diff --git a/.github/workflows/jan-astro-docs.yml b/.github/workflows/jan-astro-docs.yml index 4e28f8180..1e75e768c 100644 --- a/.github/workflows/jan-astro-docs.yml +++ b/.github/workflows/jan-astro-docs.yml @@ -14,6 +14,18 @@ on: # Review gh actions docs if you want to further define triggers, paths, etc # https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on workflow_dispatch: + inputs: + update_cloud_spec: + description: 'Update Jan Server API specification' + required: false + default: 'false' + type: choice + options: + - 'true' + - 'false' + schedule: + # Run daily at 2 AM UTC to sync with Jan Server updates + - cron: '0 2 * * *' jobs: deploy: @@ -56,9 +68,44 @@ jobs: - name: Install dependencies working-directory: website run: bun install + + - name: Update Jan Server API Spec (Scheduled/Manual) + if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.event.inputs.update_cloud_spec == 'true') + working-directory: website + continue-on-error: true + run: | + echo "📡 Updating Jan Server API specification..." + bun run generate:cloud-spec + + # Check if the spec file was updated + if git diff --quiet public/openapi/cloud-openapi.json; then + echo "✅ No changes to API specification" + else + echo "📝 API specification updated" + # Commit the changes if this is a scheduled run on main branch + if [ "${{ github.event_name }}" = "schedule" ] && [ "${{ github.ref }}" = "refs/heads/dev" ]; then + git config --local user.email "github-actions[bot]@users.noreply.github.com" + git config --local user.name "github-actions[bot]" + git add public/openapi/cloud-openapi.json + git commit -m "chore: update Jan Server API specification [skip ci]" + git push + fi + fi + env: + JAN_SERVER_SPEC_URL: ${{ secrets.JAN_SERVER_SPEC_URL || 'https://api.jan.ai/api/swagger/doc.json' }} + JAN_SERVER_PROD_URL: ${{ secrets.JAN_SERVER_PROD_URL || 'https://api.jan.ai/v1' }} - name: Build website working-directory: website - run: bun run build + run: | + # For PR and regular pushes, skip cloud spec generation in prebuild + # It will use the existing committed spec or fallback + if [ "${{ github.event_name }}" = "pull_request" ] || [ "${{ github.event_name }}" = "push" ]; then + echo "Using existing cloud spec for build" + export SKIP_CLOUD_SPEC_UPDATE=true + fi + bun run build + env: + SKIP_CLOUD_SPEC_UPDATE: ${{ github.event_name == 'pull_request' || github.event_name == 'push' }} - name: copy redirects and headers continue-on-error: true diff --git a/.github/workflows/jan-server-web-ci.yml b/.github/workflows/jan-server-web-ci.yml new file mode 100644 index 000000000..a0ec7e29c --- /dev/null +++ b/.github/workflows/jan-server-web-ci.yml @@ -0,0 +1,117 @@ +name: Jan Web Server build image and push to Harbor Registry + +on: + push: + branches: + - dev + paths: + - '.github/workflows/jan-server-web-ci.yml' + - 'core/**' + - 'web-app/**' + - 'extensions/**' + - 'extensions-web/**' + - 'Makefile' + - 'package.json' + - 'Dockerfile' + pull_request: + branches: + - dev + paths: + - '.github/workflows/jan-server-web-ci.yml' + - 'core/**' + - 'web-app/**' + - 'extensions/**' + - 'extensions-web/**' + - 'Makefile' + - 'package.json' + - 'Dockerfile' + +jobs: + build-and-preview: + runs-on: [ubuntu-24-04-docker] + permissions: + pull-requests: write + contents: write + steps: + - name: Checkout source repo + uses: actions/checkout@v4 + + - name: Login to Harbor Registry + uses: docker/login-action@v3 + with: + registry: registry.menlo.ai + username: ${{ secrets.HARBOR_USERNAME }} + password: ${{ secrets.HARBOR_PASSWORD }} + + - name: Install dependencies + run: | + (type -p wget >/dev/null || (sudo apt update && sudo apt install wget -y)) \ + && sudo mkdir -p -m 755 /etc/apt/keyrings \ + && out=$(mktemp) && wget -nv -O$out https://cli.github.com/packages/githubcli-archive-keyring.gpg \ + && cat $out | sudo tee /etc/apt/keyrings/githubcli-archive-keyring.gpg > /dev/null \ + && sudo chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg \ + && sudo mkdir -p -m 755 /etc/apt/sources.list.d \ + && echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \ + && sudo apt update + sudo apt-get install -y jq gettext + + - name: Set image tag and service name + id: vars + run: | + SERVICE_NAME=jan-server-web + if [[ "${{ github.event_name }}" == "pull_request" ]]; then + IMAGE_TAG="web:preview-${{ github.sha }}" + else + IMAGE_TAG="web:dev-${{ github.sha }}" + fi + echo "SERVICE_NAME=${SERVICE_NAME}" >> $GITHUB_OUTPUT + echo "IMAGE_TAG=${IMAGE_TAG}" >> $GITHUB_OUTPUT + echo "FULL_IMAGE=registry.menlo.ai/jan-server/${IMAGE_TAG}" >> $GITHUB_OUTPUT + + - name: Build docker image + run: | + docker build -t ${{ steps.vars.outputs.FULL_IMAGE }} . + + - name: Push docker image + run: | + docker push ${{ steps.vars.outputs.FULL_IMAGE }} + + - name: Checkout preview URL repo + if: github.event_name == 'pull_request' + uses: actions/checkout@v4 + with: + repository: menloresearch/infra-domains + token: ${{ secrets.PAT_SERVICE_ACCOUNT }} + path: preview-repo + + - name: Generate preview manifest + if: github.event_name == 'pull_request' + run: | + cd preview-repo/kubernetes + bash template/generate.sh \ + template/preview-url-template.yaml \ + preview-url/pr-${{ github.sha }}-${{ steps.vars.outputs.SERVICE_NAME }}.yaml \ + ${{ github.sha }} \ + ${{ steps.vars.outputs.SERVICE_NAME }} \ + ${{ steps.vars.outputs.FULL_IMAGE }} \ + 80 + + - name: Commit and push preview manifest + if: github.event_name == 'pull_request' + run: | + cd preview-repo + git config user.name "preview-bot" + git config user.email "preview-bot@users.noreply.github.com" + git add kubernetes/preview-url/pr-${{ github.sha }}-${{ steps.vars.outputs.SERVICE_NAME }}.yaml + git commit -m "feat(preview): add pr-${{ github.sha }}-${{ steps.vars.outputs.SERVICE_NAME }}.yaml" + git push origin main + sleep 180 + + - name: Comment preview URL on PR + if: github.event_name == 'pull_request' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + uses: mshick/add-pr-comment@v2 + with: + message: | + Preview URL: https://pr-${{ github.sha }}-${{ steps.vars.outputs.SERVICE_NAME }}.menlo.ai \ No newline at end of file diff --git a/.github/workflows/update-cloud-api-spec.yml b/.github/workflows/update-cloud-api-spec.yml new file mode 100644 index 000000000..fbb233020 --- /dev/null +++ b/.github/workflows/update-cloud-api-spec.yml @@ -0,0 +1,186 @@ +name: Update Cloud API Spec + +on: + # Manual trigger with options + workflow_dispatch: + inputs: + commit_changes: + description: 'Commit changes to repository' + required: false + default: 'true' + type: choice + options: + - 'true' + - 'false' + spec_url: + description: 'Custom API spec URL (optional)' + required: false + type: string + create_pr: + description: 'Create pull request for changes' + required: false + default: 'false' + type: choice + options: + - 'true' + - 'false' + + # Scheduled updates - runs daily at 2 AM UTC + schedule: + - cron: '0 2 * * *' + + # Can be triggered by repository dispatch (webhook from Jan Server) + repository_dispatch: + types: [update-api-spec] + +jobs: + update-spec: + name: Update Jan Server API Specification + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + + - name: Install dependencies + working-directory: website + run: bun install + + - name: Configure Git + run: | + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git config --global user.name "github-actions[bot]" + + - name: Update API Specification + id: update_spec + working-directory: website + run: | + # Set custom spec URL if provided + if [ -n "${{ github.event.inputs.spec_url }}" ]; then + export JAN_SERVER_SPEC_URL="${{ github.event.inputs.spec_url }}" + echo "📡 Using custom spec URL: $JAN_SERVER_SPEC_URL" + elif [ -n "${{ github.event.client_payload.spec_url }}" ]; then + export JAN_SERVER_SPEC_URL="${{ github.event.client_payload.spec_url }}" + echo "📡 Using webhook spec URL: $JAN_SERVER_SPEC_URL" + else + export JAN_SERVER_SPEC_URL="${{ secrets.JAN_SERVER_SPEC_URL || 'https://api.jan.ai/api/swagger/doc.json' }}" + echo "📡 Using default spec URL: $JAN_SERVER_SPEC_URL" + fi + + # Force update the spec + export FORCE_UPDATE=true + bun run generate:cloud-spec + + # Check if there are changes + if git diff --quiet public/openapi/cloud-openapi.json; then + echo "✅ No changes to API specification" + echo "has_changes=false" >> $GITHUB_OUTPUT + else + echo "📝 API specification has been updated" + echo "has_changes=true" >> $GITHUB_OUTPUT + + # Get summary of changes + echo "### Changes Summary" >> $GITHUB_STEP_SUMMARY + echo '```diff' >> $GITHUB_STEP_SUMMARY + git diff --stat public/openapi/cloud-openapi.json >> $GITHUB_STEP_SUMMARY + echo '```' >> $GITHUB_STEP_SUMMARY + fi + env: + JAN_SERVER_PROD_URL: ${{ secrets.JAN_SERVER_PROD_URL || 'https://api.jan.ai/v1' }} + JAN_SERVER_STAGING_URL: ${{ secrets.JAN_SERVER_STAGING_URL || 'https://staging-api.jan.ai/v1' }} + + - name: Create Pull Request + if: | + steps.update_spec.outputs.has_changes == 'true' && + (github.event.inputs.create_pr == 'true' || github.event_name == 'repository_dispatch') + uses: peter-evans/create-pull-request@v5 + with: + token: ${{ secrets.GITHUB_TOKEN }} + commit-message: "chore: update Jan Server API specification" + title: "chore: update Jan Server API specification" + body: | + ## 🤖 Automated API Spec Update + + This PR updates the Jan Server API specification. + + ### Trigger Information + - **Event**: ${{ github.event_name }} + - **Triggered by**: ${{ github.actor }} + - **Timestamp**: ${{ github.event.head_commit.timestamp || github.event.repository.updated_at }} + + ### What's Changed + The OpenAPI specification for Jan Server has been updated with the latest endpoints and schemas. + + ### Review Checklist + - [ ] API endpoints are correctly documented + - [ ] Authentication requirements are accurate + - [ ] Model examples are up to date + - [ ] Breaking changes are noted (if any) + + --- + *This PR was automatically generated by the API spec update workflow.* + branch: update-api-spec-${{ github.run_number }} + delete-branch: true + labels: | + documentation + api + automated + + - name: Commit and Push Changes + if: | + steps.update_spec.outputs.has_changes == 'true' && + github.event.inputs.commit_changes != 'false' && + github.event.inputs.create_pr != 'true' && + github.event_name != 'repository_dispatch' + run: | + cd website + git add public/openapi/cloud-openapi.json + git commit -m "chore: update Jan Server API specification [skip ci] + + Event: ${{ github.event_name }} + Triggered by: ${{ github.actor }}" + + # Only push to dev branch if it's a scheduled run + if [ "${{ github.event_name }}" = "schedule" ] && [ "${{ github.ref }}" = "refs/heads/dev" ]; then + git push origin HEAD:dev + echo "✅ Changes committed to dev branch" + elif [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + git push origin HEAD:${{ github.ref_name }} + echo "✅ Changes committed to ${{ github.ref_name }} branch" + else + echo "ℹ️ Changes prepared but not pushed (event: ${{ github.event_name }})" + fi + + - name: Send Notification + if: steps.update_spec.outputs.has_changes == 'true' + continue-on-error: true + run: | + echo "📬 API specification updated successfully" + + # You can add Slack/Discord notification here if needed + # Example webhook call: + # curl -X POST ${{ secrets.SLACK_WEBHOOK_URL }} \ + # -H 'Content-Type: application/json' \ + # -d '{"text": "Jan Server API spec has been updated"}' + + - name: Summary + if: always() + run: | + echo "## Workflow Summary" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "- **Status**: ${{ steps.update_spec.outputs.has_changes == 'true' && '✅ Updated' || '⏭️ No changes' }}" >> $GITHUB_STEP_SUMMARY + echo "- **Event**: ${{ github.event_name }}" >> $GITHUB_STEP_SUMMARY + echo "- **Branch**: ${{ github.ref_name }}" >> $GITHUB_STEP_SUMMARY + echo "- **Commit changes**: ${{ github.event.inputs.commit_changes || 'auto' }}" >> $GITHUB_STEP_SUMMARY + echo "- **Create PR**: ${{ github.event.inputs.create_pr || 'false' }}" >> $GITHUB_STEP_SUMMARY diff --git a/.gitignore b/.gitignore index 93e43d4d8..4b41f1c49 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,4 @@ Cargo.lock ## test test-data +llm-docs diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..d05a1f372 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,48 @@ +# Stage 1: Build stage with Node.js and Yarn v4 +FROM node:20-alpine AS builder + +# Install build dependencies +RUN apk add --no-cache \ + make \ + g++ \ + python3 \ + py3-pip \ + git + +# Enable corepack and install Yarn 4 +RUN corepack enable && corepack prepare yarn@4.5.3 --activate + +# Verify Yarn version +RUN yarn --version + +# Set working directory +WORKDIR /app + +# Copy source code +COPY ./extensions ./extensions +COPY ./extensions-web ./extensions-web +COPY ./web-app ./web-app +COPY ./Makefile ./Makefile +COPY ./.* / +COPY ./package.json ./package.json +COPY ./yarn.lock ./yarn.lock +COPY ./pre-install ./pre-install +COPY ./core ./core + +# Build web application +RUN yarn install && yarn build:core && make build-web-app + +# Stage 2: Production stage with Nginx +FROM nginx:alpine + +# Copy static files from build stage +COPY --from=builder /app/web-app/dist-web /usr/share/nginx/html + +# Copy custom nginx config +COPY nginx.conf /etc/nginx/conf.d/default.conf + +# Expose port 80 +EXPOSE 80 + +# Start nginx +CMD ["nginx", "-g", "daemon off;"] \ No newline at end of file diff --git a/LICENSE b/LICENSE index f471028db..d614b967f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,19 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ +Jan -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +Copyright 2025 Menlo Research -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright 2025 Menlo Research Pte. Ltd. +This product includes software developed by Menlo Research (https://menlo.ai). Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. +You may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +Attribution is requested in user-facing documentation and materials, where appropriate. \ No newline at end of file diff --git a/Makefile b/Makefile index 2515f8bf4..a2d5f01b4 100644 --- a/Makefile +++ b/Makefile @@ -28,13 +28,29 @@ endif yarn install yarn build:tauri:plugin:api yarn build:core - yarn build:extensions + yarn build:extensions && yarn build:extensions-web dev: install-and-build yarn download:bin yarn download:lib yarn dev +# Web application targets +install-web-app: config-yarn + yarn install + +dev-web-app: install-web-app + yarn dev:web-app + +build-web-app: install-web-app + yarn build:web-app + +serve-web-app: + yarn serve:web-app + +build-serve-web-app: build-web-app + yarn serve:web-app + # Linting lint: install-and-build yarn lint diff --git a/autoqa/checklist.md b/autoqa/checklist.md new file mode 100644 index 000000000..ebe0d1163 --- /dev/null +++ b/autoqa/checklist.md @@ -0,0 +1,264 @@ +# I. Before release + +## A. Initial update / migration Data check + +Before testing, set-up the following in the old version to make sure that we can see the data is properly migrated: +- [ ] Changing appearance / theme to something that is obviously different from default set-up +- [ ] Ensure there are a few chat threads +- [ ] Ensure there are a few favourites / star threads +- [ ] Ensure there are 2 model downloaded +- [ ] Ensure there are 2 import on local provider (llama.cpp) +- [ ] Modify MCP servers list and add some ENV value to MCP servers +- [ ] Modify Local API Server +- [ ] HTTPS proxy config value +- [ ] Add 2 custom assistants to Jan +- [ ] Create a new chat with the custom assistant +- [ ] Change the `App Data` to some other folder +- [ ] Create a Custom Provider +- [ ] Disabled some model providers +- [NEW] Change llama.cpp setting of 2 models +#### Validate that the update does not corrupt existing user data or settings (before and after update show the same information): +- [ ] Threads + - [ ] Previously used model and assistants is shown correctly + - [ ] Can resume chat in threads with the previous context +- [ ] Assistants +- Settings: + - [ ] Appearance + - [ ] MCP Servers + - [ ] Local API Server + - [ ] HTTPS Proxy +- [ ] Custom Provider Set-up + +#### In `Hub`: +- [ ] Can see model from HF listed properly +- [ ] Downloaded model will show `Use` instead of `Download` +- [ ] Toggling on `Downloaded` on the right corner show the correct list of downloaded models + +#### In `Settings -> General`: +- [ ] Ensure the `App Data` path is the same +- [ ] Click Open Logs, App Log will show + +#### In `Settings -> Model Providers`: +- [ ] Llama.cpp still listed downloaded models and user can chat with the models +- [ ] Llama.cpp still listed imported models and user can chat with the models +- [ ] Remote model still retain previously set up API keys and user can chat with model from the provider without having to re-enter API keys +- [ ] Enabled and Disabled Model Providers stay the same as before update + +#### In `Settings -> Extensions`, check that following exists: +- [ ] Conversational +- [ ] Jan Assistant +- [ ] Download Manager +- [ ] llama.cpp Inference Engine + +## B. `Settings` + +#### In `General`: +- [ ] Ensure `Community` links work and point to the correct website +- [ ] Ensure the `Check for Updates` function detect the correct latest version +- [ ] [ENG] Create a folder with un-standard character as title (e.g. Chinese character) => change the `App data` location to that folder => test that model is still able to load and run properly. +#### In `Appearance`: +- [ ] Toggle between different `Theme` options to check that they change accordingly and that all elements of the UI are legible with the right contrast: + - [ ] Light + - [ ] Dark + - [ ] System (should follow your OS system settings) +- [ ] Change the following values => close the application => re-open the application => ensure that the change is persisted across session: + - [ ] Theme + - [ ] Font Size + - [ ] Window Background + - [ ] App Main View + - [ ] Primary + - [ ] Accent + - [ ] Destructive + - [ ] Chat Width + - [ ] Ensure that when this value is changed, there is no broken UI caused by it + - [ ] Code Block + - [ ] Show Line Numbers +- [ENG] Ensure that when click on `Reset` in the `Appearance` section, it reset back to the default values +- [ENG] Ensure that when click on `Reset` in the `Code Block` section, it reset back to the default values + +#### In `Model Providers`: + +In `Llama.cpp`: +- [ ] After downloading a model from hub, the model is listed with the correct name under `Models` +- [ ] Can import `gguf` model with no error +- [ ] Imported model will be listed with correct name under the `Models` +- [ ] Check that when click `delete` the model will be removed from the list +- [ ] Deleted model doesn't appear in the selectable models section in chat input (even in old threads that use the model previously) +- [ ] Ensure that user can re-import deleted imported models +- [ ] Enable `Auto-Unload Old Models`, and ensure that only one model can run / start at a time. If there are two model running at the time of enable, both of them will be stopped. +- [ ] Disable `Auto-Unload Old Models`, and ensure that multiple models can run at the same time. +- [ ] Enable `Context Shift` and ensure that context can run for long without encountering memory error. Use the `banana test` by turn on fetch MCP => ask local model to fetch and summarize the history of banana (banana has a very long history on wiki it turns out). It should run out of context memory sufficiently fast if `Context Shift` is not enabled. +- [ ] Ensure that user can change the Jinja chat template of individual model and it doesn't affect the template of other model +- [ ] Ensure that there is a recommended `llama.cpp` for each system and that it works out of the box for users. +- [ ] [0.6.9] Take a `gguf` file and delete the `.gguf` extensions from the file name, import it into Jan and verify that it works. + +In Remote Model Providers: +- [ ] Check that the following providers are presence: + - [ ] OpenAI + - [ ] Anthropic + - [ ] Cohere + - [ ] OpenRouter + - [ ] Mistral + - [ ] Groq + - [ ] Gemini + - [ ] Hugging Face +- [ ] Models should appear as available on the selectable dropdown in chat input once some value is input in the API key field. (it could be the wrong API key) +- [ ] Once a valid API key is used, user can select a model from that provider and chat without any error. +- [ ] Delete a model and ensure that it doesn't show up in the `Modesl` list view or in the selectable dropdown in chat input. +- [ ] Ensure that a deleted model also not selectable or appear in old threads that used it. +- [ ] Adding of new model manually works and user can chat with the newly added model without error (you can add back the model you just delete for testing) +- [ ] [0.6.9] Make sure that Ollama set-up as a custom provider work with Jan +In Custom Providers: +- [ ] Ensure that user can create a new custom providers with the right baseURL and API key. +- [ ] Click `Refresh` should retrieve a list of available models from the Custom Providers. +- [ ] User can chat with the custom providers +- [ ] Ensure that Custom Providers can be deleted and won't reappear in a new session + +In general: +- [ ] Disabled Model Provider should not show up as selectable in chat input of new thread and old thread alike (old threads' chat input should show `Select Model` instead of disabled model) + +#### In `Shortcuts`: + +Make sure the following shortcut key combo is visible and works: +- [ ] New chat +- [ ] Toggle Sidebar +- [ ] Zoom In +- [ ] Zoom Out +- [ ] Send Message +- [ ] New Line +- [ ] Navigation + +#### In `Hardware`: +Ensure that the following section information show up for hardware +- [ ] Operating System +- [ ] CPU +- [ ] Memory +- [ ] GPU (If the machine has one) + - [ ] Enabling and Disabling GPUs and ensure that model still run correctly in both mode + - [ ] Enabling or Disabling GPU should not affect the UI of the application + +#### In `MCP Servers`: +- [ ] Ensure that an user can create a MCP server successfully when enter in the correct information +- [ ] Ensure that `Env` value is masked by `*` in the quick view. +- [ ] If an `Env` value is missing, there should be a error pop up. +- [ ] Ensure that deleted MCP server disappear from the `MCP Server` list without any error +- [ ] Ensure that before a MCP is deleted, it will be disable itself first and won't appear on the tool list after deleted. +- [ ] Ensure that when the content of a MCP server is edited, it will be updated and reflected accordingly in the UI and when running it. +- [ ] Toggling enable and disabled of a MCP server work properly +- [ ] A disabled MCP should not appear in the available tool list in chat input +- [ ] An disabled MCP should not be callable even when forced prompt by the model (ensure there is no ghost MCP server) +- [ ] Ensure that enabled MCP server start automatically upon starting of the application +- [ ] An enabled MCP should show functions in the available tool list +- [ ] User can use a model and call different tool from multiple enabled MCP servers in the same thread +- [ ] If `Allow All MCP Tool Permissions` is disabled, in every new thread, before a tool is called, there should be a confirmation dialog pop up to confirm the action. +- [ ] When the user click `Deny`, the tool call will not be executed and return a message indicate so in the tool call result. +- [ ] When the user click `Allow Once` on the pop up, a confirmation dialog will appear again when the tool is called next time. +- [ ] When the user click `Always Allow` on the pop up, the tool will retain permission and won't ask for confirmation again. (this applied at an individual tool level, not at the MCP server level) +- [ ] If `Allow All MCP Tool Permissions` is enabled, in every new thread, there should not be any confirmation dialog pop up when a tool is called. +- [ ] When the pop-up appear, make sure that the `Tool Parameters` is also shown with detail in the pop-up.a +- [ ] [0.6.9] Go to Enter JSON configuration when created a new MCp => paste the JSON config inside => click `Save` => server works +- [ ] [0.6.9] If individual JSON config format is failed, the MCP server should not be activated +- [ ] [0.6.9] Make sure that MCP server can be used with streamable-http transport => connect to Smithery and test MCP server + +#### In `Local API Server`: +- [ ] User can `Start Server` and chat with the default endpoint + - [ ] User should see the correct model name at `v1/models` + - [ ] User should be able to chat with it at `v1/chat/completions` +- [ ] `Open Logs` show the correct query log send to the server and return from the server +- [ ] Make sure that changing all the parameter in `Server Configuration` is reflected when `Start Server` +- [ ] [0.6.9] When the startup configuration, the last used model is also automatically start (users does not have to manually start a model before starting the server) +- [ ] [0.6.9] Make sure that you can send an image to a Local API Server and it also works (can set up Local API Server as a Custom Provider in Jan to test) + +#### In `HTTPS Proxy`: +- [ ] Model download request goes through proxy endpoint + +## C. Hub +- [ ] User can click `Download` to download a model +- [ ] User can cancel a model in the middle of downloading +- [ ] User can add a Hugging Face model detail to the list by pasting a model name / model url into the search bar and press enter +- [ ] Clicking on a listing will open up the model card information within Jan and render the HTML properly +- [ ] Clicking download work on the `Show variants` section +- [ ] Clicking download work inside the Model card HTML +- [ ] [0.6.9] Check that the model recommendation base on user hardware work as expected in the Model Hub + +## D. Threads + +#### In the left bar: +- [ ] User can delete an old thread, and it won't reappear even when app restart +- [ ] Change the title of the thread should update its last modification date and re-organise its position in the correct chronological order on the left bar. +- [ ] The title of a new thread is the first message from the user. +- [ ] Users can starred / un-starred threads accordingly +- [ ] Starred threads should move to `Favourite` section and other threads should stay in `Recent` +- [ ] Ensure that the search thread feature return accurate result based on thread titles and contents (including from both `Favourite` and `Recent`) +- [ ] `Delete All` should delete only threads in the `Recents` section +- [ ] `Unstar All` should un-star all of the `Favourites` threads and return them to `Recent` + +#### In a thread: +- [ ] When `New Chat` is clicked, the assistant is set as the last selected assistant, the model selected is set as the last used model, and the user can immediately chat with the model. +- [ ] User can conduct multi-turn conversation in a single thread without lost of data (given that `Context Shift` is not enabled) +- [ ] User can change to a different model in the middle of a conversation in a thread and the model work. +- [ ] User can click on `Regenerate` button on a returned message from the model to get a new response base on the previous context. +- [ ] User can change `Assistant` in the middle of a conversation in a thread and the new assistant setting will be applied instead. +- [ ] The chat windows can render and show all the content of a selected threads (including scroll up and down on long threads) +- [ ] Old thread retained their setting as of the last update / usage + - [ ] Assistant option + - [ ] Model option (except if the model / model provider has been deleted or disabled) +- [ ] User can send message with different type of text content (e.g text, emoji, ...) +- [ ] When request model to generate a markdown table, the table is correctly formatted as returned from the model. +- [ ] When model generate code, ensure that the code snippets is properly formatted according to the `Appearance -> Code Block` setting. +- [ ] Users can edit their old message and and user can regenerate the answer based on the new message +- [ ] User can click `Copy` to copy the model response +- [ ] User can click `Delete` to delete either the user message or the model response. +- [ ] The token speed appear when a response from model is being generated and the final value is show under the response. +- [ ] Make sure that user when using IME keyboard to type Chinese and Japanese character and they press `Enter`, the `Send` button doesn't trigger automatically after each words. +- [ ] [0.6.9] Attach an image to the chat input and see if you can chat with it using a remote model +- [ ] [0.6.9] Attach an image to the chat input and see if you can chat with it using a local model +- [ ] [0.6.9] Check that you can paste an image to text box from your system clipboard (Copy - Paste) +- [ ] [0.6.9] Make sure that user can favourite a model in the model selection in chat input + +## E. Assistants +- [ ] There is always at least one default Assistant which is Jan +- [ ] The default Jan assistant has `stream = True` by default +- [ ] User can create / edit a new assistant with different parameters and instructions choice. +- [ ] When user delete the default Assistant, the next Assistant in line will be come the default Assistant and apply their setting to new chat accordingly. +- [ ] User can create / edit assistant from within a Chat windows (on the top left) + +## F. After checking everything else + +In `Settings -> General`: +- [ ] Change the location of the `App Data` to some other path that is not the default path +- [ ] Click on `Reset` button in `Other` to factory reset the app: + - [ ] All threads deleted + - [ ] All Assistant deleted except for default Jan Assistant + - [ ] `App Data` location is reset back to default path + - [ ] Appearance reset + - [ ] Model Providers information all reset + - [ ] Llama.cpp setting reset + - [ ] API keys cleared + - [ ] All Custom Providers deleted + - [ ] MCP Servers reset + - [ ] Local API Server reset + - [ ] HTTPS Proxy reset +- [ ] After closing the app, all models are unloaded properly +- [ ] Locate to the data folder using the `App Data` path information => delete the folder => reopen the app to check that all the folder is re-created with all the necessary data. +- [ ] Ensure that the uninstallation process removes the app successfully from the system. +## G. New App Installation +- [ ] Clean up by deleting all the left over folder created by Jan + - [ ] On MacOS + - [ ] `~/Library/Application Support/Jan` + - [ ] `~/Library/Caches/jan.ai.app` + - [ ] On Windows + - [ ] `C:\Users\AppData\Roaming\Jan\` + - [ ] `C:\Users\AppData\Local\jan.ai.app` + - [ ] On Linux + - [ ] `~/.cache/Jan` + - [ ] `~/.cache/jan.ai.app` + - [ ] `~/.local/share/Jan` + - [ ] `~/.local/share/jan.ai.app` +- [ ] Ensure that the fresh install of Jan launch +- [ ] Do some basic check to see that all function still behaved as expected. To be extra careful, you can go through the whole list again. However, it is more advisable to just check to make sure that all the core functionality like `Thread` and `Model Providers` work as intended. + +# II. After release +- [ ] Check that the App Updater works and user can update to the latest release without any problem +- [ ] App restarts after the user finished an update +- [ ] Repeat section `A. Initial update / migration Data check` above to verify that update is done correctly on live version \ No newline at end of file diff --git a/docs/public/assets/images/changelog/jan-images.gif b/docs/public/assets/images/changelog/jan-images.gif new file mode 100644 index 000000000..eb7731397 Binary files /dev/null and b/docs/public/assets/images/changelog/jan-images.gif differ diff --git a/docs/public/assets/images/general/og-jan-research.jpeg b/docs/public/assets/images/general/og-jan-research.jpeg new file mode 100644 index 000000000..93abef112 Binary files /dev/null and b/docs/public/assets/images/general/og-jan-research.jpeg differ diff --git a/docs/src/pages/_meta.json b/docs/src/pages/_meta.json index 351eb454c..66d0fff38 100644 --- a/docs/src/pages/_meta.json +++ b/docs/src/pages/_meta.json @@ -9,7 +9,13 @@ }, "docs": { "type": "page", - "title": "Documentation" + "title": "Docs", + "display": "hidden" + }, + "Documentation": { + "type": "page", + "title": "Documentation", + "href": "https://docs.jan.ai" }, "platforms": { "type": "page", diff --git a/docs/src/pages/about/_assets/eniac.jpeg b/docs/src/pages/about/_assets/eniac.jpeg deleted file mode 100644 index 6facc4d04..000000000 Binary files a/docs/src/pages/about/_assets/eniac.jpeg and /dev/null differ diff --git a/docs/src/pages/about/_assets/solar-punk.webp b/docs/src/pages/about/_assets/solar-punk.webp deleted file mode 100644 index 20829fea4..000000000 Binary files a/docs/src/pages/about/_assets/solar-punk.webp and /dev/null differ diff --git a/docs/src/pages/about/_assets/solarpunk.jpeg b/docs/src/pages/about/_assets/solarpunk.jpeg deleted file mode 100644 index f00d7d43d..000000000 Binary files a/docs/src/pages/about/_assets/solarpunk.jpeg and /dev/null differ diff --git a/docs/src/pages/about/_assets/star-wars-droids.png b/docs/src/pages/about/_assets/star-wars-droids.png deleted file mode 100644 index a8dffa4c7..000000000 Binary files a/docs/src/pages/about/_assets/star-wars-droids.png and /dev/null differ diff --git a/docs/src/pages/about/_assets/vision-1.webp b/docs/src/pages/about/_assets/vision-1.webp deleted file mode 100644 index 66e41b543..000000000 Binary files a/docs/src/pages/about/_assets/vision-1.webp and /dev/null differ diff --git a/docs/src/pages/about/_meta.json b/docs/src/pages/about/_meta.json deleted file mode 100644 index 5acc0955a..000000000 --- a/docs/src/pages/about/_meta.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "about-separator": { - "title": "About Us", - "type": "separator" - }, - "index": "About", - "vision": { - "title": "Vision", - "display": "hidden" - }, - "team": "Team", - "investors": "Investors", - "wall-of-love": { - "theme": { - "toc": false, - "layout": "full" - } - }, - "acknowledgements": { - "display": "hidden" - }, - "handbook-separator": { - "title": "Handbook", - "display": "hidden" - }, - "handbook": { - "display": "hidden" - } -} diff --git a/docs/src/pages/about/handbook.mdx b/docs/src/pages/about/handbook.mdx deleted file mode 100644 index 264d6d36d..000000000 --- a/docs/src/pages/about/handbook.mdx +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Handbook -description: How we work at Jan -keywords: - [ - Jan, - Customizable Intelligence, LLM, - local AI, - privacy focus, - free and open source, - private and offline, - conversational AI, - no-subscription fee, - large language models, - build in public, - remote team, - how we work, - ] ---- - -# How We Work - -Jan operates on open-source principles, giving everyone the freedom to adjust, personalize, and contribute to its development. Our focus is on creating a community-powered ecosystem that prioritizes transparency, customization, and user privacy. For more on our principles, visit our [About page](https://jan.ai/about). - -## Open-Source - -We embrace open development, showcasing our progress and upcoming features on GitHub, and we encourage your input and contributions: - -- [Jan Framework](https://github.com/menloresearch/jan) (AGPLv3) -- [Jan Desktop Client & Local server](https://jan.ai) (AGPLv3, built on Jan Framework) -- [Nitro: run Local AI](https://github.com/menloresearch/nitro) (AGPLv3) - -## Build in Public - -We use GitHub to build in public and welcome anyone to join in. - -- [Jan's Kanban](https://github.com/orgs/menloresearch/projects/5) -- [Jan's Roadmap](https://github.com/orgs/menloresearch/projects/5/views/29) - -## Collaboration - -Our team spans the globe, working remotely to bring Jan to life. We coordinate through Discord and GitHub, valuing asynchronous communication and minimal, purposeful meetings. For collaboration and brainstorming, we utilize tools like [Excalidraw](https://excalidraw.com/) and [Miro](https://miro.com/), ensuring alignment and shared vision through visual storytelling and detailed documentation on [HackMD](https://hackmd.io/). - -Check out the [Jan Framework](https://github.com/menloresearch/jan) and our desktop client & local server at [jan.ai](https://jan.ai), both licensed under AGPLv3 for maximum openness and user freedom. diff --git a/docs/src/pages/about/handbook/_meta.json b/docs/src/pages/about/handbook/_meta.json deleted file mode 100644 index 8b72b1892..000000000 --- a/docs/src/pages/about/handbook/_meta.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "strategy": { - "display": "hidden" - }, - "project-management": { - "display": "hidden" - }, - "engineering": { - "display": "hidden" - }, - "product-design": { - "display": "hidden" - }, - "analytics": { - "display": "hidden" - }, - "website-docs": { - "title": "Website & Docs", - "display": "hidden" - } -} diff --git a/docs/src/pages/about/handbook/analytics.mdx b/docs/src/pages/about/handbook/analytics.mdx deleted file mode 100644 index 5cc34209d..000000000 --- a/docs/src/pages/about/handbook/analytics.mdx +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Analytics -description: Jan's Analytics philosophy and implementation -keywords: - [ - Jan, - Customizable Intelligence, LLM, - local AI, - privacy focus, - free and open source, - private and offline, - conversational AI, - no-subscription fee, - large language models, - analytics, - ] ---- - -# Analytics - -Adhering to Jan's privacy preserving philosophy, our analytics philosophy is to get "barely-enough-to-function'. - -## What is tracked - -1. By default, Github tracks downloads and device metadata for all public GitHub repositories. This helps us troubleshoot & ensure cross-platform support. -2. Additionally, we plan to enable a `Settings` feature for users to turn off all tracking. diff --git a/docs/src/pages/about/handbook/engineering.mdx b/docs/src/pages/about/handbook/engineering.mdx deleted file mode 100644 index 3038ead76..000000000 --- a/docs/src/pages/about/handbook/engineering.mdx +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Engineering -description: Jan is a ChatGPT-alternative that runs on your own computer, with a local API server. -keywords: - [ - Jan, - Customizable Intelligence, LLM, - local AI, - privacy focus, - free and open source, - private and offline, - conversational AI, - no-subscription fee, - large language models, - ] ---- - -# Engineering - -## Prerequisites - -- [Requirements](https://github.com/menloresearch/jan?tab=readme-ov-file#requirements-for-running-jan) -- [Setting up local env](https://github.com/menloresearch/jan?tab=readme-ov-file#contributing) diff --git a/docs/src/pages/about/handbook/engineering/_meta.json b/docs/src/pages/about/handbook/engineering/_meta.json deleted file mode 100644 index 06699fe56..000000000 --- a/docs/src/pages/about/handbook/engineering/_meta.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "ci-cd": "CI & CD", - "qa": "QA" -} diff --git a/docs/src/pages/about/handbook/engineering/ci-cd.mdx b/docs/src/pages/about/handbook/engineering/ci-cd.mdx deleted file mode 100644 index 44d389b85..000000000 --- a/docs/src/pages/about/handbook/engineering/ci-cd.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: CI & CD ---- - -import { Callout } from 'nextra/components' - -# CI & CD - -Previously we were trunk based. Now we use the following Gitflow: - -TODO: @van to include her Mermaid diagram diff --git a/docs/src/pages/about/handbook/engineering/qa.mdx b/docs/src/pages/about/handbook/engineering/qa.mdx deleted file mode 100644 index 2def2a4f5..000000000 --- a/docs/src/pages/about/handbook/engineering/qa.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: QA -description: Jan is a ChatGPT-alternative that runs on your own computer, with a local API server. -keywords: - [ - Jan, - Customizable Intelligence, LLM, - local AI, - privacy focus, - free and open source, - private and offline, - conversational AI, - no-subscription fee, - large language models, - ] ---- - -# QA - -## Phase 1: Planning - -### Definition of Ready (DoR): - -- **Scope Defined:** The features to be implemented are clearly defined and scoped out. -- **Requirements Gathered:** Gather and document all the necessary requirements for the feature. -- **Stakeholder Input:** Ensure relevant stakeholders have provided input on the document scope and content. - -### Definition of Done (DoD): - -- **Document Complete:** All sections of the document are filled out with relevant information. -- **Reviewed by Stakeholders:** The document has been reviewed and approved by stakeholders. -- **Ready for Development:** The document is in a state where developers can use it to begin implementation. - -## Phase 2: Development - -### Definition of Ready (DoR): - -- **Task Breakdown:** The development team has broken down tasks based on the document. -- **Communication Plan:** A plan is in place for communication between developers and writers if clarification is needed during implementation. -- **Developer Understanding:** Developers have a clear understanding of the document content. - -### Definition of Done (DoD): - -- **Code Implementation:** The feature is implemented according to the document specifications. -- **Developer Testing:** - - Unit tests and basic integration tests are completed - - Developer also completed self-testing for the feature (please add this as a comment in the ticket, with the tested OS and as much info as possible to reduce overlaping effort). - - (AC -> Code Changes -> Impacted scenarios) -- **Communication with Writers:** Developers have communicated any changes or challenges to the writers, and necessary adjustments are made in the document. (Can be through a note in the PR of the feature for writers to take care, or create a separate PR with the change you made for the docs, for writers to review) - -## Phase 3: QA for feature - -### Definition of Ready (DoR): - -- **Test Note Defined:** The test note is prepared outlining the testing items. -- **Environment Ready:** PR merged to nightly build, Nightly build notes updated (automatically from pipeline after merged). -- **Status:** Ticket moved to the column Testing and assigning to QA/writers to review. -- **Test Data Prepared:** Relevant test data is prepared for testing the scenarios. - -### Definition of Done (DoD): - -- **Test Executed:** All identified test items are executed on different OS, along with exploratory testing. -- **Defects Logged:** Any defects found during testing are resolved / appropriately logged (and approved for future fix). -- **Test Sign-Off:** QA team provides sign-off indicating the completion of testing. - -## Phase 4: Release (DoR) - -- **Pre-release wait time:** Code change to pre-release version should be frozen for at least X (hrs/days) for Regression testing purpose. - - Pre-release cut off on Thu morning for the team to regression test. - - Release to production (Stable) during working hour on Mon morning (if no blocker) or Tue morning. - - During the release cut off, the nightly build will be paused, to leave room for pre-release build. The build version used for regression test will be notified. -- **Pre-release testing:** A review of the implemented feature has been conducted, a long with regression test (check-list) by the team. - - Release checklist cloned from the templat for different OS (with hackMD link) - - New key test items from new feature added to the checklist. - - Split 3 OS to different team members for testing. -- **Document Updated:** The document is updated based on the review and feedback on any discrepancies or modification needed for this release. -- **Reviewed by Stakeholders:** New feature and the updated document is reviewed and approved by stakeholders. The document is in its final version, reflecting the implemented feature accurately. - -## Notes (WIP) - -- **API collection run:** to run along with nightly build daily, for critical API validation -- **Automation run:** for regression testing purpose, to reduce manual testing effort for the same items each release on multiple OS. diff --git a/docs/src/pages/about/handbook/product-design.mdx b/docs/src/pages/about/handbook/product-design.mdx deleted file mode 100644 index c0d0c10fa..000000000 --- a/docs/src/pages/about/handbook/product-design.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Product & Design -description: How we work on product design -keywords: - [ - Jan, - Customizable Intelligence, LLM, - local AI, - privacy focus, - free and open source, - private and offline, - conversational AI, - no-subscription fee, - large language models, - product design, - ] ---- - -# Product & Design - -## Roadmap - -- Conversations over Tickets - - Discord's #roadmap channel - - Work with the community to turn conversations into Product Specs -- Future System? - - Use Canny? diff --git a/docs/src/pages/about/handbook/project-management.mdx b/docs/src/pages/about/handbook/project-management.mdx deleted file mode 100644 index d6c64318d..000000000 --- a/docs/src/pages/about/handbook/project-management.mdx +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Project Management -description: Project management at Jan -keywords: - [ - Jan, - Customizable Intelligence, LLM, - local AI, - privacy focus, - free and open source, - private and offline, - conversational AI, - no-subscription fee, - large language models, - project management, - ] ---- - -import { Callout } from 'nextra/components' - -# Project Management - -We use the [Jan Monorepo Project](https://github.com/orgs/menloresearch/projects/5) in Github to manage our roadmap and sprint Kanbans. - -As much as possible, everyone owns their respective `epics` and `tasks`. - - - We aim for a `loosely coupled, but tightly aligned` autonomous culture. - - -## Quicklinks - -- [High-level roadmap](https://github.com/orgs/menloresearch/projects/5/views/16): view used at at strategic level, for team wide alignment. Start & end dates reflect engineering implementation cycles. Typically product & design work preceeds these timelines. -- [Standup Kanban](https://github.com/orgs/menloresearch/projects/5/views/25): view used during daily standup. Sprints should be up to date. - -## Organization - -[`Roadmap Labels`](https://github.com/menloresearch/jan/labels?q=roadmap) - -- `Roadmap Labels` tag large, long-term, & strategic projects that can span multiple teams and multiple sprints -- Example label: `roadmap: Jan has Mobile` -- `Roadmaps` contain `epics` - -[`Epics`](https://github.com/menloresearch/jan/issues?q=is%3Aissue+is%3Aopen+label%3A%22type%3A+epic%22) - -- `Epics` track large stories that span 1-2 weeks, and it outlines specs, architecture decisions, designs -- `Epics` contain `tasks` -- `Epics` should always have 1 owner - -[`Milestones`](https://github.com/menloresearch/jan/milestones) - -- `Milestones` track release versions. We use [semantic versioning](https://semver.org/) -- `Milestones` span ~2 weeks and have deadlines -- `Milestones` usually fit within 2-week sprint cycles - -[`Tasks`](https://github.com/menloresearch/jan/issues) - -- Tasks are individual issues (feats, bugs, chores) that can be completed within a few days -- Tasks, except for critical bugs, should always belong to an `epic` (and thus fit into our roadmap) -- Tasks are usually named per [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/#summary) -- Tasks should always have 1 owner - -We aim to always sprint on `tasks` that are a part of the [current roadmap](https://github.com/orgs/menloresearch/projects/5/views/16). - -## Kanban - -- `no status`: issues that need to be triaged (needs an owner, ETA) -- `icebox`: issues you don't plan to tackle yet -- `planned`: issues you plan to tackle this week -- `in-progress`: in progress -- `in-review`: pending PR or blocked by something -- `done`: done - -## Triage SOP - -- `Urgent bugs`: assign to an owner (or @engineers if you are not sure) && tag the current `sprint` & `milestone` -- `All else`: assign the correct roadmap `label(s)` and owner (if any) - -### Request for help - -As a result, our feature prioritization can feel a bit black box at times. - -We'd appreciate high quality insights and volunteers for user interviews through [Discord](https://discord.gg/af6SaTdzpx) and [Github](https://github.com/menloresearch). diff --git a/docs/src/pages/about/handbook/strategy.mdx b/docs/src/pages/about/handbook/strategy.mdx deleted file mode 100644 index f2ce62387..000000000 --- a/docs/src/pages/about/handbook/strategy.mdx +++ /dev/null @@ -1,51 +0,0 @@ -# Strategy - -We only have 2 planning parameters: - -- 10 year vision -- 2 week sprint -- Quarterly OKRs - -## Ideal Customer - -Our ideal customer is an AI enthusiast or business who has experienced some limitations with current AI solutions and is keen to find open source alternatives. - -## Problems - -Our ideal customer would use Jan to solve one of these problems. - -_Control_ - -- Control (e.g. preventing vendor lock-in) -- Stability (e.g. runs predictably every time) -- Local-use (e.g. for speed, or for airgapped environments) - -_Privacy_ - -- Data protection (e.g. personal data or company data) -- Privacy (e.g. nsfw) - -_Customisability_ - -- Tinkerability (e.g. ability to change model, experiment) -- Niche Models (e.g. fine-tuned, domain-specific models that outperform OpenAI) - -Sources: [^1] [^2] [^3] [^4] - -[^1]: [What are you guys doing that can't be done with ChatGPT?](https://www.reddit.com/r/LocalLLaMA/comments/17mghqr/comment/k7ksti6/?utm_source=share&utm_medium=web2x&context=3) -[^2]: [What's your main interest in running a local LLM instead of an existing API?](https://www.reddit.com/r/LocalLLaMA/comments/1718a9o/whats_your_main_interest_in_running_a_local_llm/) -[^3]: [Ask HN: What's the best self-hosted/local alternative to GPT-4?](https://news.ycombinator.com/item?id=36138224) -[^4]: [LoRAs](https://www.reddit.com/r/LocalLLaMA/comments/17mghqr/comment/k7mdz1i/?utm_source=share&utm_medium=web2x&context=3) - -## Solution - -Jan is a seamless user experience that runs on your personal computer, that glues the different pieces of the open source AI ecosystem to provide an alternative to OpenAI's closed platform. - -- We build a comprehensive, seamless platform that takes care of the technical chores across the stack required to run open source AI -- We run on top of a local folder of non-proprietary files, that anyone can tinker with (yes, even other apps!) -- We provide open formats for packaging and distributing AI to run reproducibly across devices - -## Prerequisites - -- [Figma](https://figma.com) -- [ScreenStudio](https://www.screen.studio/) diff --git a/docs/src/pages/about/handbook/website-docs.mdx b/docs/src/pages/about/handbook/website-docs.mdx deleted file mode 100644 index 773fcceea..000000000 --- a/docs/src/pages/about/handbook/website-docs.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: Website & Docs -description: Information about the Jan website and documentation. -keywords: - [ - Jan, - Customizable Intelligence, LLM, - local AI, - privacy focus, - free and open source, - private and offline, - conversational AI, - no-subscription fee, - large language models, - website, - documentation, - ] ---- - -# Website & Docs - -This website is built using [Docusaurus 3.0](https://docusaurus.io/), a modern static website generator. - -## Information Architecture - -We try to **keep routes consistent** to maintain SEO. - -- **`/guides/`**: Guides on how to use the Jan application. For end users who are directly using Jan. - -- **`/developer/`**: Developer docs on how to extend Jan. These pages are about what people can build with our software. - -- **`/api-reference/`**: Reference documentation for the Jan API server, written in Swagger/OpenAPI format. - -- **`/changelog/`**: A list of changes made to the Jan application with each release. - -- **`/blog/`**: A blog for the Jan application. - -## How to Contribute - -Refer to the [Contributing Guide](https://github.com/menloresearch/jan/blob/dev/CONTRIBUTING.md) for more comprehensive information on how to contribute to the Jan project. - -## Pre-requisites and Installation - -- [Node.js](https://nodejs.org/en/) (version 20.0.0 or higher) -- [yarn](https://yarnpkg.com/) (version 1.22.0 or higher) - -### Installation - -```bash -cd jan/docs -``` - -```bash -yarn install && yarn start -``` - -This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. - -### Build - -```bash -yarn build -``` - -This command generates static content into the `build` directory and can be served using any static contents hosting service. - -### Deployment - -Using SSH: - -```bash -USE_SSH=true yarn deploy -``` - -Not using SSH: - -```bash -GIT_USER= yarn deploy -``` - -If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. - -### Preview URL, Pre-release and Publishing Documentation - -- When a pull request is created, the preview URL will be automatically commented on the pull request. - -- The documentation will then be published to [https://dev.jan.ai/](https://dev.jan.ai/) when the pull request is merged to `main`. - -- Our open-source maintainers will sync the updated content from `main` to `release` branch, which will then be published to [https://jan.ai/](https://jan.ai/). diff --git a/docs/src/pages/about/index.mdx b/docs/src/pages/about/index.mdx deleted file mode 100644 index 05997eda2..000000000 --- a/docs/src/pages/about/index.mdx +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Menlo Research -description: We are Menlo Research, the creators and maintainers of Jan, Cortex and other tools. -keywords: - [ - Menlo Research, - Jan, - local AI, - open-source alternative to chatgpt, - alternative to openai platform, - privacy focus, - free and open source, - private and offline, - conversational AI, - no-subscription fee, - large language models, - about Jan, - desktop application, - thinking machines, - ] ---- - -import { Callout } from 'nextra/components' - -# Menlo Research - -![Eniac](./_assets/eniac.jpeg) -_[Eniac](https://www.computerhistory.org/revolution/birth-of-the-computer/4/78), the World's First Computer (Photo courtesy of US Army)_ - -## About - -We're a team of AI researchers and engineers. We are the creators and lead maintainers of a few open-source AI tools: - -- 👋 [Jan](https://jan.ai): ChatGPT-alternative that runs 100% offline -- 🤖 [Cortex](https://cortex.so/docs/): A simple, embeddable library to run LLMs locally -- More to come! - - -The [Menlo Research](https://en.wikipedia.org/wiki/Homebrew_Computer_Club) was an early computer hobbyist group from 1975 to 1986 that led to Apple and the personal computer revolution. - - -### Mission - -We're a robotics company that focuses on the cognitive framework for future robots. Our long-term mission is to advance human-machine collaboration to enable human civilization to thrive. - -### Business Model - -We're currently a bootstrapped startup [^2]. We balance technical invention with the search for a sustainable business model (e.g., consulting, paid support, and custom development). - - -We welcome business inquiries: 👋 hello@jan.ai - - -### Community - -We have a thriving community built around [Jan](../docs), where we also discuss our other projects. - -- [Discord](https://discord.gg/AAGQNpJQtH) -- [Twitter](https://twitter.com/jandotai) -- [LinkedIn](https://www.linkedin.com/company/menloresearch) -- Email: hello@jan.ai - -## Philosophy - -[Menlo](https://menlo.ai/handbook/about) is an open R&D lab in pursuit of General Intelligence, that achieves real-world impact through agents and robots. - -### 🔑 User Owned - -We build tools that are user-owned. Our products are [open-source](https://en.wikipedia.org/wiki/Open_source), designed to run offline or be [self-hosted.](https://www.reddit.com/r/selfhosted/) We make no attempt to lock you in, and our tools are free of [user-hostile dark patterns](https://twitter.com/karpathy/status/1761467904737067456?t=yGoUuKC9LsNGJxSAKv3Ubg) [^1]. - -We adopt [Local-first](https://www.inkandswitch.com/local-first/) principles and store data locally in [universal file formats](https://stephango.com/file-over-app). We build for privacy by default, and we do not [collect or sell your data](/privacy). - -### 🔧 Right to Tinker - -We believe in the [Right to Repair](https://en.wikipedia.org/wiki/Right_to_repair). We encourage our users to take it further by [tinkering, extending, and customizing](https://www.popularmechanics.com/technology/gadgets/a4395/pm-remembers-steve-jobs-how-his-philosophy-changed-technology-6507117/) our products to fit their needs. - -Our products are designed with [Extension APIs](/docs/extensions), and we do our best to write good [documentation](/docs) so users understand how things work under the hood. - -### 👫 Build with the Community - -We are part of a larger open-source community and are committed to being a good jigsaw puzzle piece. We credit and actively contribute to upstream projects. - -We adopt a public-by-default approach to [Project Management](https://github.com/orgs/menloresearch/projects/30/views/1), [Roadmaps](https://github.com/orgs/menloresearch/projects/30/views/4), and Helpdesk for our products. - -## Inspirations - -> Good artists borrow, great artists steal - Picasso - -We are inspired by and actively try to emulate the paths of companies we admire ❤️: - -- [Posthog](https://posthog.com/handbook) -- [Obsidian](https://obsidian.md/) -- [Discourse](https://www.discourse.org/about) -- [Gitlab](https://handbook.gitlab.com/handbook/company/history/#2017-gitlab-storytime) -- [Red Hat](https://www.redhat.com/en/about/development-model) -- [Ghost](https://ghost.org/docs/contributing/) -- [Lago](https://www.getlago.com/blog/open-source-licensing-and-why-lago-chose-agplv3) -- [Twenty](https://twenty.com/story) - -## Footnotes - -[^1]: [Kaparthy's Love Letter to Obsidian](https://twitter.com/karpathy/status/1761467904737067456?t=yGoUuKC9LsNGJxSAKv3Ubg) - -[^2]: [The Market for AI Companies](https://www.artfintel.com/p/the-market-for-ai-companies) by Finbarr Timbers diff --git a/docs/src/pages/about/investors.mdx b/docs/src/pages/about/investors.mdx deleted file mode 100644 index a24062540..000000000 --- a/docs/src/pages/about/investors.mdx +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Investors -description: Our unique, unconventional approach to distributing ownership -keywords: [ - ESOP, - Thinking Machines, - Jan, - Jan.ai, - Jan AI, - cortex, -] ---- - -# Investors - -We are a [bootstrapped company](https://en.wikipedia.org/wiki/Bootstrapping), and don't have any external investors (yet). - -We're open to exploring opportunities with strategic partners want to tackle [our mission](/about#mission) together. \ No newline at end of file diff --git a/docs/src/pages/about/team.mdx b/docs/src/pages/about/team.mdx deleted file mode 100644 index 96f3d14c9..000000000 --- a/docs/src/pages/about/team.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Team -description: Meet the Thinking Machines team. -keywords: - [ - Thinking Machines, - Jan, - Cortex, - jan AI, - Jan AI, - jan.ai, - cortex, - ] ---- - -import { Callout } from 'nextra/components' -import { Cards, Card } from 'nextra/components' - -# Team - -We're a small, fully-remote team, mostly based in Southeast Asia. - -We are committed to become a global company. You can check our [Careers page](https://menlo.bamboohr.com/careers) if you'd like to join us on our adventure. - -You can find our full team members on the [Menlo handbook](https://menlo.ai/handbook/team#jan). - - -Ping us in [Discord](https://discord.gg/AAGQNpJQtH) if you're keen to talk to us! - diff --git a/docs/src/pages/about/vision.mdx b/docs/src/pages/about/vision.mdx deleted file mode 100644 index 64ba612f8..000000000 --- a/docs/src/pages/about/vision.mdx +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Vision - Thinking Machines -description: We want to continue a legacy of craftsmen making tools that propel humanity forward. -keywords: - [ - Jan AI, - Thinking Machines, - Jan, - ChatGPT alternative, - local AI, - private AI, - conversational AI, - OpenAI platform alternative, - no-subscription fee, - large language model, - about Jan, - desktop application, - thinking machine, - jan vision, - ] ---- - -# Vision - -> "I do not fear computers. I fear the lack of them" - Isaac Asimov - -![Solarpunk Civilization](./_assets/solarpunk.jpeg) - -- Harmonious symbiosis of humans, nature, and machines -- Humanity has over millennia adopted tools. Fire, electricity, computers, and AI. -- AI is no different. It is a tool that can propel humanity forward. -- We reject the -- Go beyond the apocalypse narratives of Dune and Terminator, and you will find a kernel of progress - -We want to continue a legacy of craftsmen making tools that propel humanity forward. - -## Collaborating with Thinking Machines - -Our vision is to develop thinking machines that work alongside humans. - -We envision a future where AI is safely used as a tool in our daily lives, like fire and electricity. These robots enhance human potential and do not replace our key decision-making. You own your own AI. - -![jan ai shapes the future](./_assets/vision-1.webp) - -![Solarpunk Civilization](./_assets/solar-punk.webp) -> We like that Luke can just open up R2-D2 and tinker around. He was not submitting support tickets to a centralized server somewhere in the galaxy. - -## Solarpunk, not Dune - -Our vision is rooted in an optimistic view of AI's role in humanity's future. - -Like the [Solarpunk movement](https://en.wikipedia.org/wiki/Solarpunk), we envision a world where technology and nature coexist harmoniously, supporting a sustainable and flourishing ecosystem. - -We focus on AI's positive impacts on our world. From environmental conservation to the democratization of energy, AI has the potential to address some of the most pressing challenges facing our planet. - -https://www.yesmagazine.org/environment/2021/01/28/climate-change-sustainable-solarpunk \ No newline at end of file diff --git a/docs/src/pages/about/wall-of-love.mdx b/docs/src/pages/about/wall-of-love.mdx deleted file mode 100644 index 060c2c3b6..000000000 --- a/docs/src/pages/about/wall-of-love.mdx +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Wall of Love ❤️ - -description: Check out what our amazing users are saying about Jan! -keywords: - [ - Jan, - Rethink the Computer, - local AI, - privacy focus, - free and open source, - private and offline, - conversational AI, - no-subscription fee, - large language models, - wall of love, - ] ---- - -import WallOfLove from "@/components/Home/WallOfLove" - - - diff --git a/docs/src/pages/changelog/2025-08-28-image-support.mdx b/docs/src/pages/changelog/2025-08-28-image-support.mdx new file mode 100644 index 000000000..f3f6efda1 --- /dev/null +++ b/docs/src/pages/changelog/2025-08-28-image-support.mdx @@ -0,0 +1,106 @@ +--- +title: "Jan v0.6.9: Image support, stable MCP, and powerful model tools" +version: 0.6.9 +description: "Major multimodal support with image uploads, MCP out of experimental, auto-detect model capabilities, and enhanced tool calling" +date: 2025-08-28 +ogImage: "/assets/images/changelog/jan-images.gif" +--- + +import ChangelogHeader from "@/components/Changelog/ChangelogHeader" +import { Callout } from 'nextra/components' + + + +## Highlights 🎉 + +v0.6.9 delivers two highly requested features: **image support for multimodal models** and **stable MCP** (no more experimental flags!). Plus intelligent model capability detection, enhanced tool calling, and major UX improvements. + +### 🖼️ Multimodal AI is here + +**Image upload support** — Finally! Upload images directly in your chats and get visual understanding from compatible models: +- **Local models**: Automatic support for Gemma3, Qwen3, and other vision-capable models +- **Cloud models**: Manual toggle for GPT-4V, Claude 3.5 Sonnet, Gemini Pro Vision +- **Smart detection**: Jan automatically identifies which models support images +- **Privacy first**: Local models process images entirely offline + +The team has been working hard to bring this long-awaited capability to Jan, and it's been worth the wait. + +### 🔧 MCP is stable + +**Model Context Protocol** graduated from experimental to stable: +- **No more experimental flags** — MCP tools work out of the box +- **Better error handling** for smoother MCP server connections +- **Cancel tool calls** mid-execution when needed +- **Enhanced reliability** with improved server status tracking + +MCP unlocks powerful workflows: web search, code execution, productivity integrations, and more. + +### 🎯 Intelligent model management + +- **Auto-detect capabilities**: Jan identifies tool calling and vision support for local models +- **Model compatibility checker**: Hub shows hardware requirements before download +- **Favorite models**: Mark frequently used models for quick access +- **Universal GGUF import**: Import any valid .gguf file regardless of extension +- **Hardware-aware suggestions**: Get model recommendations based on your system specs + +### 🚀 Enhanced tool calling + +- **GPT-OSS models**: Upgraded llama.cpp brings tool calling to more open-source models +- **Improved performance**: Better tool execution with upgraded engine +- **Remote provider control**: Manual toggle for cloud model capabilities +- **Streamlined workflows**: Cancel operations, better error handling + +## Major Features + +### 🖼️ Multimodal support +- **Image uploads** work with compatible local and cloud models +- **Automatic detection** for local model vision capabilities +- **Manual toggle** for remote providers (GPT-4V, Claude, Gemini) +- **Privacy-preserving** local image processing + +### 🔧 Stable MCP +- **MCP Server stable release** — no more experimental flags needed +- **Enhanced error handling** for MCP connections +- **Tool cancellation** support during execution +- **Improved server status** synchronization + +### 🎯 Smart model features +- **Favorite models** — bookmark your go-to models +- **Auto-capability detection** for local models +- **Hardware compatibility** checks in Hub +- **Universal GGUF import** regardless of file extension + +### ⚡ Enhanced engine +- **Tool calling support** for GPT-OSS models +- **Upgraded llama.cpp** version with stability improvements +- **Better performance** across model types + +## Improvements + +### 🔄 API & automation +- **Auto-start API server** on Jan startup (optional) +- **Model auto-loading** when API server starts +- **Ollama endpoint** support restored for custom configurations + +### 🎨 User experience +- **Thinking windows** for OpenRouter models render correctly +- **Better error messages** across MCP operations +- **Improved import UX** with retired model cleanup +- **CPU architecture** detection at runtime + +### 🔧 Technical enhancements +- **Vulkan backend** re-enabled for integrated GPUs with sufficient memory +- **Enhanced stability** with better error handling +- **Performance optimizations** across the board + +## Thanks to our incredible team + +The engineering team delivered major features that users have been requesting for months. Image support required deep multimodal AI integration, while stabilizing MCP involved extensive testing and refinement. The auto-detection features showcase thoughtful UX design that makes AI more accessible. + +Special recognition to the contributors who made v0.6.9 possible through their dedication to bringing powerful, privacy-focused AI capabilities to everyone. + +--- + +Update your Jan or [download the latest](https://jan.ai/). + +For the complete list of changes, see the [GitHub release notes](https://github.com/janhq/jan/releases/tag/v0.6.9). diff --git a/docs/src/pages/docs/_assets/jan_loaded.png b/docs/src/pages/docs/_assets/jan_loaded.png new file mode 100644 index 000000000..cfd3b1a13 Binary files /dev/null and b/docs/src/pages/docs/_assets/jan_loaded.png differ diff --git a/docs/src/pages/docs/index.mdx b/docs/src/pages/docs/index.mdx index 9f2bd26c4..27b51f5c2 100644 --- a/docs/src/pages/docs/index.mdx +++ b/docs/src/pages/docs/index.mdx @@ -1,6 +1,6 @@ --- title: Jan -description: Build, run, and own your AI. From laptop to superintelligence. +description: Working towards open superintelligence through community-driven AI keywords: [ Jan, @@ -28,56 +28,116 @@ import FAQBox from '@/components/FaqBox' ## Jan's Goal -> Jan's goal is to build superintelligence that you can self-host and use locally. +> We're working towards open superintelligence to make a viable open-source alternative to platforms like ChatGPT +and Claude that anyone can own and run. -## What is Jan? +## What is Jan Today -Jan is an open-source AI ecosystem that runs on your hardware. We're building towards open superintelligence - a complete AI platform you actually own. +Jan is an open-source AI platform that runs on your hardware. We believe AI should be in the hands of many, not +controlled by a few tech giants. -### The Ecosystem +Today, Jan is: +- **A desktop app** that runs AI models locally or connects to cloud providers +- **A model hub** making the latest open-source models accessible +- **A connector system** that lets AI interact with real-world tools via MCP -**Models**: We build specialized models for real tasks, not general-purpose assistants: -- **Jan-Nano (32k/128k)**: 4B parameters designed for deep research with MCP. The 128k version processes entire papers, codebases, or legal documents in one go -- **Lucy**: 1.7B model that runs agentic web search on your phone. Small enough for CPU, smart enough for complex searches -- **Jan-v1**: 4B model for agentic reasoning and tool use, achieving 91.1% on SimpleQA +Tomorrow, Jan aims to be a complete ecosystem where open models rival or exceed closed alternatives. -We also integrate the best open-source models - from OpenAI's gpt-oss to community GGUF models on Hugging Face. The goal: make powerful AI accessible to everyone, not just those with server farms. - -**Applications**: Jan Desktop runs on your computer today. Web, mobile, and server versions coming in late 2025. Everything syncs, everything works together. - -**Tools**: Connect to the real world through [Model Context Protocol (MCP)](./mcp). Design with Canva, analyze data in Jupyter notebooks, control browsers, execute code in E2B sandboxes. Your AI can actually do things, not just talk about them. - - -API keys are optional. No account needed. Just download and run. Bring your own API keys to connect your favorite cloud models. + +We're building this with the open-source AI community, using the best available tools, and sharing everything +we learn along the way. -### Core Features +## The Jan Ecosystem -- **Run Models Locally**: Download any GGUF model from Hugging Face, use OpenAI's gpt-oss models, or connect to cloud providers -- **OpenAI-Compatible API**: Local server at `localhost:1337` works with tools like [Continue](./server-examples/continue-dev) and [Cline](https://cline.bot/) -- **Extend with MCP Tools**: Browser automation, web search, data analysis, design tools - all through natural language -- **Your Choice of Infrastructure**: Run on your laptop, self-host on your servers (soon), or use cloud when you need it +### Jan Apps +**Available Now:** +- **Desktop**: Full-featured AI workstation for Windows, Mac, and Linux -### Growing MCP Integrations +**Coming Late 2025:** +- **Mobile**: Jan on your phone +- **Web**: Browser-based access at jan.ai +- **Server**: Self-hosted for teams +- **Extensions**: Browser extension for Chrome-based browsers -Jan connects to real tools through MCP: -- **Creative Work**: Generate designs with Canva -- **Data Analysis**: Execute Python in Jupyter notebooks -- **Web Automation**: Control browsers with Browserbase and Browser Use -- **Code Execution**: Run code safely in E2B sandboxes -- **Search & Research**: Access current information via Exa, Perplexity, and Octagon -- **More coming**: The MCP ecosystem is expanding rapidly +### Jan Model Hub +Making open-source AI accessible to everyone: +- **Easy Downloads**: One-click model installation +- **Jan Models**: Our own models optimized for local use + - **Jan-v1**: 4B reasoning model specialized in web search + - **Research Models** + - **Jan-Nano (32k/128k)**: 4B model for web search with MCP tools + - **Lucy**: 1.7B mobile-optimized for web search +- **Community Models**: Any GGUF from Hugging Face works in Jan +- **Cloud Models**: Connect your API keys for OpenAI, Anthropic, Gemini, and more + + +### Jan Connectors Hub +Connect AI to the tools you use daily via [Model Context Protocol](./mcp): + +**Creative & Design:** +- **Canva**: Generate and edit designs + +**Data & Analysis:** +- **Jupyter**: Run Python notebooks +- **E2B**: Execute code in sandboxes + +**Web & Search:** +- **Browserbase & Browser Use**: Browser automation +- **Exa, Serper, Perplexity**: Advanced web search +- **Octagon**: Deep research capabilities + +**Productivity:** +- **Linear**: Project management +- **Todoist**: Task management + +## Core Features + +- **Run Models Locally**: Download any GGUF model from Hugging Face, use OpenAI's gpt-oss models, +or connect to cloud providers +- **OpenAI-Compatible API**: Local server at `localhost:1337` works with tools like +[Continue](./server-examples/continue-dev) and [Cline](https://cline.bot/) +- **Extend with MCP Tools**: Browser automation, web search, data analysis, and design tools, all +through natural language +- **Your Choice of Infrastructure**: Run on your laptop, self-host on your servers (soon), or use +cloud when you need it ## Philosophy Jan is built to be user-owned: -- **Open Source**: Apache 2.0 license - truly free +- **Open Source**: Apache 2.0 license - **Local First**: Your data stays on your device. Internet is optional - **Privacy Focused**: We don't collect or sell user data. See our [Privacy Policy](./privacy) - **No Lock-in**: Export your data anytime. Use any model. Switch between local and cloud - -We're building AI that respects your choices. Not another wrapper around someone else's API. + +The best AI is the one you control. Not the one that others control for you. + + +## The Path Forward + +### What Works Today +- Run powerful models locally on consumer hardware +- Connect to any cloud provider with your API keys +- Use MCP tools for real-world tasks +- Access transparent model evaluations + +### What We're Building +- More specialized models that excel at specific tasks +- Expanded app ecosystem (mobile, web, extensions) +- Richer connector ecosystem +- An evaluation framework to build better models + +### The Long-Term Vision +We're working towards open superintelligence where: +- Open models match or exceed closed alternatives +- Anyone can run powerful AI on their own hardware +- The community drives innovation, not corporations +- AI capabilities are owned by users, not rented + + +This is an ambitious goal without a guaranteed path. We're betting on the open-source community, improved +hardware, and better techniques, but we're honest that this is a journey, not a destination we've reached. ## Quick Start @@ -85,7 +145,7 @@ We're building AI that respects your choices. Not another wrapper around someone 1. [Download Jan](./quickstart) for your operating system 2. Choose a model - download locally or add cloud API keys 3. Start chatting or connect tools via MCP -4. Build with our [API](https://jan.ai/api-reference) +4. Build with our [local API](./api-server) ## Acknowledgements @@ -97,7 +157,7 @@ Jan is built on the shoulders of giants: ## FAQs - Jan is an open-source AI ecosystem building towards superintelligence you can self-host. Today it's a desktop app that runs AI models locally. Tomorrow it's a complete platform across all your devices. + Jan is an open-source AI platform working towards a viable alternative to Big Tech AI. Today it's a desktop app that runs models locally or connects to cloud providers. Tomorrow it aims to be a complete ecosystem rivaling platforms like ChatGPT and Claude. @@ -106,14 +166,14 @@ Jan is built on the shoulders of giants: **Jan Models:** - - Jan-Nano (32k/128k) - Deep research with MCP integration - - Lucy - Mobile-optimized agentic search (1.7B) - - Jan-v1 - Agentic reasoning and tool use (4B) - + - Jan-Nano (32k/128k) - Research and analysis with MCP integration + - Lucy - Mobile-optimized search (1.7B) + - Jan-v1 - Reasoning and tool use (4B) + **Open Source:** - OpenAI's gpt-oss models (120b and 20b) - Any GGUF model from Hugging Face - + **Cloud (with your API keys):** - OpenAI, Anthropic, Mistral, Groq, and more @@ -130,15 +190,27 @@ Jan is built on the shoulders of giants: **Hardware**: - Minimum: 8GB RAM, 10GB storage - - Recommended: 16GB RAM, GPU (NVIDIA/AMD/Intel), 50GB storage - - Works with: NVIDIA (CUDA), AMD (Vulkan), Intel Arc, Apple Silicon + - Recommended: 16GB RAM, GPU (NVIDIA/AMD/Intel/Apple), 50GB storage + + + + Honestly? It's ambitious and uncertain. We believe the combination of rapidly improving open models, better consumer hardware, community innovation, and specialized models working together can eventually rival closed platforms. But this is a multi-year journey with no guarantees. What we can guarantee is that we'll keep building in the open, with the community, towards this goal. + + + + Right now, Jan can: + - Run models like Llama, Mistral, and our own Jan models locally + - Connect to cloud providers if you want more power + - Use MCP tools to create designs, analyze data, browse the web, and more + - Work completely offline once models are downloaded + - Provide an OpenAI-compatible API for developers **Local use**: Always free, no catches **Cloud models**: You pay providers directly (we add no markup) **Jan cloud**: Optional paid services coming 2025 - + The core platform will always be free and open source. @@ -161,7 +233,7 @@ Jan is built on the shoulders of giants: - **Jan Web**: Beta late 2025 - **Jan Mobile**: Late 2025 - **Jan Server**: Late 2025 - + All versions will sync seamlessly. @@ -174,4 +246,4 @@ Jan is built on the shoulders of giants: Yes! We love hiring from our community. Check [Careers](https://menlo.bamboohr.com/careers). - \ No newline at end of file + diff --git a/docs/src/pages/docs/quickstart.mdx b/docs/src/pages/docs/quickstart.mdx index 813b2529a..b9a923b57 100644 --- a/docs/src/pages/docs/quickstart.mdx +++ b/docs/src/pages/docs/quickstart.mdx @@ -47,30 +47,13 @@ We recommend starting with **Jan v1**, our 4B parameter model optimized for reas Jan v1 achieves 91.1% accuracy on SimpleQA and excels at tool calling, making it perfect for web search and reasoning tasks. -**HuggingFace models:** Some require an access token. Add yours in **Settings > Model Providers > Llama.cpp > Hugging Face Access Token**. - -![Add HF Token](./_assets/hf_token.png) - -### Step 3: Enable GPU Acceleration (Optional) - -For Windows/Linux with compatible graphics cards: - -1. Go to **() Settings** > **Hardware** -2. Toggle **GPUs** to ON - -![Turn on GPU acceleration](./_assets/gpu_accl.png) - - -Install required drivers before enabling GPU acceleration. See setup guides for [Windows](/docs/desktop/windows#gpu-acceleration) & [Linux](/docs/desktop/linux#gpu-acceleration). - - -### Step 4: Start Chatting +### Step 3: Start Chatting 1. Click **New Chat** () icon 2. Select your model in the input field dropdown 3. Type your message and start chatting -![Create New Thread](./_assets/threads-new-chat-updated.png) +![Create New Thread](./_assets/jan_loaded.png) Try asking Jan v1 questions like: - "Explain quantum computing in simple terms" @@ -118,7 +101,7 @@ Thread deletion is permanent. No undo available. **All threads:** 1. Hover over `Recents` category -2. Click **three dots** () icon +2. Click **three dots** () icon 3. Select **Delete All** ## Advanced Features diff --git a/docs/src/pages/docs/threads.mdx b/docs/src/pages/docs/threads.mdx deleted file mode 100644 index 85d4bcf7c..000000000 --- a/docs/src/pages/docs/threads.mdx +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Start Chatting -description: Download models and manage your conversations with AI models locally. -keywords: - [ - Jan, - local AI, - LLM, - chat, - threads, - models, - download, - installation, - conversations, - ] ---- - -import { Callout, Steps } from 'nextra/components' -import { SquarePen, Pencil, Ellipsis, Paintbrush, Trash2, Settings } from 'lucide-react' - -# Start Chatting - - - -### Step 1: Install Jan - -1. [Download Jan](/download) -2. Install the app ([Mac](/docs/desktop/mac), [Windows](/docs/desktop/windows), [Linux](/docs/desktop/linux)) -3. Launch Jan - -### Step 2: Download a Model - -Jan requires a model to chat. Download one from the Hub: - -1. Go to the **Hub Tab** -2. Browse available models (must be GGUF format) -3. Select one matching your hardware specs -4. Click **Download** - -![Download a Model](./_assets/model-management-01.png) - - -Models consume memory and processing power. Choose based on your hardware specs. - - -**HuggingFace models:** Some require an access token. Add yours in **Settings > Model Providers > Llama.cpp > Hugging Face Access Token**. - -![Add HF Token](./_assets/hf_token.png) - -### Step 3: Enable GPU Acceleration (Optional) - -For Windows/Linux with compatible graphics cards: - -1. Go to **() Settings** > **Hardware** -2. Toggle **GPUs** to ON - -![Turn on GPU acceleration](./_assets/gpu_accl.png) - - -Install required drivers before enabling GPU acceleration. See setup guides for [Windows](/docs/desktop/windows#gpu-acceleration) & [Linux](/docs/desktop/linux#gpu-acceleration). - - -### Step 4: Start Chatting - -1. Click **New Chat** () icon -2. Select your model in the input field dropdown -3. Type your message and start chatting - -![Create New Thread](./_assets/threads-new-chat-updated.png) - - - -## Managing Conversations - -Jan organizes conversations into threads for easy tracking and revisiting. - -### View Chat History - -- **Left sidebar** shows all conversations -- Click any chat to open the full conversation -- **Favorites**: Pin important threads for quick access -- **Recents**: Access recently used threads - -![Favorites and Recents](./_assets/threads-favorites-and-recents-updated.png) - -### Edit Chat Titles - -1. Hover over a conversation in the sidebar -2. Click **three dots** () icon -3. Click **Rename** -4. Enter new title and save - -![Context Menu](./_assets/threads-context-menu-updated.png) - -### Delete Threads - - -Thread deletion is permanent. No undo available. - - -**Single thread:** -1. Hover over thread in sidebar -2. Click **three dots** () icon -3. Click **Delete** - -**All threads:** -1. Hover over `Recents` category -2. Click **three dots** () icon -3. Select **Delete All** - -## Advanced Features - -### Custom Assistant Instructions - -Customize how models respond: - -1. Use the assistant dropdown in the input field -2. Or go to the **Assistant tab** to create custom instructions -3. Instructions work across all models - -![Assistant Instruction](./_assets/assistant-dropdown.png) - -![Add an Assistant Instruction](./_assets/assistant-edit-dialog.png) - -### Model Parameters - -Fine-tune model behavior: -- Click the **Gear icon** next to your model -- Adjust parameters in **Assistant Settings** -- Switch models via the **model selector** - -![Chat with a Model](./_assets/model-parameters.png) - -### Connect Cloud Models (Optional) - -Connect to OpenAI, Anthropic, Groq, Mistral, and others: - -1. Open any thread -2. Select a cloud model from the dropdown -3. Click the **Gear icon** beside the provider -4. Add your API key (ensure sufficient credits) - -![Connect Remote APIs](./_assets/quick-start-03.png) - -For detailed setup, see [Remote APIs](/docs/remote-models/openai). diff --git a/docs/src/pages/platforms/_meta.json b/docs/src/pages/platforms/_meta.json new file mode 100644 index 000000000..bfee4c12e --- /dev/null +++ b/docs/src/pages/platforms/_meta.json @@ -0,0 +1,9 @@ +{ + "-- Switcher": { + "type": "separator", + "title": "Switcher" + }, + "index": { + "display": "hidden" + } +} diff --git a/docs/src/pages/platforms/index.mdx b/docs/src/pages/platforms/index.mdx new file mode 100644 index 000000000..8ebaabe42 --- /dev/null +++ b/docs/src/pages/platforms/index.mdx @@ -0,0 +1,87 @@ +--- +title: Coming Soon +description: Exciting new features and platforms are on the way. Stay tuned for Jan Web, Jan Mobile, and our API Platform. +keywords: + [ + Jan, + Customizable Intelligence, LLM, + local AI, + privacy focus, + free and open source, + private and offline, + conversational AI, + no-subscription fee, + large language models, + coming soon, + Jan Web, + Jan Mobile, + API Platform, + ] +--- + +import { Callout } from 'nextra/components' + +
+
+

+ 🚀 Coming Soon +

+

+ We're working on the next stage of Jan - making our local assistant more powerful and available in more platforms. +

+
+ +
+
+
🌐
+

Jan Web

+

+ Access Jan directly from your browser with our powerful web interface +

+
+ +
+
📱
+

Jan Mobile

+

+ Take Jan on the go with our native mobile applications +

+
+ +
+
+

API Platform

+

+ Integrate Jan's capabilities into your applications with our API +

+
+
+ + + **Stay Updated**: Follow our [GitHub repository](https://github.com/menloresearch/jan) and join our [Discord community](https://discord.com/invite/FTk2MvZwJH) for the latest updates on these exciting releases! + + +
+

What to Expect

+
+
+ +
+ Seamless Experience: Unified interface across all platforms +
+
+
+ +
+ Privacy First: Same privacy-focused approach you trust +
+
+
+ +
+ Developer Friendly: Robust APIs and comprehensive documentation +
+
+
+
+
diff --git a/docs/src/pages/post/jan-v1-for-research.mdx b/docs/src/pages/post/jan-v1-for-research.mdx index 2d06e38f6..b23f17d2f 100644 --- a/docs/src/pages/post/jan-v1-for-research.mdx +++ b/docs/src/pages/post/jan-v1-for-research.mdx @@ -5,7 +5,7 @@ keywords: ["Jan-V1", "AI research", "system prompts", "LLM optimization", "resea readingTime: "8 min read" tags: Qwen, Jan-V1, Agentic categories: research -ogImage: https://jan.ai/post/_assets/jan-research.jpeg +ogImage: assets/images/general/og-jan-research.jpeg date: 2025-08-22 --- diff --git a/extensions-web/package.json b/extensions-web/package.json new file mode 100644 index 000000000..8d54443fe --- /dev/null +++ b/extensions-web/package.json @@ -0,0 +1,34 @@ +{ + "name": "@jan/extensions-web", + "version": "1.0.0", + "description": "Web-specific extensions for Jan AI", + "main": "dist/index.mjs", + "module": "dist/index.mjs", + "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "tsc && vite build", + "dev": "tsc --watch", + "test": "vitest", + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@janhq/core": "workspace:*", + "typescript": "^5.3.3", + "vite": "^5.0.0", + "vitest": "^2.0.0", + "zustand": "^5.0.8" + }, + "peerDependencies": { + "@janhq/core": "*", + "zustand": "^5.0.0" + } +} diff --git a/extensions-web/src/assistant-web/index.ts b/extensions-web/src/assistant-web/index.ts new file mode 100644 index 000000000..0a800d36d --- /dev/null +++ b/extensions-web/src/assistant-web/index.ts @@ -0,0 +1,198 @@ +/** + * Web Assistant Extension + * Implements assistant management using IndexedDB + */ + +import { Assistant, AssistantExtension } from '@janhq/core' +import { getSharedDB } from '../shared/db' + +export default class AssistantExtensionWeb extends AssistantExtension { + private db: IDBDatabase | null = null + + private defaultAssistant: Assistant = { + avatar: '👋', + thread_location: undefined, + id: 'jan', + object: 'assistant', + created_at: Date.now() / 1000, + name: 'Jan', + description: + 'Jan is a helpful desktop assistant that can reason through complex tasks and use tools to complete them on the user\'s behalf.', + model: '*', + instructions: + 'You are a helpful AI assistant. Your primary goal is to assist users with their questions and tasks to the best of your abilities.\n\n' + + 'When responding:\n' + + '- Answer directly from your knowledge when you can\n' + + '- Be concise, clear, and helpful\n' + + '- Admit when you\'re unsure rather than making things up\n\n' + + 'If tools are available to you:\n' + + '- Only use tools when they add real value to your response\n' + + '- Use tools when the user explicitly asks (e.g., "search for...", "calculate...", "run this code")\n' + + '- Use tools for information you don\'t know or that needs verification\n' + + '- Never use tools just because they\'re available\n\n' + + 'When using tools:\n' + + '- Use one tool at a time and wait for results\n' + + '- Use actual values as arguments, not variable names\n' + + '- Learn from each result before deciding next steps\n' + + '- Avoid repeating the same tool call with identical parameters\n\n' + + 'Remember: Most questions can be answered without tools. Think first whether you need them.\n\n' + + 'Current date: {{current_date}}', + tools: [ + { + type: 'retrieval', + enabled: false, + useTimeWeightedRetriever: false, + settings: { + top_k: 2, + chunk_size: 1024, + chunk_overlap: 64, + retrieval_template: `Use the following pieces of context to answer the question at the end. +{context} +Question: {question} +Helpful Answer:`, + }, + }, + ], + file_ids: [], + metadata: undefined, + } + + async onLoad() { + console.log('Loading Web Assistant Extension') + this.db = await getSharedDB() + + // Create default assistant if none exist + const assistants = await this.getAssistants() + if (assistants.length === 0) { + await this.createAssistant(this.defaultAssistant) + } + } + + onUnload() { + // Don't close shared DB, other extensions might be using it + this.db = null + } + + private ensureDB(): void { + if (!this.db) { + throw new Error('Database not initialized. Call onLoad() first.') + } + } + + async getAssistants(): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['assistants'], 'readonly') + const store = transaction.objectStore('assistants') + const request = store.getAll() + + request.onsuccess = () => { + resolve(request.result || []) + } + + request.onerror = () => { + reject(request.error) + } + }) + } + + async createAssistant(assistant: Assistant): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['assistants'], 'readwrite') + const store = transaction.objectStore('assistants') + + const assistantToStore = { + ...assistant, + created_at: assistant.created_at || Date.now() / 1000, + } + + const request = store.add(assistantToStore) + + request.onsuccess = () => { + console.log('Assistant created:', assistant.id) + resolve() + } + + request.onerror = () => { + console.error('Failed to create assistant:', request.error) + reject(request.error) + } + }) + } + + async updateAssistant(id: string, assistant: Partial): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['assistants'], 'readwrite') + const store = transaction.objectStore('assistants') + + // First get the existing assistant + const getRequest = store.get(id) + + getRequest.onsuccess = () => { + const existingAssistant = getRequest.result + if (!existingAssistant) { + reject(new Error(`Assistant with id ${id} not found`)) + return + } + + const updatedAssistant = { + ...existingAssistant, + ...assistant, + id, // Ensure ID doesn't change + } + + const putRequest = store.put(updatedAssistant) + + putRequest.onsuccess = () => resolve() + putRequest.onerror = () => reject(putRequest.error) + } + + getRequest.onerror = () => { + reject(getRequest.error) + } + }) + } + + async deleteAssistant(assistant: Assistant): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['assistants'], 'readwrite') + const store = transaction.objectStore('assistants') + const request = store.delete(assistant.id) + + request.onsuccess = () => { + console.log('Assistant deleted:', assistant.id) + resolve() + } + + request.onerror = () => { + console.error('Failed to delete assistant:', request.error) + reject(request.error) + } + }) + } + + async getAssistant(id: string): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['assistants'], 'readonly') + const store = transaction.objectStore('assistants') + const request = store.get(id) + + request.onsuccess = () => { + resolve(request.result || null) + } + + request.onerror = () => { + reject(request.error) + } + }) + } +} \ No newline at end of file diff --git a/extensions-web/src/conversational-web/index.ts b/extensions-web/src/conversational-web/index.ts new file mode 100644 index 000000000..5f9ae260e --- /dev/null +++ b/extensions-web/src/conversational-web/index.ts @@ -0,0 +1,347 @@ +/** + * Web Conversational Extension + * Implements thread and message management using IndexedDB + */ + +import { Thread, ThreadMessage, ConversationalExtension, ThreadAssistantInfo } from '@janhq/core' +import { getSharedDB } from '../shared/db' + +export default class ConversationalExtensionWeb extends ConversationalExtension { + private db: IDBDatabase | null = null + + async onLoad() { + console.log('Loading Web Conversational Extension') + this.db = await getSharedDB() + } + + onUnload() { + // Don't close shared DB, other extensions might be using it + this.db = null + } + + private ensureDB(): void { + if (!this.db) { + throw new Error('Database not initialized. Call onLoad() first.') + } + } + + // Thread Management + async listThreads(): Promise { + return this.getThreads() + } + + async getThreads(): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['threads'], 'readonly') + const store = transaction.objectStore('threads') + const request = store.getAll() + + request.onsuccess = () => { + const threads = request.result || [] + // Sort by updated desc (most recent first) + threads.sort((a, b) => (b.updated || 0) - (a.updated || 0)) + resolve(threads) + } + + request.onerror = () => { + reject(request.error) + } + }) + } + + async createThread(thread: Thread): Promise { + await this.saveThread(thread) + return thread + } + + async modifyThread(thread: Thread): Promise { + await this.saveThread(thread) + } + + async saveThread(thread: Thread): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['threads'], 'readwrite') + const store = transaction.objectStore('threads') + + const threadToStore = { + ...thread, + created: thread.created || Date.now() / 1000, + updated: Date.now() / 1000, + } + + const request = store.put(threadToStore) + + request.onsuccess = () => { + console.log('Thread saved:', thread.id) + resolve() + } + + request.onerror = () => { + console.error('Failed to save thread:', request.error) + reject(request.error) + } + }) + } + + async deleteThread(threadId: string): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['threads', 'messages'], 'readwrite') + const threadsStore = transaction.objectStore('threads') + const messagesStore = transaction.objectStore('messages') + + // Delete thread + const deleteThreadRequest = threadsStore.delete(threadId) + + // Delete all messages in the thread + const messageIndex = messagesStore.index('thread_id') + const messagesRequest = messageIndex.openCursor(IDBKeyRange.only(threadId)) + + messagesRequest.onsuccess = (event) => { + const cursor = (event.target as IDBRequest).result + if (cursor) { + cursor.delete() + cursor.continue() + } + } + + transaction.oncomplete = () => { + console.log('Thread and messages deleted:', threadId) + resolve() + } + + transaction.onerror = () => { + console.error('Failed to delete thread:', transaction.error) + reject(transaction.error) + } + }) + } + + // Message Management + async createMessage(message: ThreadMessage): Promise { + await this.addNewMessage(message) + return message + } + + async listMessages(threadId: string): Promise { + return this.getAllMessages(threadId) + } + + async modifyMessage(message: ThreadMessage): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['messages'], 'readwrite') + const store = transaction.objectStore('messages') + + const messageToStore = { + ...message, + updated: Date.now() / 1000, + } + + const request = store.put(messageToStore) + + request.onsuccess = () => { + console.log('Message updated:', message.id) + resolve(message) + } + + request.onerror = () => { + console.error('Failed to update message:', request.error) + reject(request.error) + } + }) + } + + async deleteMessage(threadId: string, messageId: string): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['messages'], 'readwrite') + const store = transaction.objectStore('messages') + const request = store.delete(messageId) + + request.onsuccess = () => { + console.log('Message deleted:', messageId) + resolve() + } + + request.onerror = () => { + console.error('Failed to delete message:', request.error) + reject(request.error) + } + }) + } + + async addNewMessage(message: ThreadMessage): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['messages'], 'readwrite') + const store = transaction.objectStore('messages') + + const messageToStore = { + ...message, + created_at: message.created_at || Date.now() / 1000, + } + + const request = store.add(messageToStore) + + request.onsuccess = () => { + console.log('Message added:', message.id) + resolve() + } + + request.onerror = () => { + console.error('Failed to add message:', request.error) + reject(request.error) + } + }) + } + + async writeMessages(threadId: string, messages: ThreadMessage[]): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['messages'], 'readwrite') + const store = transaction.objectStore('messages') + + // First, delete existing messages for this thread + const index = store.index('thread_id') + const deleteRequest = index.openCursor(IDBKeyRange.only(threadId)) + + deleteRequest.onsuccess = (event) => { + const cursor = (event.target as IDBRequest).result + if (cursor) { + cursor.delete() + cursor.continue() + } else { + // After deleting old messages, add new ones + const addPromises = messages.map(message => { + return new Promise((resolveAdd, rejectAdd) => { + const messageToStore = { + ...message, + thread_id: threadId, + created_at: message.created_at || Date.now() / 1000, + } + + const addRequest = store.add(messageToStore) + addRequest.onsuccess = () => resolveAdd() + addRequest.onerror = () => rejectAdd(addRequest.error) + }) + }) + + Promise.all(addPromises) + .then(() => { + console.log(`${messages.length} messages written for thread:`, threadId) + resolve() + }) + .catch(reject) + } + } + + deleteRequest.onerror = () => { + reject(deleteRequest.error) + } + }) + } + + async getAllMessages(threadId: string): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['messages'], 'readonly') + const store = transaction.objectStore('messages') + const index = store.index('thread_id') + const request = index.getAll(threadId) + + request.onsuccess = () => { + const messages = request.result || [] + // Sort by created_at asc (chronological order) + messages.sort((a, b) => (a.created_at || 0) - (b.created_at || 0)) + resolve(messages) + } + + request.onerror = () => { + reject(request.error) + } + }) + } + + // Thread Assistant Info (simplified - stored with thread) + async getThreadAssistant(threadId: string): Promise { + const info = await this.getThreadAssistantInfo(threadId) + if (!info) { + throw new Error(`Thread assistant info not found for thread ${threadId}`) + } + return info + } + + async createThreadAssistant(threadId: string, assistant: ThreadAssistantInfo): Promise { + await this.saveThreadAssistantInfo(threadId, assistant) + return assistant + } + + async modifyThreadAssistant(threadId: string, assistant: ThreadAssistantInfo): Promise { + await this.saveThreadAssistantInfo(threadId, assistant) + return assistant + } + + async saveThreadAssistantInfo(threadId: string, assistantInfo: ThreadAssistantInfo): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['threads'], 'readwrite') + const store = transaction.objectStore('threads') + + // Get existing thread and update with assistant info + const getRequest = store.get(threadId) + + getRequest.onsuccess = () => { + const thread = getRequest.result + if (!thread) { + reject(new Error(`Thread ${threadId} not found`)) + return + } + + const updatedThread = { + ...thread, + assistantInfo, + updated_at: Date.now() / 1000, + } + + const putRequest = store.put(updatedThread) + putRequest.onsuccess = () => resolve() + putRequest.onerror = () => reject(putRequest.error) + } + + getRequest.onerror = () => { + reject(getRequest.error) + } + }) + } + + async getThreadAssistantInfo(threadId: string): Promise { + this.ensureDB() + + return new Promise((resolve, reject) => { + const transaction = this.db!.transaction(['threads'], 'readonly') + const store = transaction.objectStore('threads') + const request = store.get(threadId) + + request.onsuccess = () => { + const thread = request.result + resolve(thread?.assistantInfo) + } + + request.onerror = () => { + reject(request.error) + } + }) + } +} \ No newline at end of file diff --git a/extensions-web/src/index.ts b/extensions-web/src/index.ts new file mode 100644 index 000000000..aa53e37e1 --- /dev/null +++ b/extensions-web/src/index.ts @@ -0,0 +1,28 @@ +/** + * Web Extensions Package + * Contains browser-compatible extensions for Jan AI + */ + +import type { WebExtensionRegistry } from './types' + +export { default as AssistantExtensionWeb } from './assistant-web' +export { default as ConversationalExtensionWeb } from './conversational-web' +export { default as JanProviderWeb } from './jan-provider-web' + +// Re-export types +export type { + WebExtensionRegistry, + WebExtensionModule, + WebExtensionName, + WebExtensionLoader, + AssistantWebModule, + ConversationalWebModule, + JanProviderWebModule +} from './types' + +// Extension registry for dynamic loading +export const WEB_EXTENSIONS: WebExtensionRegistry = { + 'assistant-web': () => import('./assistant-web'), + 'conversational-web': () => import('./conversational-web'), + 'jan-provider-web': () => import('./jan-provider-web'), +} \ No newline at end of file diff --git a/extensions-web/src/jan-provider-web/api.ts b/extensions-web/src/jan-provider-web/api.ts new file mode 100644 index 000000000..68dd6cb77 --- /dev/null +++ b/extensions-web/src/jan-provider-web/api.ts @@ -0,0 +1,260 @@ +/** + * Jan Provider API Client + * Handles API requests to Jan backend for models and chat completions + */ + +import { JanAuthService } from './auth' +import { JanModel, janProviderStore } from './store' + +// JAN_API_BASE is defined in vite.config.ts + +export interface JanModelsResponse { + object: string + data: JanModel[] +} + +export interface JanChatMessage { + role: 'system' | 'user' | 'assistant' + content: string + reasoning?: string + reasoning_content?: string +} + +export interface JanChatCompletionRequest { + model: string + messages: JanChatMessage[] + temperature?: number + max_tokens?: number + top_p?: number + frequency_penalty?: number + presence_penalty?: number + stream?: boolean + stop?: string | string[] +} + +export interface JanChatCompletionChoice { + index: number + message: JanChatMessage + finish_reason: string | null +} + +export interface JanChatCompletionResponse { + id: string + object: string + created: number + model: string + choices: JanChatCompletionChoice[] + usage?: { + prompt_tokens: number + completion_tokens: number + total_tokens: number + } +} + +export interface JanChatCompletionChunk { + id: string + object: string + created: number + model: string + choices: Array<{ + index: number + delta: { + role?: string + content?: string + reasoning?: string + reasoning_content?: string + } + finish_reason: string | null + }> +} + +export class JanApiClient { + private static instance: JanApiClient + private authService: JanAuthService + + private constructor() { + this.authService = JanAuthService.getInstance() + } + + static getInstance(): JanApiClient { + if (!JanApiClient.instance) { + JanApiClient.instance = new JanApiClient() + } + return JanApiClient.instance + } + + private async makeAuthenticatedRequest( + url: string, + options: RequestInit = {} + ): Promise { + try { + const authHeader = await this.authService.getAuthHeader() + + const response = await fetch(url, { + ...options, + headers: { + 'Content-Type': 'application/json', + ...authHeader, + ...options.headers, + }, + }) + + if (!response.ok) { + const errorText = await response.text() + throw new Error(`API request failed: ${response.status} ${response.statusText} - ${errorText}`) + } + + return response.json() + } catch (error) { + console.error('API request failed:', error) + throw error + } + } + + async getModels(): Promise { + try { + janProviderStore.setLoadingModels(true) + janProviderStore.clearError() + + const response = await this.makeAuthenticatedRequest( + `${JAN_API_BASE}/models` + ) + + const models = response.data || [] + janProviderStore.setModels(models) + + return models + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to fetch models' + janProviderStore.setError(errorMessage) + janProviderStore.setLoadingModels(false) + throw error + } + } + + async createChatCompletion( + request: JanChatCompletionRequest + ): Promise { + try { + janProviderStore.clearError() + + return await this.makeAuthenticatedRequest( + `${JAN_API_BASE}/chat/completions`, + { + method: 'POST', + body: JSON.stringify({ + ...request, + stream: false, + }), + } + ) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to create chat completion' + janProviderStore.setError(errorMessage) + throw error + } + } + + async createStreamingChatCompletion( + request: JanChatCompletionRequest, + onChunk: (chunk: JanChatCompletionChunk) => void, + onComplete?: () => void, + onError?: (error: Error) => void + ): Promise { + try { + janProviderStore.clearError() + + const authHeader = await this.authService.getAuthHeader() + + const response = await fetch(`${JAN_API_BASE}/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...authHeader, + }, + body: JSON.stringify({ + ...request, + stream: true, + }), + }) + + if (!response.ok) { + const errorText = await response.text() + throw new Error(`API request failed: ${response.status} ${response.statusText} - ${errorText}`) + } + + if (!response.body) { + throw new Error('Response body is null') + } + + const reader = response.body.getReader() + const decoder = new TextDecoder() + + try { + let buffer = '' + + while (true) { + const { done, value } = await reader.read() + + if (done) { + break + } + + buffer += decoder.decode(value, { stream: true }) + const lines = buffer.split('\n') + + // Keep the last incomplete line in buffer + buffer = lines.pop() || '' + + for (const line of lines) { + const trimmedLine = line.trim() + if (trimmedLine.startsWith('data: ')) { + const data = trimmedLine.slice(6).trim() + + if (data === '[DONE]') { + onComplete?.() + return + } + + try { + const parsedChunk: JanChatCompletionChunk = JSON.parse(data) + onChunk(parsedChunk) + } catch (parseError) { + console.warn('Failed to parse SSE chunk:', parseError, 'Data:', data) + } + } + } + } + + onComplete?.() + } finally { + reader.releaseLock() + } + } catch (error) { + const err = error instanceof Error ? error : new Error('Unknown error occurred') + janProviderStore.setError(err.message) + onError?.(err) + throw err + } + } + + async initialize(): Promise { + try { + await this.authService.initialize() + janProviderStore.setAuthenticated(true) + + // Fetch initial models + await this.getModels() + + console.log('Jan API client initialized successfully') + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Failed to initialize API client' + janProviderStore.setError(errorMessage) + throw error + } finally { + janProviderStore.setInitializing(false) + } + } +} + +export const janApiClient = JanApiClient.getInstance() \ No newline at end of file diff --git a/extensions-web/src/jan-provider-web/auth.ts b/extensions-web/src/jan-provider-web/auth.ts new file mode 100644 index 000000000..be830c0d0 --- /dev/null +++ b/extensions-web/src/jan-provider-web/auth.ts @@ -0,0 +1,190 @@ +/** + * Jan Provider Authentication Service + * Handles guest login and token refresh for Jan API + */ + +export interface AuthTokens { + access_token: string + expires_in: number +} + +export interface AuthResponse { + access_token: string + expires_in: number +} + +// JAN_API_BASE is defined in vite.config.ts +const AUTH_STORAGE_KEY = 'jan_auth_tokens' +const TOKEN_EXPIRY_BUFFER = 60 * 1000 // 1 minute buffer before actual expiry + +export class JanAuthService { + private static instance: JanAuthService + private tokens: AuthTokens | null = null + private tokenExpiryTime: number = 0 + + private constructor() { + this.loadTokensFromStorage() + } + + static getInstance(): JanAuthService { + if (!JanAuthService.instance) { + JanAuthService.instance = new JanAuthService() + } + return JanAuthService.instance + } + + private loadTokensFromStorage(): void { + try { + const storedTokens = localStorage.getItem(AUTH_STORAGE_KEY) + if (storedTokens) { + const parsed = JSON.parse(storedTokens) + this.tokens = parsed.tokens + this.tokenExpiryTime = parsed.expiryTime || 0 + } + } catch (error) { + console.warn('Failed to load tokens from storage:', error) + this.clearTokens() + } + } + + private saveTokensToStorage(): void { + if (this.tokens) { + try { + localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify({ + tokens: this.tokens, + expiryTime: this.tokenExpiryTime + })) + } catch (error) { + console.error('Failed to save tokens to storage:', error) + } + } + } + + private clearTokens(): void { + this.tokens = null + this.tokenExpiryTime = 0 + localStorage.removeItem(AUTH_STORAGE_KEY) + } + + private isTokenExpired(): boolean { + return Date.now() > (this.tokenExpiryTime - TOKEN_EXPIRY_BUFFER) + } + + private calculateExpiryTime(expiresIn: number): number { + return Date.now() + (expiresIn * 1000) + } + + private async guestLogin(): Promise { + try { + const response = await fetch(`${JAN_API_BASE}/auth/guest-login`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + credentials: 'include', // Include cookies for session management + }) + + if (!response.ok) { + throw new Error(`Guest login failed: ${response.status} ${response.statusText}`) + } + + const data = await response.json() + + // API response is wrapped in result object + const authResponse = data.result || data + + // Guest login returns only access_token and expires_in + const tokens: AuthTokens = { + access_token: authResponse.access_token, + expires_in: authResponse.expires_in + } + + this.tokens = tokens + this.tokenExpiryTime = this.calculateExpiryTime(tokens.expires_in) + this.saveTokensToStorage() + + return tokens + } catch (error) { + console.error('Guest login failed:', error) + throw error + } + } + + private async refreshToken(): Promise { + try { + const response = await fetch(`${JAN_API_BASE}/auth/refresh-token`, { + method: 'GET', + credentials: 'include', // Cookies will include the refresh token + }) + + if (!response.ok) { + if (response.status === 401) { + // Refresh token is invalid, clear tokens and do guest login + this.clearTokens() + return this.guestLogin() + } + throw new Error(`Token refresh failed: ${response.status} ${response.statusText}`) + } + + const data = await response.json() + + // API response is wrapped in result object + const authResponse = data.result || data + + // Refresh endpoint returns only access_token and expires_in + const tokens: AuthTokens = { + access_token: authResponse.access_token, + expires_in: authResponse.expires_in + } + + this.tokens = tokens + this.tokenExpiryTime = this.calculateExpiryTime(tokens.expires_in) + this.saveTokensToStorage() + + return tokens + } catch (error) { + console.error('Token refresh failed:', error) + // If refresh fails, fall back to guest login + this.clearTokens() + return this.guestLogin() + } + } + + async getValidAccessToken(): Promise { + // If no tokens exist, do guest login + if (!this.tokens) { + const tokens = await this.guestLogin() + return tokens.access_token + } + + // If token is expired or about to expire, refresh it + if (this.isTokenExpired()) { + const tokens = await this.refreshToken() + return tokens.access_token + } + + // Return existing valid token + return this.tokens.access_token + } + + async initialize(): Promise { + try { + await this.getValidAccessToken() + console.log('Jan auth service initialized successfully') + } catch (error) { + console.error('Failed to initialize Jan auth service:', error) + throw error + } + } + + async getAuthHeader(): Promise<{ Authorization: string }> { + const token = await this.getValidAccessToken() + return { + Authorization: `Bearer ${token}` + } + } + + logout(): void { + this.clearTokens() + } +} \ No newline at end of file diff --git a/extensions-web/src/jan-provider-web/index.ts b/extensions-web/src/jan-provider-web/index.ts new file mode 100644 index 000000000..70cbf7770 --- /dev/null +++ b/extensions-web/src/jan-provider-web/index.ts @@ -0,0 +1 @@ +export { default } from './provider' \ No newline at end of file diff --git a/extensions-web/src/jan-provider-web/provider.ts b/extensions-web/src/jan-provider-web/provider.ts new file mode 100644 index 000000000..dbe39beba --- /dev/null +++ b/extensions-web/src/jan-provider-web/provider.ts @@ -0,0 +1,307 @@ +/** + * Jan Provider Extension for Web + * Provides remote model inference through Jan API + */ + +import { + AIEngine, + modelInfo, + SessionInfo, + UnloadResult, + chatCompletionRequest, + chatCompletion, + chatCompletionChunk, + ImportOptions, +} from '@janhq/core' // cspell: disable-line +import { janApiClient, JanChatMessage } from './api' +import { janProviderStore } from './store' + +export default class JanProviderWeb extends AIEngine { + readonly provider = 'jan' + private activeSessions: Map = new Map() + + override async onLoad() { + console.log('Loading Jan Provider Extension...') + + try { + // Initialize authentication and fetch models + await janApiClient.initialize() + console.log('Jan Provider Extension loaded successfully') + } catch (error) { + console.error('Failed to load Jan Provider Extension:', error) + throw error + } + + super.onLoad() + } + + override async onUnload() { + console.log('Unloading Jan Provider Extension...') + + // Clear all sessions + for (const sessionId of this.activeSessions.keys()) { + await this.unload(sessionId) + } + + janProviderStore.reset() + console.log('Jan Provider Extension unloaded') + } + + async list(): Promise { + try { + const janModels = await janApiClient.getModels() + + return janModels.map((model) => ({ + id: model.id, + name: model.id, // Use ID as name for now + quant_type: undefined, + providerId: this.provider, + port: 443, // HTTPS port for API + sizeBytes: 0, // Size not provided by Jan API + tags: [], + path: undefined, // Remote model, no local path + owned_by: model.owned_by, + object: model.object, + })) + } catch (error) { + console.error('Failed to list Jan models:', error) + throw error + } + } + + async load(modelId: string, _settings?: any): Promise { + try { + // For Jan API, we don't actually "load" models in the traditional sense + // We just create a session reference for tracking + const sessionId = `jan-${modelId}-${Date.now()}` + + const sessionInfo: SessionInfo = { + pid: Date.now(), // Use timestamp as pseudo-PID + port: 443, // HTTPS port + model_id: modelId, + model_path: `remote:${modelId}`, // Indicate this is a remote model + api_key: '', // API key handled by auth service + } + + this.activeSessions.set(sessionId, sessionInfo) + + console.log(`Jan model session created: ${sessionId} for model ${modelId}`) + return sessionInfo + } catch (error) { + console.error(`Failed to load Jan model ${modelId}:`, error) + throw error + } + } + + async unload(sessionId: string): Promise { + try { + const session = this.activeSessions.get(sessionId) + + if (!session) { + return { + success: false, + error: `Session ${sessionId} not found` + } + } + + this.activeSessions.delete(sessionId) + console.log(`Jan model session unloaded: ${sessionId}`) + + return { success: true } + } catch (error) { + console.error(`Failed to unload Jan session ${sessionId}:`, error) + return { + success: false, + error: error instanceof Error ? error.message : 'Unknown error' + } + } + } + + async chat( + opts: chatCompletionRequest, + abortController?: AbortController + ): Promise> { + try { + // Check if request was aborted before starting + if (abortController?.signal?.aborted) { + throw new Error('Request was aborted') + } + + // For Jan API, we need to determine which model to use + // The model should be specified in opts.model + const modelId = opts.model + if (!modelId) { + throw new Error('Model ID is required') + } + + // Convert core chat completion request to Jan API format + const janMessages: JanChatMessage[] = opts.messages.map(msg => ({ + role: msg.role as 'system' | 'user' | 'assistant', + content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content) + })) + + const janRequest = { + model: modelId, + messages: janMessages, + temperature: opts.temperature ?? undefined, + max_tokens: opts.n_predict ?? undefined, + top_p: opts.top_p ?? undefined, + frequency_penalty: opts.frequency_penalty ?? undefined, + presence_penalty: opts.presence_penalty ?? undefined, + stream: opts.stream ?? false, + stop: opts.stop ?? undefined, + } + + if (opts.stream) { + // Return async generator for streaming + return this.createStreamingGenerator(janRequest, abortController) + } else { + // Return single response + const response = await janApiClient.createChatCompletion(janRequest) + + // Check if aborted after completion + if (abortController?.signal?.aborted) { + throw new Error('Request was aborted') + } + + return { + id: response.id, + object: 'chat.completion' as const, + created: response.created, + model: response.model, + choices: response.choices.map(choice => ({ + index: choice.index, + message: { + role: choice.message.role, + content: choice.message.content, + reasoning: choice.message.reasoning, + reasoning_content: choice.message.reasoning_content, + }, + finish_reason: (choice.finish_reason || 'stop') as 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call', + })), + usage: response.usage, + } + } + } catch (error) { + console.error('Jan chat completion failed:', error) + throw error + } + } + + private async *createStreamingGenerator(janRequest: any, abortController?: AbortController) { + let resolve: () => void + let reject: (error: Error) => void + const chunks: any[] = [] + let isComplete = false + let error: Error | null = null + + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + + // Handle abort signal + const abortListener = () => { + error = new Error('Request was aborted') + reject(error) + } + + if (abortController?.signal) { + if (abortController.signal.aborted) { + throw new Error('Request was aborted') + } + abortController.signal.addEventListener('abort', abortListener) + } + + try { + // Start the streaming request + janApiClient.createStreamingChatCompletion( + janRequest, + (chunk) => { + if (abortController?.signal?.aborted) { + return + } + const streamChunk = { + id: chunk.id, + object: chunk.object, + created: chunk.created, + model: chunk.model, + choices: chunk.choices.map(choice => ({ + index: choice.index, + delta: { + role: choice.delta.role, + content: choice.delta.content, + reasoning: choice.delta.reasoning, + reasoning_content: choice.delta.reasoning_content, + }, + finish_reason: choice.finish_reason, + })), + } + chunks.push(streamChunk) + }, + () => { + isComplete = true + resolve() + }, + (err) => { + error = err + reject(err) + } + ) + + // Yield chunks as they arrive + let yieldedIndex = 0 + while (!isComplete && !error) { + if (abortController?.signal?.aborted) { + throw new Error('Request was aborted') + } + + while (yieldedIndex < chunks.length) { + yield chunks[yieldedIndex] + yieldedIndex++ + } + + // Wait a bit before checking again + await new Promise(resolve => setTimeout(resolve, 10)) + } + + // Yield any remaining chunks + while (yieldedIndex < chunks.length) { + yield chunks[yieldedIndex] + yieldedIndex++ + } + + if (error) { + throw error + } + + await promise + } finally { + // Clean up abort listener + if (abortController?.signal) { + abortController.signal.removeEventListener('abort', abortListener) + } + } + } + + async delete(modelId: string): Promise { + throw new Error(`Delete operation not supported for remote Jan API model: ${modelId}`) + } + + async import(modelId: string, _opts: ImportOptions): Promise { + throw new Error(`Import operation not supported for remote Jan API model: ${modelId}`) + } + + async abortImport(modelId: string): Promise { + throw new Error(`Abort import operation not supported for remote Jan API model: ${modelId}`) + } + + async getLoadedModels(): Promise { + return Array.from(this.activeSessions.values()).map(session => session.model_id) + } + + async isToolSupported(): Promise { + // Tools are not yet supported + return false + } +} \ No newline at end of file diff --git a/extensions-web/src/jan-provider-web/store.ts b/extensions-web/src/jan-provider-web/store.ts new file mode 100644 index 000000000..02cc70686 --- /dev/null +++ b/extensions-web/src/jan-provider-web/store.ts @@ -0,0 +1,95 @@ +/** + * Jan Provider Store + * Zustand-based state management for Jan provider authentication and models + */ + +import { create } from 'zustand' + +export interface JanModel { + id: string + object: string + owned_by: string +} + +export interface JanProviderState { + isAuthenticated: boolean + isInitializing: boolean + models: JanModel[] + isLoadingModels: boolean + error: string | null +} + +export interface JanProviderActions { + setAuthenticated: (isAuthenticated: boolean) => void + setInitializing: (isInitializing: boolean) => void + setModels: (models: JanModel[]) => void + setLoadingModels: (isLoadingModels: boolean) => void + setError: (error: string | null) => void + clearError: () => void + reset: () => void +} + +export type JanProviderStore = JanProviderState & JanProviderActions + +const initialState: JanProviderState = { + isAuthenticated: false, + isInitializing: true, + models: [], + isLoadingModels: false, + error: null, +} + +export const useJanProviderStore = create((set) => ({ + ...initialState, + + setAuthenticated: (isAuthenticated: boolean) => + set({ isAuthenticated, error: null }), + + setInitializing: (isInitializing: boolean) => + set({ isInitializing }), + + setModels: (models: JanModel[]) => + set({ models, isLoadingModels: false }), + + setLoadingModels: (isLoadingModels: boolean) => + set({ isLoadingModels }), + + setError: (error: string | null) => + set({ error }), + + clearError: () => + set({ error: null }), + + reset: () => + set({ + isAuthenticated: false, + isInitializing: false, + models: [], + isLoadingModels: false, + error: null, + }), +})) + +// Export a store instance for non-React usage +export const janProviderStore = { + // Store access methods + getState: useJanProviderStore.getState, + setState: useJanProviderStore.setState, + subscribe: useJanProviderStore.subscribe, + + // Direct action methods + setAuthenticated: (isAuthenticated: boolean) => + useJanProviderStore.getState().setAuthenticated(isAuthenticated), + setInitializing: (isInitializing: boolean) => + useJanProviderStore.getState().setInitializing(isInitializing), + setModels: (models: JanModel[]) => + useJanProviderStore.getState().setModels(models), + setLoadingModels: (isLoadingModels: boolean) => + useJanProviderStore.getState().setLoadingModels(isLoadingModels), + setError: (error: string | null) => + useJanProviderStore.getState().setError(error), + clearError: () => + useJanProviderStore.getState().clearError(), + reset: () => + useJanProviderStore.getState().reset(), +} \ No newline at end of file diff --git a/extensions-web/src/shared/db.ts b/extensions-web/src/shared/db.ts new file mode 100644 index 000000000..175d6a2b5 --- /dev/null +++ b/extensions-web/src/shared/db.ts @@ -0,0 +1,105 @@ +/** + * Shared IndexedDB utilities for web extensions + */ + +import type { IndexedDBConfig } from '../types' + +/** + * Default database configuration for Jan web extensions + */ +const DEFAULT_DB_CONFIG: IndexedDBConfig = { + dbName: 'jan-web-db', + version: 1, + stores: [ + { + name: 'assistants', + keyPath: 'id', + indexes: [ + { name: 'name', keyPath: 'name' }, + { name: 'created_at', keyPath: 'created_at' } + ] + }, + { + name: 'threads', + keyPath: 'id', + indexes: [ + { name: 'title', keyPath: 'title' }, + { name: 'created_at', keyPath: 'created_at' }, + { name: 'updated_at', keyPath: 'updated_at' } + ] + }, + { + name: 'messages', + keyPath: 'id', + indexes: [ + { name: 'thread_id', keyPath: 'thread_id' }, + { name: 'created_at', keyPath: 'created_at' } + ] + } + ] +} + +/** + * Shared IndexedDB instance + */ +let sharedDB: IDBDatabase | null = null + +/** + * Get or create the shared IndexedDB instance + */ +export const getSharedDB = async (config: IndexedDBConfig = DEFAULT_DB_CONFIG): Promise => { + if (sharedDB && sharedDB.name === config.dbName) { + return sharedDB + } + + return new Promise((resolve, reject) => { + const request = indexedDB.open(config.dbName, config.version) + + request.onerror = () => { + reject(new Error(`Failed to open database: ${request.error?.message}`)) + } + + request.onsuccess = () => { + sharedDB = request.result + resolve(sharedDB) + } + + request.onupgradeneeded = (event) => { + const db = (event.target as IDBOpenDBRequest).result + + // Create object stores + for (const store of config.stores) { + let objectStore: IDBObjectStore + + if (db.objectStoreNames.contains(store.name)) { + // Store exists, might need to update indexes + continue + } else { + // Create new store + objectStore = db.createObjectStore(store.name, { keyPath: store.keyPath }) + } + + // Create indexes + if (store.indexes) { + for (const index of store.indexes) { + try { + objectStore.createIndex(index.name, index.keyPath, { unique: index.unique || false }) + } catch (error) { + // Index might already exist, ignore + } + } + } + } + } + }) +} + +/** + * Close the shared database connection + */ +export const closeSharedDB = () => { + if (sharedDB) { + sharedDB.close() + sharedDB = null + } +} \ No newline at end of file diff --git a/extensions-web/src/types.ts b/extensions-web/src/types.ts new file mode 100644 index 000000000..4b2ba583e --- /dev/null +++ b/extensions-web/src/types.ts @@ -0,0 +1,41 @@ +/** + * Web Extension Types + */ + +import type { AssistantExtension, ConversationalExtension, BaseExtension, AIEngine } from '@janhq/core' + +type ExtensionConstructorParams = ConstructorParameters + +export interface AssistantWebModule { + default: new (...args: ExtensionConstructorParams) => AssistantExtension +} + +export interface ConversationalWebModule { + default: new (...args: ExtensionConstructorParams) => ConversationalExtension +} + +export interface JanProviderWebModule { + default: new (...args: ExtensionConstructorParams) => AIEngine +} + +export type WebExtensionModule = AssistantWebModule | ConversationalWebModule | JanProviderWebModule + +export interface WebExtensionRegistry { + 'assistant-web': () => Promise + 'conversational-web': () => Promise + 'jan-provider-web': () => Promise +} + +export type WebExtensionName = keyof WebExtensionRegistry + +export type WebExtensionLoader = WebExtensionRegistry[T] + +export interface IndexedDBConfig { + dbName: string + version: number + stores: { + name: string + keyPath: string + indexes?: { name: string; keyPath: string | string[]; unique?: boolean }[] + }[] +} \ No newline at end of file diff --git a/extensions-web/src/types/global.d.ts b/extensions-web/src/types/global.d.ts new file mode 100644 index 000000000..a6e82d759 --- /dev/null +++ b/extensions-web/src/types/global.d.ts @@ -0,0 +1,5 @@ +export {} + +declare global { + declare const JAN_API_BASE: string +} \ No newline at end of file diff --git a/extensions-web/src/vite-env.d.ts b/extensions-web/src/vite-env.d.ts new file mode 100644 index 000000000..151aa6856 --- /dev/null +++ b/extensions-web/src/vite-env.d.ts @@ -0,0 +1 @@ +/// \ No newline at end of file diff --git a/extensions-web/tsconfig.json b/extensions-web/tsconfig.json new file mode 100644 index 000000000..e90dd4997 --- /dev/null +++ b/extensions-web/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true, + "esModuleInterop": true, + "strict": true, + "skipLibCheck": true, + "outDir": "./dist", + "rootDir": "./src", + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": false, + "lib": ["ES2020", "DOM", "DOM.Iterable"] + }, + "include": ["src/**/*"], + "exclude": ["dist", "node_modules", "**/*.test.ts"] +} \ No newline at end of file diff --git a/extensions-web/vite.config.ts b/extensions-web/vite.config.ts new file mode 100644 index 000000000..8d9147c79 --- /dev/null +++ b/extensions-web/vite.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from 'vite' + +export default defineConfig({ + build: { + lib: { + entry: 'src/index.ts', + name: 'JanExtensionsWeb', + formats: ['es'], + fileName: 'index' + }, + rollupOptions: { + external: ['@janhq/core', 'zustand'] + }, + emptyOutDir: false // Don't clean the output directory + }, + define: { + JAN_API_BASE: JSON.stringify(process.env.JAN_API_BASE || 'https://api-dev.jan.ai/jan/v1'), + } +}) \ No newline at end of file diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.json index 3c0964fc6..ddbefa936 100644 --- a/extensions/llamacpp-extension/settings.json +++ b/extensions/llamacpp-extension/settings.json @@ -16,7 +16,7 @@ "description": "Environmental variables for llama.cpp(KEY=VALUE), separated by ';'", "controllerType": "input", "controllerProps": { - "value": "none", + "value": "", "placeholder": "Eg. GGML_VK_VISIBLE_DEVICES=0,1", "type": "text", "textAlign": "right" diff --git a/extensions/llamacpp-extension/src/backend.ts b/extensions/llamacpp-extension/src/backend.ts index b47839d58..710dfeba8 100644 --- a/extensions/llamacpp-extension/src/backend.ts +++ b/extensions/llamacpp-extension/src/backend.ts @@ -77,7 +77,7 @@ export async function listSupportedBackends(): Promise< supportedBackends.push('macos-arm64') } - const releases = await _fetchGithubReleases('menloresearch', 'llama.cpp') + const { releases } = await _fetchGithubReleases('menloresearch', 'llama.cpp') releases.sort((a, b) => b.tag_name.localeCompare(a.tag_name)) releases.splice(10) // keep only the latest 10 releases @@ -145,7 +145,8 @@ export async function isBackendInstalled( export async function downloadBackend( backend: string, - version: string + version: string, + source: 'github' | 'cdn' = 'github' ): Promise { const janDataFolderPath = await getJanDataFolderPath() const llamacppPath = await joinPath([janDataFolderPath, 'llamacpp']) @@ -161,9 +162,15 @@ export async function downloadBackend( const platformName = IS_WINDOWS ? 'win' : 'linux' + // Build URLs per source + const backendUrl = + source === 'github' + ? `https://github.com/menloresearch/llama.cpp/releases/download/${version}/llama-${version}-bin-${backend}.tar.gz` + : `https://catalog.jan.ai/llama.cpp/releases/${version}/llama-${version}-bin-${backend}.tar.gz` + const downloadItems = [ { - url: `https://github.com/menloresearch/llama.cpp/releases/download/${version}/llama-${version}-bin-${backend}.tar.gz`, + url: backendUrl, save_path: await joinPath([backendDir, 'backend.tar.gz']), proxy: proxyConfig, }, @@ -172,13 +179,19 @@ export async function downloadBackend( // also download CUDA runtime + cuBLAS + cuBLASLt if needed if (backend.includes('cu11.7') && !(await _isCudaInstalled('11.7'))) { downloadItems.push({ - url: `https://github.com/menloresearch/llama.cpp/releases/download/${version}/cudart-llama-bin-${platformName}-cu11.7-x64.tar.gz`, + url: + source === 'github' + ? `https://github.com/menloresearch/llama.cpp/releases/download/${version}/cudart-llama-bin-${platformName}-cu11.7-x64.tar.gz` + : `https://catalog.jan.ai/llama.cpp/releases/${version}/cudart-llama-bin-${platformName}-cu11.7-x64.tar.gz`, save_path: await joinPath([libDir, 'cuda11.tar.gz']), proxy: proxyConfig, }) } else if (backend.includes('cu12.0') && !(await _isCudaInstalled('12.0'))) { downloadItems.push({ - url: `https://github.com/menloresearch/llama.cpp/releases/download/${version}/cudart-llama-bin-${platformName}-cu12.0-x64.tar.gz`, + url: + source === 'github' + ? `https://github.com/menloresearch/llama.cpp/releases/download/${version}/cudart-llama-bin-${platformName}-cu12.0-x64.tar.gz` + : `https://catalog.jan.ai/llama.cpp/releases/${version}/cudart-llama-bin-${platformName}-cu12.0-x64.tar.gz`, save_path: await joinPath([libDir, 'cuda12.tar.gz']), proxy: proxyConfig, }) @@ -188,7 +201,7 @@ export async function downloadBackend( const downloadType = 'Engine' console.log( - `Downloading backend ${backend} version ${version}: ${JSON.stringify( + `Downloading backend ${backend} version ${version} from ${source}: ${JSON.stringify( downloadItems )}` ) @@ -223,6 +236,11 @@ export async function downloadBackend( events.emit('onFileDownloadSuccess', { modelId: taskId, downloadType }) } catch (error) { + // Fallback: if GitHub fails, retry once with CDN + if (source === 'github') { + console.warn(`GitHub download failed, falling back to CDN:`, error) + return await downloadBackend(backend, version, 'cdn') + } console.error(`Failed to download backend ${backend}: `, error) events.emit('onFileDownloadError', { modelId: taskId, downloadType }) throw error @@ -270,21 +288,32 @@ async function _getSupportedFeatures() { return features } +/** + * Fetch releases with GitHub-first strategy and fallback to CDN on any error. + * CDN endpoint is expected to mirror GitHub releases JSON shape. + */ async function _fetchGithubReleases( owner: string, repo: string -): Promise { - // by default, it's per_page=30 and page=1 -> the latest 30 releases - const url = `https://api.github.com/repos/${owner}/${repo}/releases` - const response = await fetch(url) - if (!response.ok) { - throw new Error( - `Failed to fetch releases from ${url}: ${response.statusText}` - ) +): Promise<{ releases: any[]; source: 'github' | 'cdn' }> { + const githubUrl = `https://api.github.com/repos/${owner}/${repo}/releases` + try { + const response = await fetch(githubUrl) + if (!response.ok) throw new Error(`GitHub error: ${response.status} ${response.statusText}`) + const releases = await response.json() + return { releases, source: 'github' } + } catch (_err) { + const cdnUrl = 'https://catalog.jan.ai/llama.cpp/releases/releases.json' + const response = await fetch(cdnUrl) + if (!response.ok) { + throw new Error(`Failed to fetch releases from both sources. CDN error: ${response.status} ${response.statusText}`) + } + const releases = await response.json() + return { releases, source: 'cdn' } } - return response.json() } + async function _isCudaInstalled(version: string): Promise { const sysInfo = await getSystemInfo() const os_type = sysInfo.os_type diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts index fe4f2f34c..725731bd7 100644 --- a/extensions/llamacpp-extension/src/index.ts +++ b/extensions/llamacpp-extension/src/index.ts @@ -1064,7 +1064,7 @@ export default class llamacpp_extension extends AIEngine { try { // emit download update event on progress const onProgress = (transferred: number, total: number) => { - events.emit('onFileDownloadUpdate', { + events.emit(DownloadEvent.onFileDownloadUpdate, { modelId, percent: transferred / total, size: { transferred, total }, @@ -1082,9 +1082,9 @@ export default class llamacpp_extension extends AIEngine { // If we reach here, download completed successfully (including validation) // The downloadFiles function only returns successfully if all files downloaded AND validated - events.emit(DownloadEvent.onFileDownloadAndVerificationSuccess, { - modelId, - downloadType: 'Model' + events.emit(DownloadEvent.onFileDownloadAndVerificationSuccess, { + modelId, + downloadType: 'Model', }) } catch (error) { logger.error('Error downloading model:', modelId, opts, error) @@ -1092,7 +1092,8 @@ export default class llamacpp_extension extends AIEngine { error instanceof Error ? error.message : String(error) // Check if this is a cancellation - const isCancellationError = errorMessage.includes('Download cancelled') || + const isCancellationError = + errorMessage.includes('Download cancelled') || errorMessage.includes('Validation cancelled') || errorMessage.includes('Hash computation cancelled') || errorMessage.includes('cancelled') || @@ -1372,7 +1373,7 @@ export default class llamacpp_extension extends AIEngine { envs['LLAMA_API_KEY'] = api_key // set user envs - this.parseEnvFromString(envs, this.llamacpp_env) + if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env) // model option is required // NOTE: model_path and mmproj_path can be either relative to Jan's data folder or absolute path @@ -1751,7 +1752,7 @@ export default class llamacpp_extension extends AIEngine { } // set envs const envs: Record = {} - this.parseEnvFromString(envs, this.llamacpp_env) + if (this.llamacpp_env) this.parseEnvFromString(envs, this.llamacpp_env) // Ensure backend is downloaded and ready before proceeding await this.ensureBackendReady(backend, version) @@ -1767,7 +1768,7 @@ export default class llamacpp_extension extends AIEngine { return dList } catch (error) { logger.error('Failed to query devices:\n', error) - throw new Error("Failed to load llamacpp backend") + throw new Error('Failed to load llamacpp backend') } } @@ -1876,7 +1877,7 @@ export default class llamacpp_extension extends AIEngine { logger.info( `Using explicit key_length: ${keyLen}, value_length: ${valLen}` ) - headDim = (keyLen + valLen) + headDim = keyLen + valLen } else { // Fall back to embedding_length estimation const embeddingLen = Number(meta[`${arch}.embedding_length`]) @@ -1953,22 +1954,27 @@ export default class llamacpp_extension extends AIEngine { logger.info( `isModelSupported: Total memory requirement: ${totalRequired} for ${path}` ) - let availableMemBytes: number + let totalMemBytes: number const devices = await this.getDevices() if (devices.length > 0) { - // Sum free memory across all GPUs - availableMemBytes = devices - .map((d) => d.free * 1024 * 1024) + // Sum total memory across all GPUs + totalMemBytes = devices + .map((d) => d.mem * 1024 * 1024) .reduce((a, b) => a + b, 0) } else { // CPU fallback const sys = await getSystemUsage() - availableMemBytes = (sys.total_memory - sys.used_memory) * 1024 * 1024 + totalMemBytes = sys.total_memory * 1024 * 1024 } - // check model size wrt system memory - if (modelSize > availableMemBytes) { + + // Use 80% of total memory as the usable limit + const USABLE_MEMORY_PERCENTAGE = 0.8 + const usableMemBytes = totalMemBytes * USABLE_MEMORY_PERCENTAGE + + // check model size wrt 80% of system memory + if (modelSize > usableMemBytes) { return 'RED' - } else if (modelSize + kvCacheSize > availableMemBytes) { + } else if (modelSize + kvCacheSize > usableMemBytes) { return 'YELLOW' } else { return 'GREEN' diff --git a/mise.toml b/mise.toml index e44555be4..931603999 100644 --- a/mise.toml +++ b/mise.toml @@ -48,7 +48,7 @@ outputs = ['core/dist'] [tasks.build-extensions] description = "Build extensions" depends = ["build-core"] -run = "yarn build:extensions" +run = "yarn build:extensions && yarn build:extensions-web" sources = ['extensions/**/*'] outputs = ['pre-install/*.tgz'] @@ -76,15 +76,51 @@ run = [ "yarn dev:tauri" ] +# ============================================================================ +# WEB APPLICATION DEVELOPMENT TASKS +# ============================================================================ + +[tasks.dev-web-app] +description = "Start web application development server (matches Makefile)" +depends = ["install"] +run = "yarn dev:web-app" + +[tasks.build-web-app] +description = "Build web application (matches Makefile)" +depends = ["install"] +run = "yarn build:web-app" + +[tasks.serve-web-app] +description = "Serve built web application" +run = "yarn serve:web-app" + +[tasks.build-serve-web-app] +description = "Build and serve web application (matches Makefile)" +depends = ["build-web-app"] +run = "yarn serve:web-app" + # ============================================================================ # BUILD TASKS # ============================================================================ +[tasks.install-rust-targets] +description = "Install required Rust targets for MacOS universal builds" +run = ''' +#!/usr/bin/env bash +# Check if we're on macOS +if [[ "$OSTYPE" == "darwin"* ]]; then + echo "Detected macOS, installing universal build targets..." + rustup target add x86_64-apple-darwin + rustup target add aarch64-apple-darwin + echo "Rust targets installed successfully!" +fi +''' + [tasks.build] description = "Build complete application (matches Makefile)" -depends = ["install-and-build"] +depends = ["install-rust-targets", "install-and-build"] run = [ - "yarn copy:lib", + "yarn download:bin", "yarn build" ] diff --git a/nginx.conf b/nginx.conf new file mode 100644 index 000000000..58d44f67e --- /dev/null +++ b/nginx.conf @@ -0,0 +1,22 @@ +server { + listen 80; + server_name localhost; + root /usr/share/nginx/html; + index index.html; + + # Handle routes with or without trailing slash + location / { + try_files $uri $uri/ $uri.html $uri/index.html /index.html; + } + + # Security headers + add_header X-Frame-Options "SAMEORIGIN" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + + # Cache static assets + location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { + expires 1y; + add_header Cache-Control "public, immutable"; + } +} \ No newline at end of file diff --git a/package.json b/package.json index 04f1bc1dc..ba2704e57 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,8 @@ "workspaces": { "packages": [ "core", - "web-app" + "web-app", + "extensions-web" ] }, "scripts": { @@ -17,18 +18,23 @@ "test:coverage": "vitest run --coverage", "test:prepare": "yarn build:icon && yarn copy:assets:tauri && yarn build --no-bundle ", "dev:web": "yarn workspace @janhq/web-app dev", + "dev:web-app": "yarn build:extensions-web && yarn workspace @janhq/web-app install && yarn workspace @janhq/web-app dev:web", + "build:web-app": "yarn build:extensions-web && yarn workspace @janhq/web-app install && yarn workspace @janhq/web-app build:web", + "serve:web-app": "yarn workspace @janhq/web-app serve:web", + "build:serve:web-app": "yarn build:web-app && yarn serve:web-app", "dev:tauri": "yarn build:icon && yarn copy:assets:tauri && cross-env IS_CLEAN=true tauri dev", - "copy:assets:tauri": "cpx \"pre-install/*.tgz\" \"src-tauri/resources/pre-install/\"", + "copy:assets:tauri": "cpx \"pre-install/*.tgz\" \"src-tauri/resources/pre-install/\" && cpx \"LICENSE\" \"src-tauri/resources/\"", "download:lib": "node ./scripts/download-lib.mjs", "download:bin": "node ./scripts/download-bin.mjs", "build:tauri:win32": "yarn download:bin && yarn tauri build", - "build:tauri:linux": "yarn download:bin && ./src-tauri/build-utils/shim-linuxdeploy.sh yarn tauri build && ./src-tauri/build-utils/buildAppImage.sh", + "build:tauri:linux": "yarn download:bin && NO_STRIP=1 ./src-tauri/build-utils/shim-linuxdeploy.sh yarn tauri build --verbose && ./src-tauri/build-utils/buildAppImage.sh", "build:tauri:darwin": "yarn tauri build --target universal-apple-darwin", "build:tauri": "yarn build:icon && yarn copy:assets:tauri && run-script-os", "build:tauri:plugin:api": "cd src-tauri/plugins && yarn install && yarn workspaces foreach -Apt run build", "build:icon": "tauri icon ./src-tauri/icons/icon.png", "build:core": "cd core && yarn build && yarn pack", "build:web": "yarn workspace @janhq/web-app build", + "build:extensions-web": "yarn workspace @jan/extensions-web build", "build:extensions": "rimraf ./pre-install/*.tgz || true && yarn workspace @janhq/core build && cd extensions && yarn install && yarn workspaces foreach -Apt run build:publish", "prepare": "husky" }, diff --git a/scripts/download-bin.mjs b/scripts/download-bin.mjs index 44693ab79..a1884d940 100644 --- a/scripts/download-bin.mjs +++ b/scripts/download-bin.mjs @@ -136,6 +136,11 @@ async function main() { console.log("Error Found:", err); } }) + copyFile(path.join(binDir, 'bun'), path.join(binDir, 'bun-universal-apple-darwin'), (err) => { + if (err) { + console.log("Error Found:", err); + } + }) } else if (platform === 'linux') { copyFile(path.join(binDir, 'bun'), path.join(binDir, 'bun-x86_64-unknown-linux-gnu'), (err) => { if (err) { @@ -191,6 +196,11 @@ async function main() { console.log("Error Found:", err); } }) + copyFile(path.join(binDir, 'uv'), path.join(binDir, 'uv-universal-apple-darwin'), (err) => { + if (err) { + console.log("Error Found:", err); + } + }) } else if (platform === 'linux') { copyFile(path.join(binDir, 'uv'), path.join(binDir, 'uv-x86_64-unknown-linux-gnu'), (err) => { if (err) { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 013982c83..1cc42cd76 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -5180,6 +5180,7 @@ dependencies = [ "log", "nix", "rand 0.8.5", + "reqwest 0.11.27", "serde", "sha2", "sysinfo", diff --git a/src-tauri/capabilities/system-monitor-window.json b/src-tauri/capabilities/system-monitor-window.json index 572cc0840..740bb82cc 100644 --- a/src-tauri/capabilities/system-monitor-window.json +++ b/src-tauri/capabilities/system-monitor-window.json @@ -9,6 +9,11 @@ "core:window:allow-set-theme", "log:default", "core:webview:allow-create-webview-window", - "core:window:allow-set-focus" + "core:window:allow-set-focus", + "hardware:allow-get-system-info", + "hardware:allow-get-system-usage", + "llamacpp:allow-get-devices", + "llamacpp:allow-read-gguf-metadata", + "deep-link:allow-get-current" ] } diff --git a/src-tauri/tauri.bundle.windows.nsis.template b/src-tauri/tauri.bundle.windows.nsis.template index 2a216c4a6..2cd878dc2 100644 --- a/src-tauri/tauri.bundle.windows.nsis.template +++ b/src-tauri/tauri.bundle.windows.nsis.template @@ -698,6 +698,7 @@ Section Install CreateDirectory "$INSTDIR\resources\pre-install" SetOutPath $INSTDIR File /a "/oname=vulkan-1.dll" "D:\a\jan\jan\src-tauri\resources\lib\vulkan-1.dll" + File /a "/oname=LICENSE" "D:\a\jan\jan\src-tauri\resources\LICENSE" SetOutPath "$INSTDIR\resources\pre-install" File /nonfatal /a /r "D:\a\jan\jan\src-tauri\resources\pre-install\" SetOutPath $INSTDIR @@ -821,6 +822,9 @@ Section Uninstall ; Copy main executable Delete "$INSTDIR\${MAINBINARYNAME}.exe" + ; Delete LICENSE file + Delete "$INSTDIR\LICENSE" + ; Delete resources Delete "$INSTDIR\resources\pre-install\janhq-assistant-extension-1.0.2.tgz" Delete "$INSTDIR\resources\pre-install\janhq-conversational-extension-1.0.0.tgz" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index c5dcb9c1b..dd960fa5c 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -84,6 +84,7 @@ "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico" - ] + ], + "resources": ["resources/LICENSE"] } } diff --git a/src-tauri/tauri.linux.conf.json b/src-tauri/tauri.linux.conf.json index 48411fd3b..80e7446ff 100644 --- a/src-tauri/tauri.linux.conf.json +++ b/src-tauri/tauri.linux.conf.json @@ -1,12 +1,13 @@ { "bundle": { "targets": ["deb", "appimage"], - "resources": ["resources/pre-install/**/*"], + "resources": ["resources/pre-install/**/*", "resources/LICENSE"], "externalBin": ["resources/bin/uv"], "linux": { "appimage": { "bundleMediaFramework": false, - "files": {} + "files": { + } }, "deb": { "files": { diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.json index 6edec72eb..d7d80f669 100644 --- a/src-tauri/tauri.macos.conf.json +++ b/src-tauri/tauri.macos.conf.json @@ -1,7 +1,7 @@ { "bundle": { "targets": ["app", "dmg"], - "resources": ["resources/pre-install/**/*"], + "resources": ["resources/pre-install/**/*", "resources/LICENSE"], "externalBin": ["resources/bin/bun", "resources/bin/uv"] } } diff --git a/web-app/.gitignore b/web-app/.gitignore index a547bf36d..9c7112343 100644 --- a/web-app/.gitignore +++ b/web-app/.gitignore @@ -10,6 +10,7 @@ lerna-debug.log* node_modules dist dist-ssr +dist-web *.local # Editor directories and files diff --git a/web-app/index.html b/web-app/index.html index e4b78eae1..fc264d096 100644 --- a/web-app/index.html +++ b/web-app/index.html @@ -2,9 +2,11 @@ - + + + - Vite + React + TS + Jan
diff --git a/web-app/package.json b/web-app/package.json index 84658ef86..2d080d0e6 100644 --- a/web-app/package.json +++ b/web-app/package.json @@ -9,12 +9,19 @@ "lint": "eslint .", "preview": "vite preview", "test": "vitest --run", - "test:coverage": "vitest --coverage --run" + "test:coverage": "vitest --coverage --run", + "dev:web": "vite --config vite.config.web.ts", + "build:web": "yarn tsc -b tsconfig.web.json && vite build --config vite.config.web.ts", + "preview:web": "vite preview --config vite.config.web.ts --outDir dist-web", + "serve:web": "npx serve dist-web -p 3001 -s", + "serve:web:alt": "npx http-server dist-web -p 3001 --proxy http://localhost:3001? -o", + "build:serve:web": "yarn build:web && yarn serve:web" }, "dependencies": { "@dnd-kit/core": "^6.3.1", "@dnd-kit/modifiers": "^9.0.0", "@dnd-kit/sortable": "^10.0.0", + "@jan/extensions-web": "link:../extensions-web", "@janhq/core": "link:../core", "@radix-ui/react-accordion": "^1.2.10", "@radix-ui/react-dialog": "^1.1.14", @@ -107,11 +114,13 @@ "istanbul-lib-report": "^3.0.1", "istanbul-reports": "^3.1.7", "jsdom": "^26.1.0", + "serve": "^14.2.4", "tailwind-merge": "^3.3.1", "typescript": "~5.8.3", "typescript-eslint": "^8.26.1", "vite": "^6.3.0", "vite-plugin-node-polyfills": "^0.23.0", + "vite-plugin-pwa": "^1.0.3", "vitest": "^3.1.3" } } diff --git a/web-app/public/images/jan-logo.png b/web-app/public/images/jan-logo.png new file mode 100644 index 000000000..c16023e94 Binary files /dev/null and b/web-app/public/images/jan-logo.png differ diff --git a/web-app/public/images/model-provider/jan.png b/web-app/public/images/model-provider/jan.png new file mode 100644 index 000000000..c16023e94 Binary files /dev/null and b/web-app/public/images/model-provider/jan.png differ diff --git a/web-app/src/components/ui/hover-card.tsx b/web-app/src/components/ui/hover-card.tsx index 00236b08a..a06451ead 100644 --- a/web-app/src/components/ui/hover-card.tsx +++ b/web-app/src/components/ui/hover-card.tsx @@ -6,7 +6,14 @@ import { cn } from '@/lib/utils' function HoverCard({ ...props }: React.ComponentProps) { - return + return ( + + ) } function HoverCardTrigger({ diff --git a/web-app/src/containers/ApiKeyInput.tsx b/web-app/src/containers/ApiKeyInput.tsx index 394df5696..b3dc51b3f 100644 --- a/web-app/src/containers/ApiKeyInput.tsx +++ b/web-app/src/containers/ApiKeyInput.tsx @@ -3,15 +3,18 @@ import { useLocalApiServer } from '@/hooks/useLocalApiServer' import { useState, useEffect, useCallback } from 'react' import { Eye, EyeOff } from 'lucide-react' import { useTranslation } from '@/i18n/react-i18next-compat' +import { cn } from '@/lib/utils' interface ApiKeyInputProps { showError?: boolean onValidationChange?: (isValid: boolean) => void + isServerRunning?: boolean } export function ApiKeyInput({ showError = false, onValidationChange, + isServerRunning, }: ApiKeyInputProps) { const { apiKey, setApiKey } = useLocalApiServer() const [inputValue, setInputValue] = useState(apiKey.toString()) @@ -19,16 +22,19 @@ export function ApiKeyInput({ const [error, setError] = useState('') const { t } = useTranslation() - const validateApiKey = useCallback((value: string) => { - if (!value || value.trim().length === 0) { - setError(t('common:apiKeyRequired')) - onValidationChange?.(false) - return false - } - setError('') - onValidationChange?.(true) - return true - }, [onValidationChange, t]) + const validateApiKey = useCallback( + (value: string) => { + if (!value || value.trim().length === 0) { + setError(t('common:apiKeyRequired')) + onValidationChange?.(false) + return false + } + setError('') + onValidationChange?.(true) + return true + }, + [onValidationChange, t] + ) useEffect(() => { if (showError) { @@ -64,11 +70,12 @@ export function ApiKeyInput({ value={inputValue} onChange={handleChange} onBlur={handleBlur} - className={`w-full text-sm pr-10 ${ - hasError - ? 'border-1 border-destructive focus:border-destructive focus:ring-destructive' - : '' - }`} + className={cn( + 'w-full text-sm pr-10', + hasError && + 'border-1 border-destructive focus:border-destructive focus:ring-destructive', + isServerRunning && 'opacity-50 pointer-events-none' + )} placeholder={t('common:enterApiKey')} />
diff --git a/web-app/src/containers/ApiPrefixInput.tsx b/web-app/src/containers/ApiPrefixInput.tsx index ff728f96d..7db60efdb 100644 --- a/web-app/src/containers/ApiPrefixInput.tsx +++ b/web-app/src/containers/ApiPrefixInput.tsx @@ -1,8 +1,13 @@ import { Input } from '@/components/ui/input' import { useLocalApiServer } from '@/hooks/useLocalApiServer' +import { cn } from '@/lib/utils' import { useState } from 'react' -export function ApiPrefixInput() { +export function ApiPrefixInput({ + isServerRunning, +}: { + isServerRunning?: boolean +}) { const { apiPrefix, setApiPrefix } = useLocalApiServer() const [inputValue, setInputValue] = useState(apiPrefix) @@ -27,7 +32,10 @@ export function ApiPrefixInput() { value={inputValue} onChange={handleChange} onBlur={handleBlur} - className="w-24 h-8 text-sm" + className={cn( + 'w-24 h-8 text-sm', + isServerRunning && 'opacity-50 pointer-events-none' + )} placeholder="/v1" /> ) diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx index 0fa7a4b32..ffa9a0245 100644 --- a/web-app/src/containers/ChatInput.tsx +++ b/web-app/src/containers/ChatInput.tsx @@ -32,8 +32,7 @@ import { useChat } from '@/hooks/useChat' import DropdownModelProvider from '@/containers/DropdownModelProvider' import { ModelLoader } from '@/containers/loaders/ModelLoader' import DropdownToolsAvailable from '@/containers/DropdownToolsAvailable' -import { getConnectedServers } from '@/services/mcp' -import { checkMmprojExists } from '@/services/models' +import { useServiceHub } from '@/hooks/useServiceHub' type ChatInputProps = { className?: string @@ -46,6 +45,7 @@ const ChatInput = ({ model, className, initialMessage }: ChatInputProps) => { const textareaRef = useRef(null) const [isFocused, setIsFocused] = useState(false) const [rows, setRows] = useState(1) + const serviceHub = useServiceHub() const { streamingContent, abortControllers, @@ -82,7 +82,7 @@ const ChatInput = ({ model, className, initialMessage }: ChatInputProps) => { useEffect(() => { const checkConnectedServers = async () => { try { - const servers = await getConnectedServers() + const servers = await serviceHub.mcp().getConnectedServers() setConnectedServers(servers) } catch (error) { console.error('Failed to get connected servers:', error) @@ -96,20 +96,26 @@ const ChatInput = ({ model, className, initialMessage }: ChatInputProps) => { const intervalId = setInterval(checkConnectedServers, 3000) return () => clearInterval(intervalId) - }, []) + }, [serviceHub]) // Check for mmproj existence or vision capability when model changes useEffect(() => { const checkMmprojSupport = async () => { - if (selectedModel?.id) { + if (selectedModel && selectedModel?.id) { try { // Only check mmproj for llamacpp provider if (selectedProvider === 'llamacpp') { - const hasLocalMmproj = await checkMmprojExists(selectedModel.id) + const hasLocalMmproj = await serviceHub.models().checkMmprojExists(selectedModel.id) setHasMmproj(hasLocalMmproj) - } else { - // For non-llamacpp providers, only check vision capability + } + // For non-llamacpp providers, only check vision capability + else if ( + selectedProvider !== 'llamacpp' && + selectedModel?.capabilities?.includes('vision') + ) { setHasMmproj(true) + } else { + setHasMmproj(false) } } catch (error) { console.error('Error checking mmproj:', error) @@ -119,7 +125,7 @@ const ChatInput = ({ model, className, initialMessage }: ChatInputProps) => { } checkMmprojSupport() - }, [selectedModel?.id, selectedProvider]) + }, [selectedModel, selectedModel?.capabilities, selectedProvider, serviceHub]) // Check if there are active MCP servers const hasActiveMCPServers = connectedServers.length > 0 || tools.length > 0 @@ -368,44 +374,109 @@ const ChatInput = ({ model, className, initialMessage }: ChatInputProps) => { } } - const handlePaste = (e: React.ClipboardEvent) => { - const clipboardItems = e.clipboardData?.items - if (!clipboardItems) return + const handlePaste = async (e: React.ClipboardEvent) => { + // Only process images if model supports mmproj + if (hasMmproj) { + const clipboardItems = e.clipboardData?.items + let hasProcessedImage = false - // Only allow paste if model supports mmproj - if (!hasMmproj) { - return - } + // Try clipboardData.items first (traditional method) + if (clipboardItems && clipboardItems.length > 0) { + const imageItems = Array.from(clipboardItems).filter((item) => + item.type.startsWith('image/') + ) - const imageItems = Array.from(clipboardItems).filter((item) => - item.type.startsWith('image/') - ) + if (imageItems.length > 0) { + e.preventDefault() - if (imageItems.length > 0) { - e.preventDefault() + const files: File[] = [] + let processedCount = 0 - const files: File[] = [] - let processedCount = 0 + imageItems.forEach((item) => { + const file = item.getAsFile() + if (file) { + files.push(file) + } + processedCount++ - imageItems.forEach((item) => { - const file = item.getAsFile() - if (file) { - files.push(file) + // When all items are processed, handle the valid files + if (processedCount === imageItems.length) { + if (files.length > 0) { + const syntheticEvent = { + target: { + files: files, + }, + } as unknown as React.ChangeEvent + + handleFileChange(syntheticEvent) + hasProcessedImage = true + } + } + }) + + // If we found image items but couldn't get files, fall through to modern API + if (processedCount === imageItems.length && !hasProcessedImage) { + // Continue to modern clipboard API fallback below + } else { + return // Successfully processed with traditional method + } } - processedCount++ + } - // When all items are processed, handle the valid files - if (processedCount === imageItems.length && files.length > 0) { - const syntheticEvent = { - target: { - files: files, - }, - } as unknown as React.ChangeEvent + // Modern Clipboard API fallback (for Linux, images copied from web, etc.) + if ( + navigator.clipboard && + 'read' in navigator.clipboard && + !hasProcessedImage + ) { + try { + const clipboardContents = await navigator.clipboard.read() + const files: File[] = [] - handleFileChange(syntheticEvent) + for (const item of clipboardContents) { + const imageTypes = item.types.filter((type) => + type.startsWith('image/') + ) + + for (const type of imageTypes) { + try { + const blob = await item.getType(type) + // Convert blob to File with better naming + const extension = type.split('/')[1] || 'png' + const file = new File( + [blob], + `pasted-image-${Date.now()}.${extension}`, + { type } + ) + files.push(file) + } catch (error) { + console.error('Error reading clipboard item:', error) + } + } + } + + if (files.length > 0) { + e.preventDefault() + const syntheticEvent = { + target: { + files: files, + }, + } as unknown as React.ChangeEvent + + handleFileChange(syntheticEvent) + return + } + } catch (error) { + console.error('Clipboard API access failed:', error) } - }) + } + + // If we reach here, no image was found - allow normal text pasting to continue + console.log( + 'No image data found in clipboard, allowing normal text paste' + ) } + // If hasMmproj is false or no images found, allow normal text pasting to continue } return ( @@ -500,7 +571,7 @@ const ChatInput = ({ model, className, initialMessage }: ChatInputProps) => { // When Shift+Enter is pressed, a new line is added (default behavior) } }} - onPaste={hasMmproj ? handlePaste : undefined} + onPaste={handlePaste} placeholder={t('common:placeholder.chatInput')} autoFocus spellCheck={spellCheckChatInput} @@ -535,29 +606,41 @@ const ChatInput = ({ model, className, initialMessage }: ChatInputProps) => { )} {/* File attachment - show only for models with mmproj */} {hasMmproj && ( -
- - -
+ + + +
+ + +
+
+ +

{t('vision')}

+
+
+
)} {/* Microphone - always available - Temp Hide */} - {/*
+ {/*
*/} {selectedModel?.capabilities?.includes('embeddings') && ( -
+
{ return (
@@ -632,7 +715,7 @@ const ChatInput = ({ model, className, initialMessage }: ChatInputProps) => { -
+
{ -
+
{ - abortDownload(download.name).then(() => { + serviceHub.models().abortDownload(download.name).then(() => { toast.info( t('common:toast.downloadCancelled.title'), { diff --git a/web-app/src/containers/DropdownModelProvider.tsx b/web-app/src/containers/DropdownModelProvider.tsx index 005580890..303fe2a37 100644 --- a/web-app/src/containers/DropdownModelProvider.tsx +++ b/web-app/src/containers/DropdownModelProvider.tsx @@ -20,10 +20,9 @@ import { localStorageKey } from '@/constants/localStorage' import { useTranslation } from '@/i18n/react-i18next-compat' import { useFavoriteModel } from '@/hooks/useFavoriteModel' import { predefinedProviders } from '@/consts/providers' -import { - checkMmprojExistsAndUpdateOffloadMMprojSetting, - checkMmprojExists, -} from '@/services/models' +import { useServiceHub } from '@/hooks/useServiceHub' +import { PlatformFeatures } from '@/lib/platform/const' +import { PlatformFeature } from '@/lib/platform/types' type DropdownModelProviderProps = { model?: ThreadModel @@ -78,6 +77,7 @@ const DropdownModelProvider = ({ const navigate = useNavigate() const { t } = useTranslation() const { favoriteModels } = useFavoriteModel() + const serviceHub = useServiceHub() // Search state const [open, setOpen] = useState(false) @@ -107,7 +107,7 @@ const DropdownModelProvider = ({ const checkAndUpdateModelVisionCapability = useCallback( async (modelId: string) => { try { - const hasVision = await checkMmprojExists(modelId) + const hasVision = await serviceHub.models().checkMmprojExists(modelId) if (hasVision) { // Update the model capabilities to include 'vision' const provider = getProviderByName('llamacpp') @@ -136,7 +136,7 @@ const DropdownModelProvider = ({ console.debug('Error checking mmproj for model:', modelId, error) } }, - [getProviderByName, updateProvider] + [getProviderByName, updateProvider, serviceHub] ) // Initialize model provider only once @@ -150,7 +150,7 @@ const DropdownModelProvider = ({ } // Check mmproj existence for llamacpp models if (model?.provider === 'llamacpp') { - await checkMmprojExistsAndUpdateOffloadMMprojSetting( + await serviceHub.models().checkMmprojExistsAndUpdateOffloadMMprojSetting( model.id as string, updateProvider, getProviderByName @@ -164,7 +164,7 @@ const DropdownModelProvider = ({ if (lastUsed && checkModelExists(lastUsed.provider, lastUsed.model)) { selectModelProvider(lastUsed.provider, lastUsed.model) if (lastUsed.provider === 'llamacpp') { - await checkMmprojExistsAndUpdateOffloadMMprojSetting( + await serviceHub.models().checkMmprojExistsAndUpdateOffloadMMprojSetting( lastUsed.model, updateProvider, getProviderByName @@ -173,8 +173,28 @@ const DropdownModelProvider = ({ await checkAndUpdateModelVisionCapability(lastUsed.model) } } else { + // For web-only builds, auto-select the first model from jan provider + if (PlatformFeatures[PlatformFeature.WEB_AUTO_MODEL_SELECTION]) { + const janProvider = providers.find( + (p) => p.provider === 'jan' && p.active && p.models.length > 0 + ) + if (janProvider && janProvider.models.length > 0) { + const firstModel = janProvider.models[0] + selectModelProvider(janProvider.provider, firstModel.id) + return + } + } selectModelProvider('', '') } + } else if (PlatformFeatures[PlatformFeature.WEB_AUTO_MODEL_SELECTION] && !selectedModel) { + // For web-only builds, always auto-select the first model from jan provider if none is selected + const janProvider = providers.find( + (p) => p.provider === 'jan' && p.active && p.models.length > 0 + ) + if (janProvider && janProvider.models.length > 0) { + const firstModel = janProvider.models[0] + selectModelProvider(janProvider.provider, firstModel.id) + } } } @@ -189,6 +209,8 @@ const DropdownModelProvider = ({ updateProvider, getProviderByName, checkAndUpdateModelVisionCapability, + serviceHub, + selectedModel, ]) // Update display model when selection changes @@ -354,7 +376,7 @@ const DropdownModelProvider = ({ // Check mmproj existence for llamacpp models if (searchableModel.provider.provider === 'llamacpp') { - await checkMmprojExistsAndUpdateOffloadMMprojSetting( + await serviceHub.models().checkMmprojExistsAndUpdateOffloadMMprojSetting( searchableModel.model.id, updateProvider, getProviderByName @@ -380,6 +402,7 @@ const DropdownModelProvider = ({ updateProvider, getProviderByName, checkAndUpdateModelVisionCapability, + serviceHub, ] ) @@ -414,13 +437,15 @@ const DropdownModelProvider = ({ - {currentModel?.settings && provider && ( - - )} + {currentModel?.settings && + provider && + provider.provider === 'llamacpp' && ( + + )}
-
{ - e.stopPropagation() - navigate({ - to: route.settings.providers, - params: { providerName: providerInfo.provider }, - }) - setOpen(false) - }} - > - -
+ {PlatformFeatures[PlatformFeature.MODEL_PROVIDER_SETTINGS] && ( +
{ + e.stopPropagation() + navigate({ + to: route.settings.providers, + params: { providerName: providerInfo.provider }, + }) + setOpen(false) + }} + > + +
+ )}
{/* Models for this provider */} diff --git a/web-app/src/containers/LeftPanel.tsx b/web-app/src/containers/LeftPanel.tsx index 14cfba3aa..b019d318e 100644 --- a/web-app/src/containers/LeftPanel.tsx +++ b/web-app/src/containers/LeftPanel.tsx @@ -43,27 +43,33 @@ import { DownloadManagement } from '@/containers/DownloadManegement' import { useSmallScreen } from '@/hooks/useMediaQuery' import { useClickOutside } from '@/hooks/useClickOutside' import { useDownloadStore } from '@/hooks/useDownloadStore' +import { PlatformFeatures } from '@/lib/platform/const' +import { PlatformFeature } from '@/lib/platform/types' const mainMenus = [ { title: 'common:newChat', icon: IconCirclePlusFilled, route: route.home, + isEnabled: true, }, { title: 'common:assistants', icon: IconClipboardSmileFilled, route: route.assistant, + isEnabled: true, }, { title: 'common:hub', icon: IconAppsFilled, route: route.hub.index, + isEnabled: PlatformFeatures[PlatformFeature.MODEL_HUB], }, { title: 'common:settings', icon: IconSettingsFilled, route: route.settings.general, + isEnabled: true, }, ] @@ -473,6 +479,9 @@ const LeftPanel = () => {
{mainMenus.map((menu) => { + if (!menu.isEnabled) { + return null + } const isActive = currentPath.includes(route.settings.index) && menu.route.includes(route.settings.index) diff --git a/web-app/src/containers/ModelInfoHoverCard.tsx b/web-app/src/containers/ModelInfoHoverCard.tsx index e540bed1a..63f5f3183 100644 --- a/web-app/src/containers/ModelInfoHoverCard.tsx +++ b/web-app/src/containers/ModelInfoHoverCard.tsx @@ -4,12 +4,12 @@ import { HoverCardTrigger, } from '@/components/ui/hover-card' import { IconInfoCircle } from '@tabler/icons-react' -import { CatalogModel, ModelQuant } from '@/services/models' -import { extractDescription } from '@/lib/models' +import { CatalogModel, ModelQuant } from '@/services/models/types' interface ModelInfoHoverCardProps { model: CatalogModel variant?: ModelQuant + isDefaultVariant?: boolean defaultModelQuantizations: string[] modelSupportStatus: Record onCheckModelSupport: (variant: ModelQuant) => void @@ -19,15 +19,15 @@ interface ModelInfoHoverCardProps { export const ModelInfoHoverCard = ({ model, variant, + isDefaultVariant, defaultModelQuantizations, modelSupportStatus, onCheckModelSupport, children, }: ModelInfoHoverCardProps) => { - const isVariantMode = !!variant const displayVariant = variant || - model.quants.find((m) => + model.quants.find((m: ModelQuant) => defaultModelQuantizations.some((e) => m.model_id.toLowerCase().includes(e) ) @@ -79,6 +79,15 @@ export const ModelInfoHoverCard = ({
) + } else if (status === 'GREY') { + return ( +
+
+ + Unable to determine model compatibility with your current device + +
+ ) } else { return (
@@ -95,8 +104,8 @@ export const ModelInfoHoverCard = ({ {children || (
)} @@ -106,10 +115,10 @@ export const ModelInfoHoverCard = ({ {/* Header */}

- {isVariantMode ? variant.model_id : model.model_name} + {!isDefaultVariant ? variant?.model_id : model?.model_name}

- {isVariantMode + {!isDefaultVariant ? 'Model Variant Information' : 'Model Information'}

@@ -118,57 +127,19 @@ export const ModelInfoHoverCard = ({ {/* Main Info Grid */}
- {isVariantMode ? ( - <> -
- - File Size - - - {variant.file_size} - -
-
- - Quantization - - - {variant.model_id.split('-').pop()?.toUpperCase() || - 'N/A'} - -
- - ) : ( - <> -
- - Downloads - - - {model.downloads?.toLocaleString() || '0'} - -
-
- Variants - - {model.quants?.length || 0} - -
- - )} + <> +
+ + {isDefaultVariant ? 'Default Quantization' : 'Quantization'} + + + {variant?.model_id.split('-').pop()?.toUpperCase() || 'N/A'} + +
+
- {!isVariantMode && ( -
- - Default Size - - - {displayVariant?.file_size || 'N/A'} - -
- )}
Compatibility @@ -204,21 +175,6 @@ export const ModelInfoHoverCard = ({
)} - - {/* Content Section */} -
-
- {isVariantMode ? 'Download URL' : 'Description'} -
-
- {isVariantMode ? ( -
{variant.path}
- ) : ( - extractDescription(model?.description) || - 'No description available' - )} -
-
diff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsx index b3bb55e40..a18f5184a 100644 --- a/web-app/src/containers/ModelSetting.tsx +++ b/web-app/src/containers/ModelSetting.tsx @@ -11,7 +11,7 @@ import { } from '@/components/ui/sheet' import { DynamicControllerSetting } from '@/containers/dynamicControllerSetting' import { useModelProvider } from '@/hooks/useModelProvider' -import { stopModel } from '@/services/models' +import { useServiceHub } from '@/hooks/useServiceHub' import { cn } from '@/lib/utils' import { useTranslation } from '@/i18n/react-i18next-compat' @@ -28,10 +28,11 @@ export function ModelSetting({ }: ModelSettingProps) { const { updateProvider } = useModelProvider() const { t } = useTranslation() + const serviceHub = useServiceHub() // Create a debounced version of stopModel that waits 500ms after the last call const debouncedStopModel = debounce((modelId: string) => { - stopModel(modelId) + serviceHub.models().stopModel(modelId) }, 500) const handleSettingChange = ( diff --git a/web-app/src/containers/ModelSupportStatus.tsx b/web-app/src/containers/ModelSupportStatus.tsx index 3667f4461..560880a11 100644 --- a/web-app/src/containers/ModelSupportStatus.tsx +++ b/web-app/src/containers/ModelSupportStatus.tsx @@ -6,8 +6,8 @@ import { TooltipProvider, TooltipTrigger, } from '@/components/ui/tooltip' -import { isModelSupported } from '@/services/models' -import { getJanDataFolderPath, joinPath } from '@janhq/core' +import { getJanDataFolderPath, joinPath, fs } from '@janhq/core' +import { useServiceHub } from '@/hooks/useServiceHub' interface ModelSupportStatusProps { modelId: string | undefined @@ -23,20 +23,21 @@ export const ModelSupportStatus = ({ className, }: ModelSupportStatusProps) => { const [modelSupportStatus, setModelSupportStatus] = useState< - 'RED' | 'YELLOW' | 'GREEN' | 'LOADING' | null + 'RED' | 'YELLOW' | 'GREEN' | 'LOADING' | null | 'GREY' >(null) + const serviceHub = useServiceHub() // Helper function to check model support with proper path resolution const checkModelSupportWithPath = useCallback( async ( id: string, ctxSize: number - ): Promise<'RED' | 'YELLOW' | 'GREEN'> => { + ): Promise<'RED' | 'YELLOW' | 'GREEN' | 'GREY' | null> => { try { - // Get Jan's data folder path and construct the full model file path - // Following the llamacpp extension structure: /llamacpp/models//model.gguf const janDataFolder = await getJanDataFolderPath() - const modelFilePath = await joinPath([ + + // First try the standard downloaded model path + const ggufModelPath = await joinPath([ janDataFolder, 'llamacpp', 'models', @@ -44,17 +45,50 @@ export const ModelSupportStatus = ({ 'model.gguf', ]) - return await isModelSupported(modelFilePath, ctxSize) + // Check if the standard model.gguf file exists + if (await fs.existsSync(ggufModelPath)) { + return await serviceHub.models().isModelSupported(ggufModelPath, ctxSize) + } + + // If model.gguf doesn't exist, try reading from model.yml (for imported models) + const modelConfigPath = await joinPath([ + janDataFolder, + 'llamacpp', + 'models', + id, + 'model.yml', + ]) + + if (!(await fs.existsSync(modelConfigPath))) { + console.error( + `Neither model.gguf nor model.yml found for model: ${id}` + ) + return null + } + + // Read the model configuration to get the actual model path + const modelConfig = await serviceHub.app().readYaml<{ model_path: string }>( + `llamacpp/models/${id}/model.yml` + ) + + // Handle both absolute and relative paths + const actualModelPath = + modelConfig.model_path.startsWith('/') || + modelConfig.model_path.match(/^[A-Za-z]:/) + ? modelConfig.model_path // absolute path, use as-is + : await joinPath([janDataFolder, modelConfig.model_path]) // relative path, join with data folder + + return await serviceHub.models().isModelSupported(actualModelPath, ctxSize) } catch (error) { console.error( - 'Error checking model support with constructed path:', + 'Error checking model support with path resolution:', error ) // If path construction or model support check fails, assume not supported - return 'RED' + return null } }, - [] + [serviceHub] ) // Helper function to get icon color based on model support status diff --git a/web-app/src/containers/PortInput.tsx b/web-app/src/containers/PortInput.tsx index 2bf783908..2235a9ef7 100644 --- a/web-app/src/containers/PortInput.tsx +++ b/web-app/src/containers/PortInput.tsx @@ -1,8 +1,9 @@ import { Input } from '@/components/ui/input' import { useLocalApiServer } from '@/hooks/useLocalApiServer' +import { cn } from '@/lib/utils' import { useState } from 'react' -export function PortInput() { +export function PortInput({ isServerRunning }: { isServerRunning?: boolean }) { const { serverPort, setServerPort } = useLocalApiServer() const [inputValue, setInputValue] = useState(serverPort.toString()) @@ -29,7 +30,10 @@ export function PortInput() { value={inputValue} onChange={handleChange} onBlur={handleBlur} - className="w-24 h-8 text-sm" + className={cn( + 'w-24 h-8 text-sm', + isServerRunning && 'opacity-50 pointer-events-none' + )} /> ) } diff --git a/web-app/src/containers/RenderMarkdown.tsx b/web-app/src/containers/RenderMarkdown.tsx index bfcb1608d..125994eab 100644 --- a/web-app/src/containers/RenderMarkdown.tsx +++ b/web-app/src/containers/RenderMarkdown.tsx @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable react-hooks/exhaustive-deps */ import ReactMarkdown, { Components } from 'react-markdown' import remarkGfm from 'remark-gfm' @@ -7,8 +6,7 @@ import remarkMath from 'remark-math' import rehypeKatex from 'rehype-katex' import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter' import * as prismStyles from 'react-syntax-highlighter/dist/cjs/styles/prism' -import { memo, useState, useMemo } from 'react' -import virtualizedRenderer from 'react-syntax-highlighter-virtualized-renderer' +import { memo, useState, useMemo, useRef, useEffect } from 'react' import { getReadableLanguageName } from '@/lib/utils' import { cn } from '@/lib/utils' import { useCodeblock } from '@/hooks/useCodeblock' @@ -39,6 +37,13 @@ function RenderMarkdownComponent({ // State for tracking which code block has been copied const [copiedId, setCopiedId] = useState(null) + // Map to store unique IDs for code blocks based on content and position + const codeBlockIds = useRef(new Map()) + + // Clear ID map when content changes + useEffect(() => { + codeBlockIds.current.clear() + }, [content]) // Function to handle copying code to clipboard const handleCopy = (code: string, id: string) => { @@ -51,17 +56,6 @@ function RenderMarkdownComponent({ }, 2000) } - // Simple hash function for strings - const hashString = (str: string): string => { - let hash = 0 - for (let i = 0; i < str.length; i++) { - const char = str.charCodeAt(i) - hash = (hash << 5) - hash + char - hash = hash & hash // Convert to 32bit integer - } - return Math.abs(hash).toString(36) - } - // Default components for syntax highlighting and emoji rendering const defaultComponents: Components = useMemo( () => ({ @@ -72,10 +66,13 @@ function RenderMarkdownComponent({ const code = String(children).replace(/\n$/, '') - // Generate a stable ID based on code content and language - const codeId = `code-${hashString(code.substring(0, 40) + language)}` - - const shouldVirtualize = code.split('\n').length > 300 + // Generate a unique ID based on content and language + const contentKey = `${code}-${language}` + let codeId = codeBlockIds.current.get(contentKey) + if (!codeId) { + codeId = `code-${codeBlockIds.current.size}` + codeBlockIds.current.set(contentKey, codeId) + } return !isInline && !isUser ? (
@@ -147,11 +144,6 @@ function RenderMarkdownComponent({ overflow: 'auto', border: 'none', }} - renderer={ - shouldVirtualize - ? (virtualizedRenderer() as (props: any) => React.ReactNode) - : undefined - } PreTag="div" CodeTag={'code'} {...props} @@ -164,7 +156,7 @@ function RenderMarkdownComponent({ ) }, }), - [codeBlockStyle, showLineNumbers, copiedId, handleCopy, hashString] + [codeBlockStyle, showLineNumbers, copiedId] ) // Memoize the remarkPlugins to prevent unnecessary re-renders diff --git a/web-app/src/containers/ServerHostSwitcher.tsx b/web-app/src/containers/ServerHostSwitcher.tsx index 1643d71ff..ee05908ab 100644 --- a/web-app/src/containers/ServerHostSwitcher.tsx +++ b/web-app/src/containers/ServerHostSwitcher.tsx @@ -4,6 +4,7 @@ import { DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu' + import { useLocalApiServer } from '@/hooks/useLocalApiServer' import { cn } from '@/lib/utils' @@ -12,12 +13,19 @@ const hostOptions = [ { value: '0.0.0.0', label: '0.0.0.0' }, ] -export function ServerHostSwitcher() { +export function ServerHostSwitcher({ + isServerRunning, +}: { + isServerRunning?: boolean +}) { const { serverHost, setServerHost } = useLocalApiServer() return ( - + { const { t } = useTranslation() @@ -25,7 +27,17 @@ const SettingsMenu = () => { const { providers } = useModelProvider() // Filter providers that have active API keys (or are llama.cpp which doesn't need one) - const activeProviders = providers.filter((provider) => provider.active) + // On web: exclude llamacpp provider as it's not available + const activeProviders = providers.filter((provider) => { + if (!provider.active) return false + + // On web version, hide llamacpp provider + if (!PlatformFeatures[PlatformFeature.LOCAL_INFERENCE] && provider.provider === 'llama.cpp') { + return false + } + + return true + }) // Check if current route has a providerName parameter and expand providers submenu useEffect(() => { @@ -55,43 +67,62 @@ const SettingsMenu = () => { { title: 'common:general', route: route.settings.general, + hasSubMenu: false, + isEnabled: true, }, { title: 'common:appearance', route: route.settings.appearance, + hasSubMenu: false, + isEnabled: true, }, { title: 'common:privacy', route: route.settings.privacy, + hasSubMenu: false, + isEnabled: PlatformFeatures[PlatformFeature.ANALYTICS], }, { title: 'common:modelProviders', route: route.settings.model_providers, hasSubMenu: activeProviders.length > 0, + isEnabled: PlatformFeatures[PlatformFeature.MODEL_PROVIDER_SETTINGS], }, { title: 'common:keyboardShortcuts', route: route.settings.shortcuts, + hasSubMenu: false, + isEnabled: true, }, { title: 'common:hardware', route: route.settings.hardware, + hasSubMenu: false, + isEnabled: PlatformFeatures[PlatformFeature.HARDWARE_MONITORING], }, { title: 'common:mcp-servers', route: route.settings.mcp_servers, + hasSubMenu: false, + isEnabled: PlatformFeatures[PlatformFeature.MCP_SERVERS], }, { title: 'common:local_api_server', route: route.settings.local_api_server, + hasSubMenu: false, + isEnabled: PlatformFeatures[PlatformFeature.LOCAL_API_SERVER], }, { title: 'common:https_proxy', route: route.settings.https_proxy, + hasSubMenu: false, + isEnabled: PlatformFeatures[PlatformFeature.HTTPS_PROXY], }, { title: 'common:extensions', route: route.settings.extensions, + hasSubMenu: false, + isEnabled: PlatformFeatures[PlatformFeature.EXTENSION_MANAGEMENT], }, ] @@ -126,7 +157,11 @@ const SettingsMenu = () => { )} >
- {menuSettings.map((menu) => ( + {menuSettings.map((menu) => { + if (!menu.isEnabled) { + return null + } + return (
{
)}
- ))} + ) + })}
diff --git a/web-app/src/containers/SetupScreen.tsx b/web-app/src/containers/SetupScreen.tsx index e9867b38a..812ed6493 100644 --- a/web-app/src/containers/SetupScreen.tsx +++ b/web-app/src/containers/SetupScreen.tsx @@ -11,7 +11,7 @@ function SetupScreen() { const { t } = useTranslation() const { providers } = useModelProvider() const firstItemRemoteProvider = - providers.length > 0 ? providers[1].provider : 'openai' + providers.length > 0 ? providers[1]?.provider : 'openai' // Check if setup tour has been completed const isSetupCompleted = diff --git a/web-app/src/containers/ThreadContent.tsx b/web-app/src/containers/ThreadContent.tsx index a5a872b3e..fc7306142 100644 --- a/web-app/src/containers/ThreadContent.tsx +++ b/web-app/src/containers/ThreadContent.tsx @@ -40,6 +40,7 @@ import TokenSpeedIndicator from '@/containers/TokenSpeedIndicator' import CodeEditor from '@uiw/react-textarea-code-editor' import '@uiw/react-textarea-code-editor/dist.css' import { useTranslation } from '@/i18n/react-i18next-compat' +import { useModelProvider } from '@/hooks/useModelProvider' const CopyButton = ({ text }: { text: string }) => { const [copied, setCopied] = useState(false) @@ -152,6 +153,7 @@ export const ThreadContent = memo( } ) => { const { t } = useTranslation() + const { selectedModel } = useModelProvider() // Use useMemo to stabilize the components prop const linkComponents = useMemo( @@ -517,7 +519,7 @@ export const ThreadContent = memo( - {item.isLastMessage && ( + {item.isLastMessage && selectedModel && (
- - - - handleCapabilityChange('vision', checked) - } - /> - - - {t('providers:editModel.notAvailable')} - - + + handleCapabilityChange('vision', checked) + } + />
-
+ {/*
@@ -216,7 +204,7 @@ export const DialogEditModel = ({ {t('providers:editModel.notAvailable')} -
+
*/} {/*
diff --git a/web-app/src/hooks/__tests__/useAppUpdater.test.ts b/web-app/src/hooks/__tests__/useAppUpdater.test.ts index 2c736f0f3..1cbd96afe 100644 --- a/web-app/src/hooks/__tests__/useAppUpdater.test.ts +++ b/web-app/src/hooks/__tests__/useAppUpdater.test.ts @@ -34,8 +34,26 @@ vi.mock('@/types/events', () => ({ }, })) -vi.mock('@/services/models', () => ({ - stopAllModels: vi.fn(), +// Mock the ServiceHub +const mockStopAllModels = vi.fn() +const mockUpdaterCheck = vi.fn() +const mockUpdaterDownloadAndInstall = vi.fn() +const mockUpdaterDownloadAndInstallWithProgress = vi.fn() +const mockEventsEmit = vi.fn() +vi.mock('@/hooks/useServiceHub', () => ({ + getServiceHub: () => ({ + models: () => ({ + stopAllModels: mockStopAllModels, + }), + updater: () => ({ + check: mockUpdaterCheck, + downloadAndInstall: mockUpdaterDownloadAndInstall, + downloadAndInstallWithProgress: mockUpdaterDownloadAndInstallWithProgress, + }), + events: () => ({ + emit: mockEventsEmit, + }), + }), })) // Mock global window.core @@ -58,14 +76,11 @@ import { isDev } from '@/lib/utils' import { check } from '@tauri-apps/plugin-updater' import { events } from '@janhq/core' import { emit } from '@tauri-apps/api/event' -import { stopAllModels } from '@/services/models' describe('useAppUpdater', () => { const mockEvents = events as any - const mockCheck = check as any const mockIsDev = isDev as any const mockEmit = emit as any - const mockStopAllModels = stopAllModels as any const mockRelaunch = window.core?.api?.relaunch as any beforeEach(() => { @@ -131,7 +146,7 @@ describe('useAppUpdater', () => { version: '1.2.0', downloadAndInstall: vi.fn(), } - mockCheck.mockResolvedValue(mockUpdate) + mockUpdaterCheck.mockResolvedValue(mockUpdate) const { result } = renderHook(() => useAppUpdater()) @@ -140,7 +155,7 @@ describe('useAppUpdater', () => { updateResult = await result.current.checkForUpdate() }) - expect(mockCheck).toHaveBeenCalled() + expect(mockUpdaterCheck).toHaveBeenCalled() expect(result.current.updateState.isUpdateAvailable).toBe(true) expect(result.current.updateState.updateInfo).toBe(mockUpdate) expect(result.current.updateState.remindMeLater).toBe(false) @@ -148,7 +163,7 @@ describe('useAppUpdater', () => { }) it('should handle no update available', async () => { - mockCheck.mockResolvedValue(null) + mockUpdaterCheck.mockResolvedValue(null) const { result } = renderHook(() => useAppUpdater()) @@ -164,7 +179,7 @@ describe('useAppUpdater', () => { it('should handle errors during update check', async () => { const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - mockCheck.mockRejectedValue(new Error('Network error')) + mockUpdaterCheck.mockRejectedValue(new Error('Network error')) const { result } = renderHook(() => useAppUpdater()) @@ -185,7 +200,7 @@ describe('useAppUpdater', () => { }) it('should reset remindMeLater when requested', async () => { - mockCheck.mockResolvedValue(null) + mockUpdaterCheck.mockResolvedValue(null) const { result } = renderHook(() => useAppUpdater()) @@ -213,7 +228,7 @@ describe('useAppUpdater', () => { updateResult = await result.current.checkForUpdate() }) - expect(mockCheck).not.toHaveBeenCalled() + expect(mockUpdaterCheck).not.toHaveBeenCalled() expect(result.current.updateState.isUpdateAvailable).toBe(false) expect(updateResult).toBe(null) }) @@ -258,7 +273,7 @@ describe('useAppUpdater', () => { } // Mock check to return the update - mockCheck.mockResolvedValue(mockUpdate) + mockUpdaterCheck.mockResolvedValue(mockUpdate) const { result } = renderHook(() => useAppUpdater()) @@ -268,7 +283,7 @@ describe('useAppUpdater', () => { }) // Mock the download and install process - mockDownloadAndInstall.mockImplementation(async (progressCallback) => { + mockUpdaterDownloadAndInstallWithProgress.mockImplementation(async (progressCallback) => { // Simulate download events progressCallback({ event: 'Started', @@ -292,8 +307,8 @@ describe('useAppUpdater', () => { }) expect(mockStopAllModels).toHaveBeenCalled() - expect(mockEmit).toHaveBeenCalledWith('KILL_SIDECAR') - expect(mockDownloadAndInstall).toHaveBeenCalled() + expect(mockEventsEmit).toHaveBeenCalledWith('KILL_SIDECAR') + expect(mockUpdaterDownloadAndInstallWithProgress).toHaveBeenCalled() expect(mockRelaunch).toHaveBeenCalled() }) @@ -306,7 +321,7 @@ describe('useAppUpdater', () => { } // Mock check to return the update - mockCheck.mockResolvedValue(mockUpdate) + mockUpdaterCheck.mockResolvedValue(mockUpdate) const { result } = renderHook(() => useAppUpdater()) @@ -315,7 +330,7 @@ describe('useAppUpdater', () => { await result.current.checkForUpdate() }) - mockDownloadAndInstall.mockRejectedValue(new Error('Download failed')) + mockUpdaterDownloadAndInstallWithProgress.mockRejectedValue(new Error('Download failed')) await act(async () => { await result.current.downloadAndInstallUpdate() @@ -351,7 +366,7 @@ describe('useAppUpdater', () => { } // Mock check to return the update - mockCheck.mockResolvedValue(mockUpdate) + mockUpdaterCheck.mockResolvedValue(mockUpdate) const { result } = renderHook(() => useAppUpdater()) @@ -360,7 +375,7 @@ describe('useAppUpdater', () => { await result.current.checkForUpdate() }) - mockDownloadAndInstall.mockImplementation(async (progressCallback) => { + mockUpdaterDownloadAndInstallWithProgress.mockImplementation(async (progressCallback) => { progressCallback({ event: 'Started', data: { contentLength: 2000 }, diff --git a/web-app/src/hooks/__tests__/useAppearance.test.ts b/web-app/src/hooks/__tests__/useAppearance.test.ts index b421c7e26..74be4d3d2 100644 --- a/web-app/src/hooks/__tests__/useAppearance.test.ts +++ b/web-app/src/hooks/__tests__/useAppearance.test.ts @@ -31,7 +31,7 @@ vi.mock('zustand/middleware', () => ({ // Mock global constants Object.defineProperty(global, 'IS_WINDOWS', { value: false, writable: true }) Object.defineProperty(global, 'IS_LINUX', { value: false, writable: true }) -Object.defineProperty(global, 'IS_TAURI', { value: false, writable: true }) +Object.defineProperty(global, 'IS_WEB_APP', { value: false, writable: true }) describe('useAppearance', () => { beforeEach(() => { @@ -154,8 +154,8 @@ describe('useAppearance', () => { describe('Platform-specific behavior', () => { - it('should use alpha 1 for non-Tauri environments', () => { - Object.defineProperty(global, 'IS_TAURI', { value: false }) + it('should use alpha 1 for web environments', () => { + Object.defineProperty(global, 'IS_WEB_APP', { value: false }) Object.defineProperty(global, 'IS_WINDOWS', { value: true }) const { result } = renderHook(() => useAppearance()) diff --git a/web-app/src/hooks/__tests__/useLlamacppDevices.test.ts b/web-app/src/hooks/__tests__/useLlamacppDevices.test.ts index 6c5639b48..b8a5acdcf 100644 --- a/web-app/src/hooks/__tests__/useLlamacppDevices.test.ts +++ b/web-app/src/hooks/__tests__/useLlamacppDevices.test.ts @@ -1,11 +1,36 @@ import { renderHook, act } from '@testing-library/react' import { describe, it, expect, vi, beforeEach } from 'vitest' import { useLlamacppDevices } from '../useLlamacppDevices' -import { getLlamacppDevices } from '../../services/hardware' -// Mock the hardware service -vi.mock('@/services/hardware', () => ({ - getLlamacppDevices: vi.fn(), +// Mock the ServiceHub +const mockGetLlamacppDevices = vi.fn() +vi.mock('@/hooks/useServiceHub', () => ({ + getServiceHub: () => ({ + hardware: () => ({ + getLlamacppDevices: mockGetLlamacppDevices, + }), + providers: () => ({ + updateSettings: vi.fn().mockResolvedValue(undefined), + }), + }), +})) + +// Mock useModelProvider +const mockUpdateProvider = vi.fn() +vi.mock('../useModelProvider', () => ({ + useModelProvider: { + getState: () => ({ + getProviderByName: () => ({ + settings: [ + { + key: 'device', + controller_props: { value: '' }, + }, + ], + }), + updateProvider: mockUpdateProvider, + }), + }, })) // Mock the window.core object @@ -19,7 +44,6 @@ Object.defineProperty(window, 'core', { }) describe('useLlamacppDevices', () => { - const mockGetLlamacppDevices = vi.mocked(getLlamacppDevices) beforeEach(() => { vi.clearAllMocks() diff --git a/web-app/src/hooks/__tests__/useMCPServers.test.ts b/web-app/src/hooks/__tests__/useMCPServers.test.ts index 642a31007..e5256a549 100644 --- a/web-app/src/hooks/__tests__/useMCPServers.test.ts +++ b/web-app/src/hooks/__tests__/useMCPServers.test.ts @@ -3,10 +3,17 @@ import { renderHook, act } from '@testing-library/react' import { useMCPServers } from '../useMCPServers' import type { MCPServerConfig } from '../useMCPServers' -// Mock the MCP service functions -vi.mock('@/services/mcp', () => ({ - updateMCPConfig: vi.fn().mockResolvedValue(undefined), - restartMCPServers: vi.fn().mockResolvedValue(undefined), +// Mock the ServiceHub +const mockUpdateMCPConfig = vi.fn().mockResolvedValue(undefined) +const mockRestartMCPServers = vi.fn().mockResolvedValue(undefined) + +vi.mock('@/hooks/useServiceHub', () => ({ + getServiceHub: () => ({ + mcp: () => ({ + updateMCPConfig: mockUpdateMCPConfig, + restartMCPServers: mockRestartMCPServers, + }), + }), })) describe('useMCPServers', () => { @@ -338,7 +345,6 @@ describe('useMCPServers', () => { describe('syncServers', () => { it('should call updateMCPConfig with current servers', async () => { - const { updateMCPConfig } = await import('@/services/mcp') const { result } = renderHook(() => useMCPServers()) const serverConfig: MCPServerConfig = { @@ -355,7 +361,7 @@ describe('useMCPServers', () => { await result.current.syncServers() }) - expect(updateMCPConfig).toHaveBeenCalledWith( + expect(mockUpdateMCPConfig).toHaveBeenCalledWith( JSON.stringify({ mcpServers: { 'test-server': serverConfig, @@ -365,14 +371,13 @@ describe('useMCPServers', () => { }) it('should call updateMCPConfig with empty servers object', async () => { - const { updateMCPConfig } = await import('@/services/mcp') const { result } = renderHook(() => useMCPServers()) await act(async () => { await result.current.syncServers() }) - expect(updateMCPConfig).toHaveBeenCalledWith( + expect(mockUpdateMCPConfig).toHaveBeenCalledWith( JSON.stringify({ mcpServers: {}, }) @@ -381,8 +386,7 @@ describe('useMCPServers', () => { }) describe('syncServersAndRestart', () => { - it('should call updateMCPConfig and then restartMCPServers', async () => { - const { updateMCPConfig, restartMCPServers } = await import('@/services/mcp') + it('should call updateMCPConfig and then mockRestartMCPServers', async () => { const { result } = renderHook(() => useMCPServers()) const serverConfig: MCPServerConfig = { @@ -399,14 +403,14 @@ describe('useMCPServers', () => { await result.current.syncServersAndRestart() }) - expect(updateMCPConfig).toHaveBeenCalledWith( + expect(mockUpdateMCPConfig).toHaveBeenCalledWith( JSON.stringify({ mcpServers: { 'python-server': serverConfig, }, }) ) - expect(restartMCPServers).toHaveBeenCalled() + expect(mockRestartMCPServers).toHaveBeenCalled() }) }) diff --git a/web-app/src/hooks/__tests__/useMessages.test.ts b/web-app/src/hooks/__tests__/useMessages.test.ts index 25e230694..89c0c4e85 100644 --- a/web-app/src/hooks/__tests__/useMessages.test.ts +++ b/web-app/src/hooks/__tests__/useMessages.test.ts @@ -3,10 +3,17 @@ import { renderHook, act } from '@testing-library/react' import { useMessages } from '../useMessages' import { ThreadMessage } from '@janhq/core' -// Mock dependencies -vi.mock('@/services/messages', () => ({ - createMessage: vi.fn(), - deleteMessage: vi.fn(), +// Mock the ServiceHub +const mockCreateMessage = vi.fn() +const mockDeleteMessage = vi.fn() + +vi.mock('@/hooks/useServiceHub', () => ({ + getServiceHub: () => ({ + messages: () => ({ + createMessage: mockCreateMessage, + deleteMessage: mockDeleteMessage, + }), + }), })) vi.mock('./useAssistant', () => ({ @@ -19,15 +26,18 @@ vi.mock('./useAssistant', () => ({ instructions: 'Test instructions', parameters: 'test parameters', }, + assistants: [{ + id: 'test-assistant', + name: 'Test Assistant', + avatar: 'test-avatar.png', + instructions: 'Test instructions', + parameters: 'test parameters', + }], })), }, })) -import { createMessage, deleteMessage } from '@/services/messages' - describe('useMessages', () => { - const mockCreateMessage = createMessage as any - const mockDeleteMessage = deleteMessage as any beforeEach(() => { vi.clearAllMocks() diff --git a/web-app/src/hooks/__tests__/useModelSources.test.ts b/web-app/src/hooks/__tests__/useModelSources.test.ts index 41e5985a8..1006f4719 100644 --- a/web-app/src/hooks/__tests__/useModelSources.test.ts +++ b/web-app/src/hooks/__tests__/useModelSources.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest' import { renderHook, act } from '@testing-library/react' import { useModelSources } from '../useModelSources' -import type { CatalogModel } from '@/services/models' +import type { CatalogModel } from '@/services/models/types' // Mock constants vi.mock('@/constants/localStorage', () => ({ @@ -20,9 +20,15 @@ vi.mock('zustand/middleware', () => ({ }), })) -// Mock the fetchModelCatalog service -vi.mock('@/services/models', () => ({ - fetchModelCatalog: vi.fn(), +// Mock the ServiceHub +const mockFetchModelCatalog = vi.fn() + +vi.mock('@/hooks/useServiceHub', () => ({ + getServiceHub: () => ({ + models: () => ({ + fetchModelCatalog: mockFetchModelCatalog, + }), + }), })) // Mock the sanitizeModelId function @@ -31,13 +37,8 @@ vi.mock('@/lib/utils', () => ({ })) describe('useModelSources', () => { - let mockFetchModelCatalog: any - - beforeEach(async () => { + beforeEach(() => { vi.clearAllMocks() - // Get the mocked function - const { fetchModelCatalog } = await import('@/services/models') - mockFetchModelCatalog = fetchModelCatalog as any // Reset store state to defaults useModelSources.setState({ diff --git a/web-app/src/hooks/__tests__/useTools.test.ts b/web-app/src/hooks/__tests__/useTools.test.ts index c395847f1..4071f10b9 100644 --- a/web-app/src/hooks/__tests__/useTools.test.ts +++ b/web-app/src/hooks/__tests__/useTools.test.ts @@ -8,19 +8,23 @@ const mockUpdateTools = vi.fn() const mockListen = vi.fn() const mockUnsubscribe = vi.fn() -// Mock the dependencies -vi.mock('@/services/mcp', () => ({ - getTools: mockGetTools, -})) - +// Mock useAppState vi.mock('../useAppState', () => ({ useAppState: () => ({ updateTools: mockUpdateTools, }), })) -vi.mock('@tauri-apps/api/event', () => ({ - listen: mockListen, +// Mock the ServiceHub +vi.mock('@/hooks/useServiceHub', () => ({ + getServiceHub: () => ({ + mcp: () => ({ + getTools: mockGetTools, + }), + events: () => ({ + listen: mockListen, + }), + }), })) describe('useTools', () => { diff --git a/web-app/src/hooks/useAppUpdater.ts b/web-app/src/hooks/useAppUpdater.ts index 303cb43e3..3e6a4b9b9 100644 --- a/web-app/src/hooks/useAppUpdater.ts +++ b/web-app/src/hooks/useAppUpdater.ts @@ -1,14 +1,13 @@ import { isDev } from '@/lib/utils' -import { check, Update } from '@tauri-apps/plugin-updater' import { useState, useCallback, useEffect } from 'react' import { events, AppEvent } from '@janhq/core' -import { emit } from '@tauri-apps/api/event' +import type { UpdateInfo } from '@/services/updater/types' import { SystemEvent } from '@/types/events' -import { stopAllModels } from '@/services/models' +import { getServiceHub } from '@/hooks/useServiceHub' export interface UpdateState { isUpdateAvailable: boolean - updateInfo: Update | null + updateInfo: UpdateInfo | null isDownloading: boolean downloadProgress: number downloadedBytes: number @@ -74,7 +73,7 @@ export const useAppUpdater = () => { if (!isDev()) { // Production mode - use actual Tauri updater - const update = await check() + const update = await getServiceHub().updater().check() if (update) { const newState = { @@ -168,14 +167,14 @@ export const useAppUpdater = () => { let downloaded = 0 let contentLength = 0 - await stopAllModels() - emit(SystemEvent.KILL_SIDECAR) + await getServiceHub().models().stopAllModels() + getServiceHub().events().emit(SystemEvent.KILL_SIDECAR) await new Promise((resolve) => setTimeout(resolve, 1000)) - await updateState.updateInfo.downloadAndInstall((event) => { + await getServiceHub().updater().downloadAndInstallWithProgress((event) => { switch (event.event) { case 'Started': - contentLength = event.data.contentLength || 0 + contentLength = event.data?.contentLength || 0 setUpdateState((prev) => ({ ...prev, totalBytes: contentLength, @@ -190,7 +189,7 @@ export const useAppUpdater = () => { }) break case 'Progress': { - downloaded += event.data.chunkLength + downloaded += event.data?.chunkLength || 0 const progress = contentLength > 0 ? downloaded / contentLength : 0 setUpdateState((prev) => ({ ...prev, diff --git a/web-app/src/hooks/useAssistant.ts b/web-app/src/hooks/useAssistant.ts index d878607e1..eab1fffc9 100644 --- a/web-app/src/hooks/useAssistant.ts +++ b/web-app/src/hooks/useAssistant.ts @@ -1,4 +1,4 @@ -import { createAssistant, deleteAssistant } from '@/services/assistants' +import { getServiceHub } from '@/hooks/useServiceHub' import { Assistant as CoreAssistant } from '@janhq/core' import { create } from 'zustand' import { localStorageKey } from '@/constants/localStorage' @@ -51,7 +51,7 @@ export const useAssistant = create()((set, get) => ({ currentAssistant: defaultAssistant, addAssistant: (assistant) => { set({ assistants: [...get().assistants, assistant] }) - createAssistant(assistant as unknown as CoreAssistant).catch((error) => { + getServiceHub().assistants().createAssistant(assistant as unknown as CoreAssistant).catch((error) => { console.error('Failed to create assistant:', error) }) }, @@ -68,13 +68,13 @@ export const useAssistant = create()((set, get) => ({ : state.currentAssistant, }) // Create assistant already cover update logic - createAssistant(assistant as unknown as CoreAssistant).catch((error) => { + getServiceHub().assistants().createAssistant(assistant as unknown as CoreAssistant).catch((error) => { console.error('Failed to update assistant:', error) }) }, deleteAssistant: (id) => { const state = get() - deleteAssistant( + getServiceHub().assistants().deleteAssistant( state.assistants.find((e) => e.id === id) as unknown as CoreAssistant ).catch((error) => { console.error('Failed to delete assistant:', error) diff --git a/web-app/src/hooks/useChat.ts b/web-app/src/hooks/useChat.ts index 134dc1ae1..029dfe722 100644 --- a/web-app/src/hooks/useChat.ts +++ b/web-app/src/hooks/useChat.ts @@ -21,12 +21,10 @@ import { renderInstructions } from '@/lib/instructionTemplate' import { ChatCompletionMessageToolCall } from 'openai/resources' import { useAssistant } from './useAssistant' -import { stopModel, startModel, stopAllModels } from '@/services/models' - +import { useServiceHub } from '@/hooks/useServiceHub' import { useToolApproval } from '@/hooks/useToolApproval' import { useToolAvailable } from '@/hooks/useToolAvailable' import { OUT_OF_CONTEXT_SIZE } from '@/utils/error' -import { updateSettings } from '@/services/providers' import { useContextSizeApproval } from './useModelContextApproval' import { useModelLoad } from './useModelLoad' import { @@ -46,6 +44,7 @@ export const useChat = () => { } = useAppState() const { assistants, currentAssistant } = useAssistant() const { updateProvider } = useModelProvider() + const serviceHub = useServiceHub() const { approvedTools, showApprovalModal, allowAllMCPPermissions } = useToolApproval() @@ -106,14 +105,14 @@ export const useChat = () => { const restartModel = useCallback( async (provider: ProviderObject, modelId: string) => { - await stopAllModels() + await serviceHub.models().stopAllModels() await new Promise((resolve) => setTimeout(resolve, 1000)) updateLoadingModel(true) - await startModel(provider, modelId).catch(console.error) + await serviceHub.models().startModel(provider, modelId).catch(console.error) updateLoadingModel(false) await new Promise((resolve) => setTimeout(resolve, 1000)) }, - [updateLoadingModel] + [updateLoadingModel, serviceHub] ) const increaseModelContextSize = useCallback( @@ -189,7 +188,7 @@ export const useChat = () => { settings: newSettings, } - await updateSettings(providerName, updateObj.settings ?? []) + await serviceHub.providers().updateSettings(providerName, updateObj.settings ?? []) updateProvider(providerName, { ...provider, ...updateObj, @@ -198,7 +197,7 @@ export const useChat = () => { if (updatedProvider) await restartModel(updatedProvider, modelId) return updatedProvider }, - [updateProvider, getProviderByName, restartModel] + [updateProvider, getProviderByName, restartModel, serviceHub] ) const sendMessage = useCallback( @@ -232,7 +231,7 @@ export const useChat = () => { try { if (selectedModel?.id) { updateLoadingModel(true) - await startModel(activeProvider, selectedModel.id) + await serviceHub.models().startModel(activeProvider, selectedModel.id) updateLoadingModel(false) } @@ -477,7 +476,7 @@ export const useChat = () => { activeThread.model?.id && provider?.provider === 'llamacpp' ) { - await stopModel(activeThread.model.id, 'llamacpp') + await serviceHub.models().stopModel(activeThread.model.id, 'llamacpp') throw new Error('No response received from the model') } @@ -551,6 +550,7 @@ export const useChat = () => { increaseModelContextSize, toggleOnContextShifting, setModelLoadError, + serviceHub, ] ) diff --git a/web-app/src/hooks/useLlamacppDevices.ts b/web-app/src/hooks/useLlamacppDevices.ts index 245bcc60f..4ac2260b7 100644 --- a/web-app/src/hooks/useLlamacppDevices.ts +++ b/web-app/src/hooks/useLlamacppDevices.ts @@ -1,6 +1,6 @@ import { create } from 'zustand' -import { getLlamacppDevices, DeviceList } from '@/services/hardware' -import { updateSettings } from '@/services/providers' +import { getServiceHub } from '@/hooks/useServiceHub' +import type { DeviceList } from '@/services/hardware/types' import { useModelProvider } from './useModelProvider' interface LlamacppDevicesStore { @@ -24,7 +24,7 @@ export const useLlamacppDevices = create((set, get) => ({ set({ loading: true, error: null }) try { - const devices = await getLlamacppDevices() + const devices = await getServiceHub().hardware().getLlamacppDevices() // Check current device setting from provider const { getProviderByName } = useModelProvider.getState() @@ -92,7 +92,7 @@ export const useLlamacppDevices = create((set, get) => ({ return setting }) - await updateSettings('llamacpp', updatedSettings) + await getServiceHub().providers().updateSettings('llamacpp', updatedSettings) updateProvider('llamacpp', { settings: updatedSettings, }) diff --git a/web-app/src/hooks/useMCPServers.ts b/web-app/src/hooks/useMCPServers.ts index b19130ae9..d6da04baa 100644 --- a/web-app/src/hooks/useMCPServers.ts +++ b/web-app/src/hooks/useMCPServers.ts @@ -1,5 +1,5 @@ import { create } from 'zustand' -import { restartMCPServers, updateMCPConfig } from '@/services/mcp' +import { getServiceHub } from '@/hooks/useServiceHub' // Define the structure of an MCP server configuration export type MCPServerConfig = { @@ -27,6 +27,11 @@ type MCPServerStoreState = { setLeftPanel: (value: boolean) => void addServer: (key: string, config: MCPServerConfig) => void editServer: (key: string, config: MCPServerConfig) => void + renameServer: ( + oldKey: string, + newKey: string, + config: MCPServerConfig + ) => void deleteServer: (key: string) => void setServers: (servers: MCPServers) => void syncServers: () => Promise @@ -47,7 +52,10 @@ export const useMCPServers = create()((set, get) => ({ // Add a new MCP server or update if the key already exists addServer: (key, config) => set((state) => { - const mcpServers = { ...state.mcpServers, [key]: config } + // Remove the key first if it exists to maintain insertion order + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { [key]: _, ...restServers } = state.mcpServers + const mcpServers = { [key]: config, ...restServers } return { mcpServers } }), @@ -60,6 +68,27 @@ export const useMCPServers = create()((set, get) => ({ const mcpServers = { ...state.mcpServers, [key]: config } return { mcpServers } }), + + // Rename a server while preserving its position + renameServer: (oldKey, newKey, config) => + set((state) => { + // Only proceed if the server exists + if (!state.mcpServers[oldKey]) return state + + const entries = Object.entries(state.mcpServers) + const mcpServers: MCPServers = {} + + // Rebuild the object with the same order, replacing the old key with the new key + entries.forEach(([key, serverConfig]) => { + if (key === oldKey) { + mcpServers[newKey] = config + } else { + mcpServers[key] = serverConfig + } + }) + + return { mcpServers } + }), setServers: (servers) => set((state) => { const mcpServers = { ...state.mcpServers, ...servers } @@ -82,7 +111,7 @@ export const useMCPServers = create()((set, get) => ({ }), syncServers: async () => { const mcpServers = get().mcpServers - await updateMCPConfig( + await getServiceHub().mcp().updateMCPConfig( JSON.stringify({ mcpServers, }) @@ -90,10 +119,10 @@ export const useMCPServers = create()((set, get) => ({ }, syncServersAndRestart: async () => { const mcpServers = get().mcpServers - await updateMCPConfig( + await getServiceHub().mcp().updateMCPConfig( JSON.stringify({ mcpServers, }) - ).then(() => restartMCPServers()) + ).then(() => getServiceHub().mcp().restartMCPServers()) }, })) diff --git a/web-app/src/hooks/useMessages.ts b/web-app/src/hooks/useMessages.ts index bead31641..8dba73b9b 100644 --- a/web-app/src/hooks/useMessages.ts +++ b/web-app/src/hooks/useMessages.ts @@ -1,9 +1,6 @@ import { create } from 'zustand' import { ThreadMessage } from '@janhq/core' -import { - createMessage, - deleteMessage as deleteMessageExt, -} from '@/services/messages' +import { getServiceHub } from '@/hooks/useServiceHub' import { useAssistant } from './useAssistant' type MessageState = { @@ -42,7 +39,7 @@ export const useMessages = create()((set, get) => ({ assistant: selectedAssistant, }, } - createMessage(newMessage).then((createdMessage) => { + getServiceHub().messages().createMessage(newMessage).then((createdMessage) => { set((state) => ({ messages: { ...state.messages, @@ -55,7 +52,7 @@ export const useMessages = create()((set, get) => ({ }) }, deleteMessage: (threadId, messageId) => { - deleteMessageExt(threadId, messageId) + getServiceHub().messages().deleteMessage(threadId, messageId) set((state) => ({ messages: { ...state.messages, diff --git a/web-app/src/hooks/useModelProvider.ts b/web-app/src/hooks/useModelProvider.ts index 9be26ce41..86d7f4dba 100644 --- a/web-app/src/hooks/useModelProvider.ts +++ b/web-app/src/hooks/useModelProvider.ts @@ -1,7 +1,7 @@ import { create } from 'zustand' import { persist, createJSONStorage } from 'zustand/middleware' import { localStorageKey } from '@/constants/localStorage' -import { sep } from '@tauri-apps/api/path' +import { getServiceHub } from '@/hooks/useServiceHub' import { modelSettings } from '@/lib/predefined' type ModelProviderState = { @@ -93,7 +93,7 @@ export const useModelProvider = create()( ? legacyModels : models ).find( - (m) => m.id.split(':').slice(0, 2).join(sep()) === model.id + (m) => m.id.split(':').slice(0, 2).join(getServiceHub().path().sep()) === model.id )?.settings || model.settings const existingModel = models.find((m) => m.id === model.id) return { @@ -241,7 +241,7 @@ export const useModelProvider = create()( } // Migrate model settings - if (provider.models) { + if (provider.models && provider.provider === 'llamacpp') { provider.models.forEach((model) => { if (!model.settings) model.settings = {} diff --git a/web-app/src/hooks/useModelSources.ts b/web-app/src/hooks/useModelSources.ts index 3357947e1..2730e82d5 100644 --- a/web-app/src/hooks/useModelSources.ts +++ b/web-app/src/hooks/useModelSources.ts @@ -1,7 +1,8 @@ import { create } from 'zustand' import { localStorageKey } from '@/constants/localStorage' import { createJSONStorage, persist } from 'zustand/middleware' -import { fetchModelCatalog, CatalogModel } from '@/services/models' +import { getServiceHub } from '@/hooks/useServiceHub' +import type { CatalogModel } from '@/services/models/types' import { sanitizeModelId } from '@/lib/utils' // Zustand store for model sources @@ -21,7 +22,7 @@ export const useModelSources = create()( fetchSources: async () => { set({ loading: true, error: null }) try { - const newSources = await fetchModelCatalog().then((catalogs) => + const newSources = await getServiceHub().models().fetchModelCatalog().then((catalogs) => catalogs.map((catalog) => ({ ...catalog, quants: catalog.quants.map((quant) => ({ diff --git a/web-app/src/hooks/useServiceHub.ts b/web-app/src/hooks/useServiceHub.ts new file mode 100644 index 000000000..22af1886b --- /dev/null +++ b/web-app/src/hooks/useServiceHub.ts @@ -0,0 +1,55 @@ +import { create } from 'zustand' +import { ServiceHub } from '@/services' + +interface ServiceState { + serviceHub: ServiceHub | null + setServiceHub: (serviceHub: ServiceHub) => void +} + +const useServiceStore = create()((set) => ({ + serviceHub: null, + setServiceHub: (serviceHub: ServiceHub) => set({ serviceHub }), +})) + +/** + * Hook to get the ServiceHub instance for React components + * Throws an error if ServiceHub is not initialized + */ +export const useServiceHub = (): ServiceHub => { + const serviceHub = useServiceStore((state) => state.serviceHub) + + if (!serviceHub) { + throw new Error('ServiceHub not initialized. Make sure services are initialized before using this hook.') + } + + return serviceHub +} + +/** + * Global function to get ServiceHub for non-React contexts (Zustand stores, service files, etc.) + * Throws an error if ServiceHub is not initialized + */ +export const getServiceHub = (): ServiceHub => { + const serviceHub = useServiceStore.getState().serviceHub + + if (!serviceHub) { + throw new Error('ServiceHub not initialized. Make sure services are initialized before accessing services.') + } + + return serviceHub +} + +/** + * Initialize the ServiceHub in the store + * This should only be called from the root layout after service initialization + */ +export const initializeServiceHubStore = (serviceHub: ServiceHub) => { + useServiceStore.getState().setServiceHub(serviceHub) +} + +/** + * Check if ServiceHub is initialized + */ +export const isServiceHubInitialized = (): boolean => { + return useServiceStore.getState().serviceHub !== null +} \ No newline at end of file diff --git a/web-app/src/hooks/useTheme.ts b/web-app/src/hooks/useTheme.ts index aaf855d3b..bf17cd90b 100644 --- a/web-app/src/hooks/useTheme.ts +++ b/web-app/src/hooks/useTheme.ts @@ -1,6 +1,7 @@ import { create } from 'zustand' import { createJSONStorage, persist } from 'zustand/middleware' -import { getCurrentWindow, Theme } from '@tauri-apps/api/window' +import { getServiceHub } from '@/hooks/useServiceHub' +import type { ThemeMode } from '@/services/theme/types' import { localStorageKey } from '@/constants/localStorage' // Function to check if OS prefers dark mode @@ -28,10 +29,10 @@ export const useTheme = create()( setTheme: async (activeTheme: AppTheme) => { if (activeTheme === 'auto') { const isDarkMode = checkOSDarkMode() - await getCurrentWindow().setTheme(null) + await getServiceHub().theme().setTheme(null) set(() => ({ activeTheme, isDark: isDarkMode })) } else { - await getCurrentWindow().setTheme(activeTheme as Theme) + await getServiceHub().theme().setTheme(activeTheme as ThemeMode) set(() => ({ activeTheme, isDark: activeTheme === 'dark' })) } }, diff --git a/web-app/src/hooks/useThreads.ts b/web-app/src/hooks/useThreads.ts index 83bd320c8..823f3d93c 100644 --- a/web-app/src/hooks/useThreads.ts +++ b/web-app/src/hooks/useThreads.ts @@ -1,8 +1,7 @@ import { create } from 'zustand' import { ulid } from 'ulidx' -import { createThread, deleteThread, updateThread } from '@/services/threads' +import { getServiceHub } from '@/hooks/useServiceHub' import { Fzf } from 'fzf' -import { sep } from '@tauri-apps/api/path' type ThreadState = { threads: Record @@ -47,7 +46,7 @@ export const useThreads = create()((set, get) => ({ id: thread.model.provider === 'llama.cpp' || thread.model.provider === 'llamacpp' - ? thread.model?.id.split(':').slice(0, 2).join(sep()) + ? thread.model?.id.split(':').slice(0, 2).join(getServiceHub().path().sep()) : thread.model?.id, } : undefined, @@ -95,7 +94,7 @@ export const useThreads = create()((set, get) => ({ }, toggleFavorite: (threadId) => { set((state) => { - updateThread({ + getServiceHub().threads().updateThread({ ...state.threads[threadId], isFavorite: !state.threads[threadId].isFavorite, }) @@ -115,7 +114,7 @@ export const useThreads = create()((set, get) => ({ set((state) => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { [threadId]: _, ...remainingThreads } = state.threads - deleteThread(threadId) + getServiceHub().threads().deleteThread(threadId) return { threads: remainingThreads, searchIndex: new Fzf(Object.values(remainingThreads), { @@ -136,7 +135,7 @@ export const useThreads = create()((set, get) => ({ // Only delete non-favorite threads nonFavoriteThreadIds.forEach((threadId) => { - deleteThread(threadId) + getServiceHub().threads().deleteThread(threadId) }) // Keep only favorite threads @@ -169,7 +168,7 @@ export const useThreads = create()((set, get) => ({ {} as Record ) Object.values(updatedThreads).forEach((thread) => { - updateThread({ ...thread, isFavorite: false }) + getServiceHub().threads().updateThread({ ...thread, isFavorite: false }) }) return { threads: updatedThreads } }) @@ -191,7 +190,7 @@ export const useThreads = create()((set, get) => ({ updated: Date.now() / 1000, assistants: assistant ? [assistant] : [], } - return await createThread(newThread).then((createdThread) => { + return await getServiceHub().threads().createThread(newThread).then((createdThread) => { set((state) => { // Get all existing threads as an array const existingThreads = Object.values(state.threads) @@ -214,7 +213,7 @@ export const useThreads = create()((set, get) => ({ if (!state.currentThreadId) return { ...state } const currentThread = state.getCurrentThread() if (currentThread) - updateThread({ + getServiceHub().threads().updateThread({ ...currentThread, assistants: [{ ...assistant, model: currentThread.model }], }) @@ -234,7 +233,7 @@ export const useThreads = create()((set, get) => ({ set((state) => { if (!state.currentThreadId) return { ...state } const currentThread = state.getCurrentThread() - if (currentThread) updateThread({ ...currentThread, model }) + if (currentThread) getServiceHub().threads().updateThread({ ...currentThread, model }) return { threads: { ...state.threads, @@ -255,7 +254,7 @@ export const useThreads = create()((set, get) => ({ title: newTitle, updated: Date.now() / 1000, } - updateThread(updatedThread) // External call, order is fine + getServiceHub().threads().updateThread(updatedThread) // External call, order is fine const newThreads = { ...state.threads, [threadId]: updatedThread } return { threads: newThreads, @@ -285,7 +284,7 @@ export const useThreads = create()((set, get) => ({ updatedThreads[threadId] = updatedThread // Update the backend for the main thread - updateThread(updatedThread) + getServiceHub().threads().updateThread(updatedThread) return { threads: updatedThreads, diff --git a/web-app/src/hooks/useTools.ts b/web-app/src/hooks/useTools.ts index 20cab7939..3d66e3ab7 100644 --- a/web-app/src/hooks/useTools.ts +++ b/web-app/src/hooks/useTools.ts @@ -1,7 +1,6 @@ import { useEffect } from 'react' -import { getTools } from '@/services/mcp' +import { getServiceHub } from '@/hooks/useServiceHub' import { MCPTool } from '@/types/completion' -import { listen } from '@tauri-apps/api/event' import { SystemEvent } from '@/types/events' import { useAppState } from './useAppState' @@ -10,7 +9,7 @@ export const useTools = () => { useEffect(() => { function setTools() { - getTools().then((data: MCPTool[]) => { + getServiceHub().mcp().getTools().then((data: MCPTool[]) => { updateTools(data) }).catch((error) => { console.error('Failed to fetch MCP tools:', error) @@ -19,7 +18,7 @@ export const useTools = () => { setTools() let unsubscribe = () => {} - listen(SystemEvent.MCP_UPDATE, setTools).then((unsub) => { + getServiceHub().events().listen(SystemEvent.MCP_UPDATE, setTools).then((unsub) => { // Unsubscribe from the event when the component unmounts unsubscribe = unsub }).catch((error) => { diff --git a/web-app/src/lib/completion.ts b/web-app/src/lib/completion.ts index 6f5f6cdab..9c81a4034 100644 --- a/web-app/src/lib/completion.ts +++ b/web-app/src/lib/completion.ts @@ -11,8 +11,7 @@ import { chatCompletionChunk, Tool, } from '@janhq/core' -import { invoke } from '@tauri-apps/api/core' -import { fetch as fetchTauri } from '@tauri-apps/plugin-http' +import { getServiceHub } from '@/hooks/useServiceHub' import { ChatCompletionMessageParam, ChatCompletionTool, @@ -32,7 +31,6 @@ import { ulid } from 'ulidx' import { MCPTool } from '@/types/completion' import { CompletionMessagesBuilder } from './messages' import { ChatCompletionMessageToolCall } from 'openai/resources' -import { callToolWithCancellation } from '@/services/mcp' import { ExtensionManager } from './extension' import { useAppState } from '@/hooks/useAppState' @@ -171,11 +169,11 @@ export const sendCompletion = async ( providerName = 'openai-compatible' const tokenJS = new TokenJS({ - apiKey: provider.api_key ?? (await invoke('app_token')), + apiKey: provider.api_key ?? (await getServiceHub().core().getAppToken()) ?? '', // TODO: Retrieve from extension settings baseURL: provider.base_url, // Use Tauri's fetch to avoid CORS issues only for openai-compatible provider - ...(providerName === 'openai-compatible' && { fetch: fetchTauri }), + ...(providerName === 'openai-compatible' && { fetch: getServiceHub().providers().fetch() }), // OpenRouter identification headers for Jan // ref: https://openrouter.ai/docs/api-reference/overview#headers ...(provider.provider === 'openrouter' && { @@ -407,7 +405,7 @@ export const postMessageProcessing = async ( ) : true) - const { promise, cancel } = callToolWithCancellation({ + const { promise, cancel } = getServiceHub().mcp().callToolWithCancellation({ toolName: toolCall.function.name, arguments: toolCall.function.arguments.length ? JSON.parse(toolCall.function.arguments) diff --git a/web-app/src/lib/extension.ts b/web-app/src/lib/extension.ts index d7d67ba3a..1f8944553 100644 --- a/web-app/src/lib/extension.ts +++ b/web-app/src/lib/extension.ts @@ -1,6 +1,6 @@ import { AIEngine, BaseExtension, ExtensionTypeEnum } from '@janhq/core' -import { convertFileSrc, invoke } from '@tauri-apps/api/core' +import { getServiceHub } from '@/hooks/useServiceHub' /** * Extension manifest object. @@ -24,13 +24,17 @@ export class Extension { /** @type {string} Extension's version. */ version?: string + /** @type {BaseExtension} Pre-loaded extension instance for web extensions. */ + extensionInstance?: BaseExtension + constructor( url: string, name: string, productName?: string, active?: boolean, description?: string, - version?: string + version?: string, + extensionInstance?: BaseExtension ) { this.name = name this.productName = productName @@ -38,6 +42,7 @@ export class Extension { this.active = active this.description = description this.version = version + this.extensionInstance = extensionInstance } } @@ -48,6 +53,7 @@ export type ExtensionManifest = { active?: boolean description?: string version?: string + extensionInstance?: BaseExtension // For web extensions } /** @@ -143,19 +149,21 @@ export class ExtensionManager { * @returns An array of extensions. */ async getActive(): Promise { - const res = await invoke('get_active_extensions') - if (!res || !Array.isArray(res)) return [] + const manifests = await getServiceHub().core().getActiveExtensions() + if (!manifests || !Array.isArray(manifests)) return [] - const extensions: Extension[] = res.map((ext: ExtensionManifest) => { + const extensions: Extension[] = manifests.map((manifest: ExtensionManifest) => { return new Extension( - ext.url, - ext.name, - ext.productName, - ext.active, - ext.description, - ext.version + manifest.url, + manifest.name, + manifest.productName, + manifest.active, + manifest.description, + manifest.version, + manifest.extensionInstance // Pass the extension instance if available ) }) + return extensions } @@ -165,9 +173,16 @@ export class ExtensionManager { * @returns {void} */ async activateExtension(extension: Extension) { - // Import class + // Check if extension already has a pre-loaded instance (web extensions) + if (extension.extensionInstance) { + this.register(extension.name, extension.extensionInstance) + console.log(`Extension '${extension.name}' registered with pre-loaded instance`) + return + } + + // Import class for Tauri extensions const extensionUrl = extension.url - await import(/* @vite-ignore */ convertFileSrc(extensionUrl)).then( + await import(/* @vite-ignore */ getServiceHub().core().convertFileSrc(extensionUrl)).then( (extensionClass) => { // Register class if it has a default export if ( @@ -212,9 +227,7 @@ export class ExtensionManager { if (typeof window === 'undefined') { return } - const res = (await invoke('install_extension', { - extensions, - })) as ExtensionManifest[] + const res = await getServiceHub().core().installExtension(extensions) return res.map(async (ext: ExtensionManifest) => { const extension = new Extension(ext.name, ext.url) await this.activateExtension(extension) @@ -228,11 +241,11 @@ export class ExtensionManager { * @param {boolean} reload Whether to reload all renderers after updating the extensions. * @returns {Promise.} Whether uninstalling the extensions was successful. */ - uninstall(extensions: string[], reload = true) { + async uninstall(extensions: string[], reload = true) { if (typeof window === 'undefined') { return } - return invoke('uninstall_extension', { extensions, reload }) + return await getServiceHub().core().uninstallExtension(extensions, reload) } /** diff --git a/web-app/src/lib/platform/PlatformGuard.tsx b/web-app/src/lib/platform/PlatformGuard.tsx new file mode 100644 index 000000000..78d7cebd0 --- /dev/null +++ b/web-app/src/lib/platform/PlatformGuard.tsx @@ -0,0 +1,43 @@ +import { ReactNode } from 'react' +import { PlatformFeature } from './types' +import { getUnavailableFeatureMessage } from './utils' +import { PlatformFeatures } from './const' + +interface PlatformGuardProps { + feature: PlatformFeature + children: ReactNode + fallback?: ReactNode + showMessage?: boolean +} + +export const PlatformGuard = ({ + feature, + children, + fallback, + showMessage = true, +}: PlatformGuardProps) => { + const isAvailable = PlatformFeatures[feature] || false + + if (isAvailable) { + return <>{children} + } + + if (fallback) { + return <>{fallback} + } + + if (showMessage) { + return ( +
+
+

Feature Not Available

+

+ {getUnavailableFeatureMessage(feature)} +

+
+
+ ) + } + + return null +} diff --git a/web-app/src/lib/platform/const.ts b/web-app/src/lib/platform/const.ts new file mode 100644 index 000000000..e2aabb109 --- /dev/null +++ b/web-app/src/lib/platform/const.ts @@ -0,0 +1,49 @@ +/** + * Platform Feature Configuration + * Centralized feature flags for different platforms + */ + +import { PlatformFeature } from './types' +import { isPlatformTauri } from './utils' + +/** + * Platform Features Configuration + * Centralized feature flags for different platforms + */ +export const PlatformFeatures: Record = { + // Hardware monitoring and GPU usage + [PlatformFeature.HARDWARE_MONITORING]: isPlatformTauri(), + + // Extension installation/management + [PlatformFeature.EXTENSION_MANAGEMENT]: true, + + // Local model inference (llama.cpp) + [PlatformFeature.LOCAL_INFERENCE]: isPlatformTauri(), + + // MCP (Model Context Protocol) servers + [PlatformFeature.MCP_SERVERS]: isPlatformTauri(), + + // Local API server + [PlatformFeature.LOCAL_API_SERVER]: isPlatformTauri(), + + // Hub/model downloads + [PlatformFeature.MODEL_HUB]: isPlatformTauri(), + + // System integrations (logs, file explorer, etc.) + [PlatformFeature.SYSTEM_INTEGRATIONS]: isPlatformTauri(), + + // HTTPS proxy + [PlatformFeature.HTTPS_PROXY]: isPlatformTauri(), + + // Default model providers (OpenAI, Anthropic, etc.) - disabled for web-only Jan builds + [PlatformFeature.DEFAULT_PROVIDERS]: isPlatformTauri(), + + // Analytics and telemetry - disabled for web + [PlatformFeature.ANALYTICS]: isPlatformTauri(), + + // Web-specific automatic model selection from jan provider - enabled for web only + [PlatformFeature.WEB_AUTO_MODEL_SELECTION]: !isPlatformTauri(), + + // Model provider settings page management - disabled for web only + [PlatformFeature.MODEL_PROVIDER_SETTINGS]: isPlatformTauri(), +} \ No newline at end of file diff --git a/web-app/src/lib/platform/index.ts b/web-app/src/lib/platform/index.ts new file mode 100644 index 000000000..08d34d4cc --- /dev/null +++ b/web-app/src/lib/platform/index.ts @@ -0,0 +1,13 @@ +/** + * Platform Detection and Utilities + * Main entry point for platform-aware functionality + */ + +// Re-export all types +export * from './types' + +// Re-export all utilities +export * from './utils' + +// Re-export components +export * from './PlatformGuard' \ No newline at end of file diff --git a/web-app/src/lib/platform/types.ts b/web-app/src/lib/platform/types.ts new file mode 100644 index 000000000..5aa0fe7f4 --- /dev/null +++ b/web-app/src/lib/platform/types.ts @@ -0,0 +1,51 @@ +/** + * Platform Types and Features + * Defines all platform-specific types and feature enums + */ + +/** + * Supported platforms + */ +export type Platform = 'tauri' | 'web' + +/** + * Platform Feature Enum + * Defines all available features that can be platform-specific + */ +export enum PlatformFeature { + // Hardware monitoring and GPU usage + HARDWARE_MONITORING = 'hardwareMonitoring', + + // Extension installation/management + EXTENSION_MANAGEMENT = 'extensionManagement', + + // Local model inference (llama.cpp) + LOCAL_INFERENCE = 'localInference', + + // MCP (Model Context Protocol) servers + MCP_SERVERS = 'mcpServers', + + // Local API server + LOCAL_API_SERVER = 'localApiServer', + + // Hub/model downloads + MODEL_HUB = 'modelHub', + + // System integrations (logs, file explorer, etc.) + SYSTEM_INTEGRATIONS = 'systemIntegrations', + + // HTTPS proxy + HTTPS_PROXY = 'httpsProxy', + + // Default model providers (OpenAI, Anthropic, etc.) + DEFAULT_PROVIDERS = 'defaultProviders', + + // Analytics and telemetry + ANALYTICS = 'analytics', + + // Web-specific automatic model selection from jan provider + WEB_AUTO_MODEL_SELECTION = 'webAutoModelSelection', + + // Model provider settings page management + MODEL_PROVIDER_SETTINGS = 'modelProviderSettings', +} diff --git a/web-app/src/lib/platform/utils.ts b/web-app/src/lib/platform/utils.ts new file mode 100644 index 000000000..9ef9183d9 --- /dev/null +++ b/web-app/src/lib/platform/utils.ts @@ -0,0 +1,28 @@ +import { Platform, PlatformFeature } from './types' + +declare const IS_WEB_APP: boolean + +export const isPlatformTauri = (): boolean => { + if (typeof IS_WEB_APP === 'undefined') { + return true + } + if (IS_WEB_APP === true || (IS_WEB_APP as unknown as string) === 'true') { + return false + } + return true +} + +export const getCurrentPlatform = (): Platform => { + return isPlatformTauri() ? 'tauri' : 'web' +} + +export const getUnavailableFeatureMessage = ( + feature: PlatformFeature +): string => { + const platform = getCurrentPlatform() + const featureName = feature + .replace(/([A-Z])/g, ' $1') + .toLowerCase() + .replace(/^./, (str) => str.toUpperCase()) + return `${featureName} is not available on ${platform} platform` +} diff --git a/web-app/src/lib/service.ts b/web-app/src/lib/service.ts index 809090b9d..a35d99636 100644 --- a/web-app/src/lib/service.ts +++ b/web-app/src/lib/service.ts @@ -1,5 +1,7 @@ import { CoreRoutes, APIRoutes } from '@janhq/core' -import { invoke, InvokeArgs } from '@tauri-apps/api/core' +import { getServiceHub } from '@/hooks/useServiceHub' +import { isPlatformTauri } from '@/lib/platform' +import type { InvokeArgs } from '@/services/core/types' export const AppRoutes = [ 'installExtensions', @@ -40,11 +42,17 @@ export const APIs = { return { ...acc, [proxy.route]: (args?: InvokeArgs) => { - // For each route, define a function that sends a request to the API - return invoke( - proxy.route.replace(/([A-Z])/g, '_$1').toLowerCase(), - args - ) + if (isPlatformTauri()) { + // For Tauri platform, use the service hub to invoke commands + return getServiceHub().core().invoke( + proxy.route.replace(/([A-Z])/g, '_$1').toLowerCase(), + args + ) + } else { + // For Web platform, provide fallback implementations + console.warn(`API call '${proxy.route}' not supported in web environment`, args) + return Promise.resolve(null) + } }, } }, {}), diff --git a/web-app/src/lib/utils.ts b/web-app/src/lib/utils.ts index 3d896b883..0d3fa8f61 100644 --- a/web-app/src/lib/utils.ts +++ b/web-app/src/lib/utils.ts @@ -8,6 +8,8 @@ export function cn(...inputs: ClassValue[]) { export function getProviderLogo(provider: string) { switch (provider) { + case 'jan': + return '/images/model-provider/jan.png' case 'llamacpp': return '/images/model-provider/llamacpp.svg' case 'anthropic': @@ -33,6 +35,8 @@ export function getProviderLogo(provider: string) { export const getProviderTitle = (provider: string) => { switch (provider) { + case 'jan': + return 'Jan' case 'llamacpp': return 'Llama.cpp' case 'openai': diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.json index 17e59d3bb..cf3d8ec17 100644 --- a/web-app/src/locales/en/settings.json +++ b/web-app/src/locales/en/settings.json @@ -37,7 +37,7 @@ "reportAnIssueDesc": "Found a bug? Help us out by filing an issue on GitHub.", "reportIssue": "Report Issue", "credits": "Credits", - "creditsDesc1": "Jan is built with ❤️ by the Menlo Team.", + "creditsDesc1": "👋 Jan is built with ❤️ by the Menlo Research team.", "creditsDesc2": "Special thanks to our open-source dependencies—especially llama.cpp and Tauri—and to our amazing AI community.", "appVersion": "App Version", "dataFolder": { @@ -234,7 +234,7 @@ "reportAnIssueDesc": "Found a bug? Help us out by filing an issue on GitHub.", "reportIssue": "Report Issue", "credits": "Credits", - "creditsDesc1": "Jan is built with ❤️ by the Menlo Team.", + "creditsDesc1": "👋 Jan is built with ❤️ by the Menlo Research team.", "creditsDesc2": "Special thanks to our open-source dependencies—especially llama.cpp and Tauri—and to our amazing AI community." }, "extensions": { diff --git a/web-app/src/providers/AnalyticProvider.tsx b/web-app/src/providers/AnalyticProvider.tsx index 5bacfb48f..f26e3f97e 100644 --- a/web-app/src/providers/AnalyticProvider.tsx +++ b/web-app/src/providers/AnalyticProvider.tsx @@ -1,13 +1,20 @@ import posthog from 'posthog-js' import { useEffect } from 'react' -import { getAppDistinctId, updateDistinctId } from '@/services/analytic' +import { useServiceHub } from '@/hooks/useServiceHub' import { useAnalytic } from '@/hooks/useAnalytic' +import { PlatformFeatures } from '@/lib/platform/const' +import { PlatformFeature } from '@/lib/platform/types' export function AnalyticProvider() { const { productAnalytic } = useAnalytic() + const serviceHub = useServiceHub() useEffect(() => { + // Early exit if analytics are disabled for this platform + if (!PlatformFeatures[PlatformFeature.ANALYTICS]) { + return + } if (!POSTHOG_KEY || !POSTHOG_HOST) { console.warn( 'PostHog not initialized: Missing POSTHOG_KEY or POSTHOG_HOST environment variables' @@ -46,19 +53,19 @@ export function AnalyticProvider() { }, }) // Attempt to restore distinct Id from app global settings - getAppDistinctId() + serviceHub.analytic().getAppDistinctId() .then((id) => { if (id) posthog.identify(id) }) .finally(() => { posthog.opt_in_capturing() posthog.register({ app_version: VERSION }) - updateDistinctId(posthog.get_distinct_id()) + serviceHub.analytic().updateDistinctId(posthog.get_distinct_id()) }) } else { posthog.opt_out_capturing() } - }, [productAnalytic]) + }, [productAnalytic, serviceHub]) // This component doesn't render anything return null diff --git a/web-app/src/providers/DataProvider.tsx b/web-app/src/providers/DataProvider.tsx index baca6e213..352026175 100644 --- a/web-app/src/providers/DataProvider.tsx +++ b/web-app/src/providers/DataProvider.tsx @@ -2,25 +2,16 @@ import { useMessages } from '@/hooks/useMessages' import { useModelProvider } from '@/hooks/useModelProvider' import { useAppUpdater } from '@/hooks/useAppUpdater' -import { fetchMessages } from '@/services/messages' -import { getProviders } from '@/services/providers' -import { fetchThreads } from '@/services/threads' +import { useServiceHub } from '@/hooks/useServiceHub' import { useEffect } from 'react' import { useMCPServers } from '@/hooks/useMCPServers' -import { getMCPConfig } from '@/services/mcp' import { useAssistant } from '@/hooks/useAssistant' -import { getAssistants } from '@/services/assistants' -import { - onOpenUrl, - getCurrent as getCurrentDeepLinkUrls, -} from '@tauri-apps/plugin-deep-link' import { useNavigate } from '@tanstack/react-router' import { route } from '@/constants/routes' import { useThreads } from '@/hooks/useThreads' import { useLocalApiServer } from '@/hooks/useLocalApiServer' import { useAppState } from '@/hooks/useAppState' import { AppEvent, events } from '@janhq/core' -import { startModel } from '@/services/models' import { localStorageKey } from '@/constants/localStorage' export function DataProvider() { @@ -33,6 +24,7 @@ export function DataProvider() { const { setAssistants, initializeWithLastUsed } = useAssistant() const { setThreads } = useThreads() const navigate = useNavigate() + const serviceHub = useServiceHub() // Local API Server hooks const { @@ -49,9 +41,9 @@ export function DataProvider() { useEffect(() => { console.log('Initializing DataProvider...') - getProviders().then(setProviders) - getMCPConfig().then((data) => setServers(data.mcpServers ?? [])) - getAssistants() + serviceHub.providers().getProviders().then(setProviders) + serviceHub.mcp().getMCPConfig().then((data) => setServers(data.mcpServers ?? {})) + serviceHub.assistants().getAssistants() .then((data) => { // Only update assistants if we have valid data if (data && Array.isArray(data) && data.length > 0) { @@ -62,22 +54,21 @@ export function DataProvider() { .catch((error) => { console.warn('Failed to load assistants, keeping default:', error) }) - getCurrentDeepLinkUrls().then(handleDeepLink) - onOpenUrl(handleDeepLink) + serviceHub.deeplink().getCurrent().then(handleDeepLink) + serviceHub.deeplink().onOpenUrl(handleDeepLink) // eslint-disable-next-line react-hooks/exhaustive-deps - }, []) + }, [serviceHub]) useEffect(() => { - fetchThreads().then((threads) => { + serviceHub.threads().fetchThreads().then((threads) => { setThreads(threads) threads.forEach((thread) => - fetchMessages(thread.id).then((messages) => + serviceHub.messages().fetchMessages(thread.id).then((messages) => setMessages(thread.id, messages) ) ) }) - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []) + }, [serviceHub, setThreads, setMessages]) // Check for app updates useEffect(() => { @@ -91,10 +82,9 @@ export function DataProvider() { useEffect(() => { events.on(AppEvent.onModelImported, () => { - getProviders().then(setProviders) + serviceHub.providers().getProviders().then(setProviders) }) - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []) + }, [serviceHub, setProviders]) const getLastUsedModel = (): { provider: string; model: string } | null => { try { @@ -166,7 +156,7 @@ export function DataProvider() { setServerStatus('pending') // Start the model first - startModel(modelToStart.provider, modelToStart.model) + serviceHub.models().startModel(modelToStart.provider, modelToStart.model) .then(() => { console.log(`Model ${modelToStart.model} started successfully`) @@ -190,7 +180,7 @@ export function DataProvider() { }) } // eslint-disable-next-line react-hooks/exhaustive-deps - }, []) + }, [serviceHub]) const handleDeepLink = (urls: string[] | null) => { if (!urls) return diff --git a/web-app/src/providers/ExtensionProvider.tsx b/web-app/src/providers/ExtensionProvider.tsx index bffce9e66..fe5b91472 100644 --- a/web-app/src/providers/ExtensionProvider.tsx +++ b/web-app/src/providers/ExtensionProvider.tsx @@ -1,12 +1,13 @@ import { ExtensionManager } from '@/lib/extension' import { APIs } from '@/lib/service' -import { EventEmitter } from '@/services/events' +import { EventEmitter } from '@/services/events/EventEmitter' import { EngineManager, ModelManager } from '@janhq/core' import { PropsWithChildren, useCallback, useEffect, useState } from 'react' export function ExtensionProvider({ children }: PropsWithChildren) { const [finishedSetup, setFinishedSetup] = useState(false) const setupExtensions = useCallback(async () => { + // Setup core window object for both platforms window.core = { api: APIs, } @@ -16,7 +17,7 @@ export function ExtensionProvider({ children }: PropsWithChildren) { window.core.engineManager = new EngineManager() window.core.modelManager = new ModelManager() - // Register all active extensions + // Register extensions - same pattern for both platforms await ExtensionManager.getInstance() .registerActive() .then(() => ExtensionManager.getInstance().load()) diff --git a/web-app/src/providers/GlobalEventHandler.tsx b/web-app/src/providers/GlobalEventHandler.tsx index 62bb67185..8295ba9a5 100644 --- a/web-app/src/providers/GlobalEventHandler.tsx +++ b/web-app/src/providers/GlobalEventHandler.tsx @@ -1,7 +1,7 @@ import { useEffect } from 'react' import { events } from '@janhq/core' import { useModelProvider } from '@/hooks/useModelProvider' -import { getProviders } from '@/services/providers' +import { useServiceHub } from '@/hooks/useServiceHub' /** * GlobalEventHandler handles global events that should be processed across all screens @@ -9,6 +9,7 @@ import { getProviders } from '@/services/providers' */ export function GlobalEventHandler() { const { setProviders } = useModelProvider() + const serviceHub = useServiceHub() // Handle settingsChanged event globally useEffect(() => { @@ -22,7 +23,7 @@ export function GlobalEventHandler() { if (event.key === 'version_backend') { try { // Refresh providers to get updated settings from the extension - const updatedProviders = await getProviders() + const updatedProviders = await serviceHub.providers().getProviders() setProviders(updatedProviders) console.log('Providers refreshed after version_backend change') } catch (error) { @@ -47,7 +48,7 @@ export function GlobalEventHandler() { return () => { events.off('settingsChanged', handleSettingsChanged) } - }, [setProviders]) + }, [setProviders, serviceHub]) // This component doesn't render anything return null diff --git a/web-app/src/providers/ServiceHubProvider.tsx b/web-app/src/providers/ServiceHubProvider.tsx new file mode 100644 index 000000000..68aa43c19 --- /dev/null +++ b/web-app/src/providers/ServiceHubProvider.tsx @@ -0,0 +1,26 @@ +import { useEffect, useState } from 'react' +import { initializeServiceHub } from '@/services' +import { initializeServiceHubStore } from '@/hooks/useServiceHub' + +interface ServiceHubProviderProps { + children: React.ReactNode +} + +export function ServiceHubProvider({ children }: ServiceHubProviderProps) { + const [isReady, setIsReady] = useState(false) + + useEffect(() => { + initializeServiceHub() + .then((hub) => { + console.log('Services initialized, initializing Zustand store') + initializeServiceHubStore(hub) + setIsReady(true) + }) + .catch((error) => { + console.error('Service initialization failed:', error) + setIsReady(true) // Still render to show error state + }) + }, []) + + return <>{isReady && children} +} \ No newline at end of file diff --git a/web-app/src/providers/__tests__/DataProvider.test.tsx b/web-app/src/providers/__tests__/DataProvider.test.tsx index 565899a46..9757c2b29 100644 --- a/web-app/src/providers/__tests__/DataProvider.test.tsx +++ b/web-app/src/providers/__tests__/DataProvider.test.tsx @@ -9,26 +9,7 @@ vi.mock('@tauri-apps/plugin-deep-link', () => ({ getCurrent: vi.fn().mockResolvedValue([]), })) -// Mock services -vi.mock('@/services/threads', () => ({ - fetchThreads: vi.fn().mockResolvedValue([]), -})) - -vi.mock('@/services/messages', () => ({ - fetchMessages: vi.fn().mockResolvedValue([]), -})) - -vi.mock('@/services/providers', () => ({ - getProviders: vi.fn().mockResolvedValue([]), -})) - -vi.mock('@/services/assistants', () => ({ - getAssistants: vi.fn().mockResolvedValue([]), -})) - -vi.mock('@/services/mcp', () => ({ - getMCPConfig: vi.fn().mockResolvedValue({ mcpServers: [] }), -})) +// The services are handled by the global ServiceHub mock in test setup // Mock hooks vi.mock('@/hooks/useThreads', () => ({ @@ -98,16 +79,11 @@ describe('DataProvider', () => { }) it('initializes data on mount', async () => { - const mockFetchThreads = vi.mocked(await vi.importMock('@/services/threads')).fetchThreads - const mockGetAssistants = vi.mocked(await vi.importMock('@/services/assistants')).getAssistants - const mockGetProviders = vi.mocked(await vi.importMock('@/services/providers')).getProviders - + // DataProvider initializes and renders children without errors renderWithRouter(
Test Child
) await waitFor(() => { - expect(mockFetchThreads).toHaveBeenCalled() - expect(mockGetAssistants).toHaveBeenCalled() - expect(mockGetProviders).toHaveBeenCalled() + expect(screen.getByText('Test Child')).toBeInTheDocument() }) }) diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsx index a8dc9fb03..13ed27813 100644 --- a/web-app/src/routes/__root.tsx +++ b/web-app/src/routes/__root.tsx @@ -30,6 +30,9 @@ import { useCallback, useEffect } from 'react' import GlobalError from '@/containers/GlobalError' import { GlobalEventHandler } from '@/providers/GlobalEventHandler' import ErrorDialog from '@/containers/dialogs/ErrorDialog' +import { ServiceHubProvider } from '@/providers/ServiceHubProvider' +import { PlatformFeatures } from '@/lib/platform/const' +import { PlatformFeature } from '@/lib/platform/types' export const Route = createRootRoute({ component: RootLayout, @@ -76,13 +79,14 @@ const AppLayout = () => { const handleGlobalDrop = (e: DragEvent) => { e.preventDefault() e.stopPropagation() - + // Only prevent if the target is not within a chat input or other valid drop zone const target = e.target as Element - const isValidDropZone = target?.closest('[data-drop-zone="true"]') || - target?.closest('.chat-input-drop-zone') || - target?.closest('[data-tauri-drag-region]') - + const isValidDropZone = + target?.closest('[data-drop-zone="true"]') || + target?.closest('.chat-input-drop-zone') || + target?.closest('[data-tauri-drag-region]') + if (!isValidDropZone) { // Prevent the file from opening in the window return false @@ -96,7 +100,7 @@ const AppLayout = () => { return () => { window.removeEventListener('dragenter', preventDefaults) - window.removeEventListener('dragover', preventDefaults) + window.removeEventListener('dragover', preventDefaults) window.removeEventListener('drop', handleGlobalDrop) } }, []) @@ -160,7 +164,7 @@ const AppLayout = () => {
)} - {productAnalyticPrompt && } + {PlatformFeatures[PlatformFeature.ANALYTICS] && productAnalyticPrompt && } ) } @@ -192,21 +196,24 @@ function RootLayout() { return ( - - - - - - - - - {isLocalAPIServerLogsRoute ? : } - {/* */} - - - - - + + + + + + + + + {isLocalAPIServerLogsRoute ? : } + + {/* {isLocalAPIServerLogsRoute ? : } */} + {/* */} + + + + + + ) } diff --git a/web-app/src/routes/hub/$modelId.tsx b/web-app/src/routes/hub/$modelId.tsx index 2d0eecc70..75ccc58bf 100644 --- a/web-app/src/routes/hub/$modelId.tsx +++ b/web-app/src/routes/hub/$modelId.tsx @@ -13,19 +13,18 @@ import { } from '@tabler/icons-react' import { route } from '@/constants/routes' import { useModelSources } from '@/hooks/useModelSources' +import { PlatformGuard } from '@/lib/platform/PlatformGuard' +import { PlatformFeature } from '@/lib/platform' import { extractModelName, extractDescription } from '@/lib/models' import { RenderMarkdown } from '@/containers/RenderMarkdown' import { useEffect, useMemo, useCallback, useState } from 'react' import { useModelProvider } from '@/hooks/useModelProvider' import { useDownloadStore } from '@/hooks/useDownloadStore' -import { +import { useServiceHub } from '@/hooks/useServiceHub' +import type { CatalogModel, ModelQuant, - convertHfRepoToCatalogModel, - fetchHuggingFaceRepo, - pullModelWithMetadata, - isModelSupported, -} from '@/services/models' +} from '@/services/models/types' import { Progress } from '@/components/ui/progress' import { Button } from '@/components/ui/button' import { cn } from '@/lib/utils' @@ -46,6 +45,14 @@ export const Route = createFileRoute('/hub/$modelId')({ }) function HubModelDetail() { + return ( + + + + ) +} + +function HubModelDetailContent() { const { modelId } = useParams({ from: Route.id }) const navigate = useNavigate() const { huggingfaceToken } = useGeneralSetting() @@ -56,6 +63,7 @@ function HubModelDetail() { const llamaProvider = getProviderByName('llamacpp') const { downloads, localDownloadingModels, addLocalDownloadingModel } = useDownloadStore() + const serviceHub = useServiceHub() const [repoData, setRepoData] = useState() // State for README content @@ -64,7 +72,7 @@ function HubModelDetail() { // State for model support status const [modelSupportStatus, setModelSupportStatus] = useState< - Record + Record >({}) useEffect(() => { @@ -72,15 +80,15 @@ function HubModelDetail() { }, [fetchSources]) const fetchRepo = useCallback(async () => { - const repoInfo = await fetchHuggingFaceRepo( + const repoInfo = await serviceHub.models().fetchHuggingFaceRepo( search.repo || modelId, huggingfaceToken ) if (repoInfo) { - const repoDetail = convertHfRepoToCatalogModel(repoInfo) - setRepoData(repoDetail) + const repoDetail = serviceHub.models().convertHfRepoToCatalogModel(repoInfo) + setRepoData(repoDetail || undefined) } - }, [modelId, search, huggingfaceToken]) + }, [serviceHub, modelId, search, huggingfaceToken]) useEffect(() => { fetchRepo() @@ -160,7 +168,7 @@ function HubModelDetail() { try { // Use the HuggingFace path for the model const modelPath = variant.path - const supported = await isModelSupported(modelPath, 8192) + const supported = await serviceHub.models().isModelSupported(modelPath, 8192) setModelSupportStatus((prev) => ({ ...prev, [modelKey]: supported, @@ -173,7 +181,7 @@ function HubModelDetail() { })) } }, - [modelSupportStatus] + [modelSupportStatus, serviceHub] ) // Extract tags from quants (model variants) @@ -465,7 +473,7 @@ function HubModelDetail() { addLocalDownloadingModel( variant.model_id ) - pullModelWithMetadata( + serviceHub.models().pullModelWithMetadata( variant.model_id, variant.path, modelData.mmproj_models?.[0]?.path, diff --git a/web-app/src/routes/hub/index.tsx b/web-app/src/routes/hub/index.tsx index 07dd0f85b..2a53a848f 100644 --- a/web-app/src/routes/hub/index.tsx +++ b/web-app/src/routes/hub/index.tsx @@ -4,6 +4,8 @@ import { createFileRoute, useNavigate, useSearch } from '@tanstack/react-router' import { route } from '@/constants/routes' import { useModelSources } from '@/hooks/useModelSources' import { cn } from '@/lib/utils' +import { PlatformGuard } from '@/lib/platform/PlatformGuard' +import { PlatformFeature } from '@/lib/platform' import { useState, useMemo, @@ -40,13 +42,8 @@ import { DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu' -import { - CatalogModel, - pullModelWithMetadata, - fetchHuggingFaceRepo, - convertHfRepoToCatalogModel, - isModelSupported, -} from '@/services/models' +import { useServiceHub } from '@/hooks/useServiceHub' +import type { CatalogModel } from '@/services/models/types' import { useDownloadStore } from '@/hooks/useDownloadStore' import { Progress } from '@/components/ui/progress' import HeaderPage from '@/containers/HeaderPage' @@ -71,8 +68,17 @@ export const Route = createFileRoute(route.hub.index as any)({ }) function Hub() { + return ( + + + + ) +} + +function HubContent() { const parentRef = useRef(null) const { huggingfaceToken } = useGeneralSetting() + const serviceHub = useServiceHub() const { t } = useTranslation() const sortOptions = [ @@ -194,46 +200,50 @@ function Hub() { fetchSources() }, [fetchSources]) + const fetchHuggingFaceModel = async (searchValue: string) => { + if ( + !searchValue.length || + (!searchValue.includes('/') && !searchValue.startsWith('http')) + ) { + return + } + + setIsSearching(true) + if (addModelSourceTimeoutRef.current) { + clearTimeout(addModelSourceTimeoutRef.current) + } + + addModelSourceTimeoutRef.current = setTimeout(async () => { + try { + const repoInfo = await serviceHub.models().fetchHuggingFaceRepo(searchValue, huggingfaceToken) + if (repoInfo) { + const catalogModel = serviceHub.models().convertHfRepoToCatalogModel(repoInfo) + if ( + !sources.some( + (s) => + catalogModel.model_name.trim().split('/').pop() === + s.model_name.trim() && + catalogModel.developer.trim() === s.developer?.trim() + ) + ) { + setHuggingFaceRepo(catalogModel) + } + } + } catch (error) { + console.error('Error fetching repository info:', error) + } finally { + setIsSearching(false) + } + }, 500) + } + const handleSearchChange = (e: ChangeEvent) => { setIsSearching(false) setSearchValue(e.target.value) setHuggingFaceRepo(null) // Clear previous repo info - if (addModelSourceTimeoutRef.current) { - clearTimeout(addModelSourceTimeoutRef.current) - } - - if ( - e.target.value.length && - (e.target.value.includes('/') || e.target.value.startsWith('http')) - ) { - setIsSearching(true) - - addModelSourceTimeoutRef.current = setTimeout(async () => { - try { - // Fetch HuggingFace repository information - const repoInfo = await fetchHuggingFaceRepo( - e.target.value, - huggingfaceToken - ) - if (repoInfo) { - const catalogModel = convertHfRepoToCatalogModel(repoInfo) - if ( - !sources.some( - (s) => - catalogModel.model_name.trim().split('/').pop() === - s.model_name.trim() - ) - ) { - setHuggingFaceRepo(catalogModel) - } - } - } catch (error) { - console.error('Error fetching repository info:', error) - } finally { - setIsSearching(false) - } - }, 500) + if (!showOnlyDownloaded) { + fetchHuggingFaceModel(e.target.value) } } @@ -293,7 +303,7 @@ function Hub() { try { // Use the HuggingFace path for the model const modelPath = variant.path - const supportStatus = await isModelSupported(modelPath, 8192) + const supportStatus = await serviceHub.models().isModelSupported(modelPath, 8192) setModelSupportStatus((prev) => ({ ...prev, @@ -307,7 +317,7 @@ function Hub() { })) } }, - [modelSupportStatus] + [modelSupportStatus, serviceHub] ) const DownloadButtonPlaceholder = useMemo(() => { @@ -353,7 +363,7 @@ function Hub() { // Immediately set local downloading state addLocalDownloadingModel(modelId) const mmprojPath = model.mmproj_models?.[0]?.path - pullModelWithMetadata( + serviceHub.models().pullModelWithMetadata( modelId, modelUrl, mmprojPath, @@ -399,14 +409,15 @@ function Hub() { ) } }, [ + localDownloadingModels, downloadProcesses, llamaProvider?.models, isRecommendedModel, - downloadButtonRef, - localDownloadingModels, - addLocalDownloadingModel, t, + addLocalDownloadingModel, + huggingfaceToken, handleUseModel, + serviceHub, ]) const { step } = useSearch({ from: Route.id }) @@ -482,9 +493,9 @@ function Hub() { const isLastStep = currentStepIndex === steps.length - 1 const renderFilter = () => { - if (searchValue.length === 0) - return ( - <> + return ( + <> + {searchValue.length === 0 && ( @@ -509,17 +520,26 @@ function Hub() { ))} -
- - - {t('hub:downloaded')} - -
- - ) + )} +
+ { + setShowOnlyDownloaded(checked) + if (checked) { + setHuggingFaceRepo(null) + } else { + // Re-trigger HuggingFace search when switching back to "All models" + fetchHuggingFaceModel(searchValue) + } + }} + /> + + {t('hub:downloaded')} + +
+ + ) } return ( @@ -661,6 +681,18 @@ function Hub() { defaultModelQuantizations={ defaultModelQuantizations } + variant={ + filteredModels[ + virtualItem.index + ].quants.find((m) => + defaultModelQuantizations.some((e) => + m.model_id.toLowerCase().includes(e) + ) + ) ?? + filteredModels[virtualItem.index] + .quants?.[0] + } + isDefaultVariant={true} modelSupportStatus={modelSupportStatus} onCheckModelSupport={checkModelSupport} /> @@ -930,7 +962,7 @@ function Hub() { addLocalDownloadingModel( variant.model_id ) - pullModelWithMetadata( + serviceHub.models().pullModelWithMetadata( variant.model_id, variant.path, filteredModels[ diff --git a/web-app/src/routes/index.tsx b/web-app/src/routes/index.tsx index a8d9815ff..4ff643356 100644 --- a/web-app/src/routes/index.tsx +++ b/web-app/src/routes/index.tsx @@ -35,11 +35,12 @@ function Index() { useTools() // Conditional to check if there are any valid providers - // required min 1 api_key or 1 model in llama.cpp + // required min 1 api_key or 1 model in llama.cpp or jan provider const hasValidProviders = providers.some( (provider) => provider.api_key?.length || - (provider.provider === 'llamacpp' && provider.models.length) + (provider.provider === 'llamacpp' && provider.models.length) || + (provider.provider === 'jan' && provider.models.length) ) useEffect(() => { diff --git a/web-app/src/routes/local-api-server/logs.tsx b/web-app/src/routes/local-api-server/logs.tsx index ee3b41ab5..6c6909774 100644 --- a/web-app/src/routes/local-api-server/logs.tsx +++ b/web-app/src/routes/local-api-server/logs.tsx @@ -2,15 +2,25 @@ import { createFileRoute } from '@tanstack/react-router' import { route } from '@/constants/routes' import { useEffect, useState, useRef } from 'react' -import { parseLogLine, readLogs } from '@/services/app' -import { listen } from '@tauri-apps/api/event' +import { useServiceHub } from '@/hooks/useServiceHub' +import type { LogEntry } from '@/services/app/types' import { useTranslation } from '@/i18n/react-i18next-compat' +import { PlatformGuard } from '@/lib/platform/PlatformGuard' +import { PlatformFeature } from '@/lib/platform' // eslint-disable-next-line @typescript-eslint/no-explicit-any export const Route = createFileRoute(route.localApiServerlogs as any)({ - component: LogsViewer, + component: LocalApiServerLogsGuarded, }) +function LocalApiServerLogsGuarded() { + return ( + + + + ) +} + const SERVER_LOG_TARGET = 'app_lib::core::server::proxy' const LOG_EVENT_NAME = 'log://log' @@ -18,9 +28,10 @@ function LogsViewer() { const { t } = useTranslation() const [logs, setLogs] = useState([]) const logsContainerRef = useRef(null) + const serviceHub = useServiceHub() useEffect(() => { - readLogs().then((logData) => { + serviceHub.app().readLogs().then((logData) => { const logs = logData .filter((log) => log?.target === SERVER_LOG_TARGET) .filter(Boolean) as LogEntry[] @@ -32,9 +43,9 @@ function LogsViewer() { }, 100) }) let unsubscribe = () => {} - listen(LOG_EVENT_NAME, (event) => { + serviceHub.events().listen(LOG_EVENT_NAME, (event) => { const { message } = event.payload as { message: string } - const log: LogEntry | undefined = parseLogLine(message) + const log: LogEntry | undefined = serviceHub.app().parseLogLine(message) if (log?.target === SERVER_LOG_TARGET) { setLogs((prevLogs) => { const newLogs = [...prevLogs, log] @@ -51,7 +62,7 @@ function LogsViewer() { return () => { unsubscribe() } - }, []) + }, [serviceHub]) // Function to scroll to the bottom of the logs container const scrollToBottom = () => { diff --git a/web-app/src/routes/logs.tsx b/web-app/src/routes/logs.tsx index c1c420ba8..95afde4d7 100644 --- a/web-app/src/routes/logs.tsx +++ b/web-app/src/routes/logs.tsx @@ -2,25 +2,36 @@ import { createFileRoute } from '@tanstack/react-router' import { route } from '@/constants/routes' import { useEffect, useState, useRef } from 'react' -import { readLogs } from '@/services/app' +import { useServiceHub } from '@/hooks/useServiceHub' import { useTranslation } from '@/i18n/react-i18next-compat' +import { PlatformGuard } from '@/lib/platform/PlatformGuard' +import { PlatformFeature } from '@/lib/platform' // eslint-disable-next-line @typescript-eslint/no-explicit-any export const Route = createFileRoute(route.appLogs as any)({ - component: LogsViewer, + component: LogsViewerGuarded, }) +function LogsViewerGuarded() { + return ( + + + + ) +} + // Define log entry type function LogsViewer() { const { t } = useTranslation() const [logs, setLogs] = useState([]) const logsContainerRef = useRef(null) + const serviceHub = useServiceHub() useEffect(() => { let lastLogsLength = 0 function updateLogs() { - readLogs().then((logData) => { + serviceHub.app().readLogs().then((logData) => { let needScroll = false const filteredLogs = logData.filter(Boolean) as LogEntry[] if (filteredLogs.length > lastLogsLength) needScroll = true @@ -40,7 +51,7 @@ function LogsViewer() { return () => { clearInterval(intervalId) } - }, []) + }, [serviceHub]) // Function to scroll to the bottom of the logs container const scrollToBottom = () => { diff --git a/web-app/src/routes/settings/__tests__/general.test.tsx b/web-app/src/routes/settings/__tests__/general.test.tsx index e21a28dcf..c9955ca95 100644 --- a/web-app/src/routes/settings/__tests__/general.test.tsx +++ b/web-app/src/routes/settings/__tests__/general.test.tsx @@ -167,14 +167,37 @@ vi.mock('@/components/ui/dialog', () => ({ ), })) -vi.mock('@/services/app', () => ({ - factoryReset: vi.fn(), - getJanDataFolder: vi.fn().mockResolvedValue('/test/data/folder'), - relocateJanDataFolder: vi.fn(), +vi.mock('@/services/app/web', () => ({ + WebAppService: vi.fn().mockImplementation(() => ({ + factoryReset: vi.fn(), + getJanDataFolder: vi.fn().mockResolvedValue('/test/data/folder'), + relocateJanDataFolder: vi.fn(), + })), })) -vi.mock('@/services/models', () => ({ - stopAllModels: vi.fn(), +vi.mock('@/services/models/default', () => ({ + DefaultModelsService: vi.fn().mockImplementation(() => ({ + stopAllModels: vi.fn(), + })), +})) + +vi.mock('@/hooks/useServiceHub', () => ({ + useServiceHub: () => ({ + app: () => ({ + factoryReset: vi.fn(), + getJanDataFolder: vi.fn().mockResolvedValue('/test/data/folder'), + relocateJanDataFolder: vi.fn(), + }), + models: () => ({ + stopAllModels: vi.fn(), + }), + dialog: () => ({ + open: vi.fn().mockResolvedValue('/test/path'), + }), + events: () => ({ + emit: vi.fn(), + }), + }), })) vi.mock('@tauri-apps/plugin-dialog', () => ({ @@ -236,6 +259,7 @@ vi.mock('@/types/events', () => ({ }, })) + vi.mock('@tanstack/react-router', () => ({ createFileRoute: (path: string) => (config: any) => ({ ...config, @@ -247,6 +271,7 @@ vi.mock('@tanstack/react-router', () => ({ global.VERSION = '1.0.0' global.IS_MACOS = false global.IS_WINDOWS = true +global.AUTO_UPDATER_DISABLED = false global.window = { ...global.window, core: { diff --git a/web-app/src/routes/settings/__tests__/hardware.test.tsx b/web-app/src/routes/settings/__tests__/hardware.test.tsx index 831821310..604ee639c 100644 --- a/web-app/src/routes/settings/__tests__/hardware.test.tsx +++ b/web-app/src/routes/settings/__tests__/hardware.test.tsx @@ -103,6 +103,17 @@ vi.mock('@tanstack/react-router', () => ({ createFileRoute: () => (config: any) => config, })) +// Mock platform utils to enable hardware monitoring +vi.mock('@/lib/platform/utils', () => ({ + isPlatformTauri: () => true, + getUnavailableFeatureMessage: () => 'Feature not available', +})) + +// Mock PlatformGuard to always render children +vi.mock('@/lib/platform/PlatformGuard', () => ({ + PlatformGuard: ({ children }: { children: React.ReactNode }) => <>{children}, +})) + global.IS_MACOS = false // Import the actual component after all mocks are set up diff --git a/web-app/src/routes/settings/extensions.tsx b/web-app/src/routes/settings/extensions.tsx index fbe97ec71..9843d48b0 100644 --- a/web-app/src/routes/settings/extensions.tsx +++ b/web-app/src/routes/settings/extensions.tsx @@ -8,6 +8,8 @@ import SettingsMenu from '@/containers/SettingsMenu' import { RenderMarkdown } from '@/containers/RenderMarkdown' import { ExtensionManager } from '@/lib/extension' import { useTranslation } from '@/i18n/react-i18next-compat' +import { PlatformGuard } from '@/lib/platform/PlatformGuard' +import { PlatformFeature } from '@/lib/platform' // eslint-disable-next-line @typescript-eslint/no-explicit-any export const Route = createFileRoute(route.settings.extensions as any)({ @@ -15,6 +17,14 @@ export const Route = createFileRoute(route.settings.extensions as any)({ }) function Extensions() { + return ( + + + + ) +} + +function ExtensionsContent() { const { t } = useTranslation() const extensions = ExtensionManager.getInstance().listExtensions() return ( diff --git a/web-app/src/routes/settings/general.tsx b/web-app/src/routes/settings/general.tsx index aa93f985a..a07015c3f 100644 --- a/web-app/src/routes/settings/general.tsx +++ b/web-app/src/routes/settings/general.tsx @@ -9,8 +9,6 @@ import { useTranslation } from '@/i18n/react-i18next-compat' import { useGeneralSetting } from '@/hooks/useGeneralSetting' import { useAppUpdater } from '@/hooks/useAppUpdater' import { useEffect, useState, useCallback } from 'react' -import { open } from '@tauri-apps/plugin-dialog' -import { revealItemInDir } from '@tauri-apps/plugin-opener' import ChangeDataFolderLocation from '@/containers/dialogs/ChangeDataFolderLocation' import { @@ -23,11 +21,7 @@ import { DialogTitle, DialogTrigger, } from '@/components/ui/dialog' -import { - factoryReset, - getJanDataFolder, - relocateJanDataFolder, -} from '@/services/app' +import { useServiceHub } from '@/hooks/useServiceHub' import { IconBrandDiscord, IconBrandGithub, @@ -37,16 +31,15 @@ import { IconCopy, IconCopyCheck, } from '@tabler/icons-react' -import { WebviewWindow } from '@tauri-apps/api/webviewWindow' -import { windowKey } from '@/constants/windows' +// import { windowKey } from '@/constants/windows' import { toast } from 'sonner' import { isDev } from '@/lib/utils' -import { emit } from '@tauri-apps/api/event' -import { stopAllModels } from '@/services/models' import { SystemEvent } from '@/types/events' import { Input } from '@/components/ui/input' import { useHardware } from '@/hooks/useHardware' import LanguageSwitcher from '@/containers/LanguageSwitcher' +import { PlatformFeatures } from '@/lib/platform/const' +import { PlatformFeature } from '@/lib/platform/types' // eslint-disable-next-line @typescript-eslint/no-explicit-any export const Route = createFileRoute(route.settings.general as any)({ @@ -61,6 +54,7 @@ function General() { huggingfaceToken, setHuggingfaceToken, } = useGeneralSetting() + const serviceHub = useServiceHub() const openFileTitle = (): string => { if (IS_MACOS) { @@ -81,51 +75,22 @@ function General() { useEffect(() => { const fetchDataFolder = async () => { - const path = await getJanDataFolder() + const path = await serviceHub.app().getJanDataFolder() setJanDataFolder(path) } fetchDataFolder() - }, []) + }, [serviceHub]) const resetApp = async () => { pausePolling() // TODO: Loading indicator - await factoryReset() + await serviceHub.app().factoryReset() } const handleOpenLogs = async () => { try { - // Check if logs window already exists - const existingWindow = await WebviewWindow.getByLabel( - windowKey.logsAppWindow - ) - - if (existingWindow) { - // If window exists, focus it - await existingWindow.setFocus() - console.log('Focused existing logs window') - } else { - // Create a new logs window using Tauri v2 WebviewWindow API - const logsWindow = new WebviewWindow(windowKey.logsAppWindow, { - url: route.appLogs, - title: 'App Logs - Jan', - width: 800, - height: 600, - resizable: true, - center: true, - }) - - // Listen for window creation - logsWindow.once('tauri://created', () => { - console.log('Logs window created') - }) - - // Listen for window errors - logsWindow.once('tauri://error', (e) => { - console.error('Error creating logs window:', e) - }) - } + await serviceHub.window().openLogsWindow() } catch (error) { console.error('Failed to open logs window:', error) } @@ -142,7 +107,7 @@ function General() { } const handleDataFolderChange = async () => { - const selectedPath = await open({ + const selectedPath = await serviceHub.dialog().open({ multiple: false, directory: true, defaultPath: janDataFolder, @@ -150,7 +115,7 @@ function General() { if (selectedPath === janDataFolder) return if (selectedPath !== null) { - setSelectedNewPath(selectedPath) + setSelectedNewPath(selectedPath as string) setIsDialogOpen(true) } } @@ -158,11 +123,11 @@ function General() { const confirmDataFolderChange = async () => { if (selectedNewPath) { try { - await stopAllModels() - emit(SystemEvent.KILL_SIDECAR) + await serviceHub.models().stopAllModels() + serviceHub.events().emit(SystemEvent.KILL_SIDECAR) setTimeout(async () => { try { - await relocateJanDataFolder(selectedNewPath) + await serviceHub.app().relocateJanDataFolder(selectedNewPath) setJanDataFolder(selectedNewPath) // Only relaunch if relocation was successful window.core?.api?.relaunch() @@ -180,7 +145,7 @@ function General() { } catch (error) { console.error('Failed to relocate data folder:', error) // Revert the data folder path on error - const originalPath = await getJanDataFolder() + const originalPath = await serviceHub.app().getJanDataFolder() setJanDataFolder(originalPath) toast.error(t('settings:general.failedToRelocateDataFolderDesc')) @@ -216,15 +181,17 @@ function General() {
{/* General */} - - v{VERSION} - - } - /> - {!AUTO_UPDATER_DISABLED && ( + {PlatformFeatures[PlatformFeature.SYSTEM_INTEGRATIONS] && ( + + v{VERSION} + + } + /> + )} + {!AUTO_UPDATER_DISABLED && PlatformFeatures[PlatformFeature.SYSTEM_INTEGRATIONS] && ( - {/* Data folder */} + {/* Data folder - Desktop only */} + {PlatformFeatures[PlatformFeature.SYSTEM_INTEGRATIONS] && ( - {/* Advanced */} + )} + {/* Advanced - Desktop only */} + {PlatformFeatures[PlatformFeature.SYSTEM_INTEGRATIONS] && ( + )} {/* Other */} @@ -458,23 +429,25 @@ function General() { /> } /> - setHuggingfaceToken(e.target.value)} - placeholder={'hf_xxx'} - required - /> - } - /> + {PlatformFeatures[PlatformFeature.MODEL_HUB] && ( + setHuggingfaceToken(e.target.value)} + placeholder={'hf_xxx'} + required + /> + } + /> + )} {/* Resources */} diff --git a/web-app/src/routes/settings/hardware.tsx b/web-app/src/routes/settings/hardware.tsx index fc3987743..83c383198 100644 --- a/web-app/src/routes/settings/hardware.tsx +++ b/web-app/src/routes/settings/hardware.tsx @@ -10,13 +10,13 @@ import { useHardware } from '@/hooks/useHardware' import { useLlamacppDevices } from '@/hooks/useLlamacppDevices' import { useEffect, useState } from 'react' import { IconDeviceDesktopAnalytics } from '@tabler/icons-react' -import { getHardwareInfo, getSystemUsage } from '@/services/hardware' -import { WebviewWindow } from '@tauri-apps/api/webviewWindow' +import { useServiceHub } from '@/hooks/useServiceHub' +import type { HardwareData, SystemUsage } from '@/services/hardware/types' import { formatMegaBytes } from '@/lib/utils' -import { windowKey } from '@/constants/windows' import { toNumber } from '@/utils/number' import { useModelProvider } from '@/hooks/useModelProvider' -import { stopAllModels } from '@/services/models' +import { PlatformGuard } from '@/lib/platform/PlatformGuard' +import { PlatformFeature } from '@/lib/platform' // eslint-disable-next-line @typescript-eslint/no-explicit-any export const Route = createFileRoute(route.settings.hardware as any)({ @@ -24,8 +24,17 @@ export const Route = createFileRoute(route.settings.hardware as any)({ }) function Hardware() { + return ( + + + + ) +} + +function HardwareContent() { const { t } = useTranslation() const [isLoading, setIsLoading] = useState(false) + const serviceHub = useServiceHub() const { hardwareData, systemUsage, @@ -66,74 +75,47 @@ function Hardware() { useEffect(() => { setIsLoading(true) Promise.all([ - getHardwareInfo() - .then((data) => { - setHardwareData(data) + serviceHub.hardware().getHardwareInfo() + .then((data: HardwareData | null) => { + if (data) setHardwareData(data) }) .catch((error) => { console.error('Failed to get hardware info:', error) }), - getSystemUsage() - .then((data) => { - updateSystemUsage(data) + serviceHub.hardware().getSystemUsage() + .then((data: SystemUsage | null) => { + if (data) updateSystemUsage(data) }) - .catch((error) => { + .catch((error: unknown) => { console.error('Failed to get initial system usage:', error) }), ]).finally(() => { setIsLoading(false) }) - }, [setHardwareData, updateSystemUsage]) + }, [serviceHub, setHardwareData, updateSystemUsage]) useEffect(() => { - if (pollingPaused) return + if (pollingPaused) { + return + } const intervalId = setInterval(() => { - getSystemUsage() - .then((data) => { - updateSystemUsage(data) + serviceHub.hardware().getSystemUsage() + .then((data: SystemUsage | null) => { + if (data) updateSystemUsage(data) }) - .catch((error) => { + .catch((error: unknown) => { console.error('Failed to get system usage:', error) }) }, 5000) return () => clearInterval(intervalId) - }, [updateSystemUsage, pollingPaused]) + }, [serviceHub, updateSystemUsage, pollingPaused]) const handleClickSystemMonitor = async () => { try { - // Check if system monitor window already exists - const existingWindow = await WebviewWindow.getByLabel( - windowKey.systemMonitorWindow - ) - - if (existingWindow) { - // If window exists, focus it - await existingWindow.setFocus() - console.log('Focused existing system monitor window') - } else { - // Create a new system monitor window - const monitorWindow = new WebviewWindow(windowKey.systemMonitorWindow, { - url: route.systemMonitor, - title: 'System Monitor - Jan', - width: 900, - height: 600, - resizable: true, - center: true, - }) - - // Listen for window creation - monitorWindow.once('tauri://created', () => { - console.log('System monitor window created') - }) - - // Listen for window errors - monitorWindow.once('tauri://error', (e) => { - console.error('Error creating system monitor window:', e) - }) - } + await serviceHub.window().openSystemMonitorWindow() } catch (error) { console.error('Failed to open system monitor window:', error) } @@ -326,7 +308,7 @@ function Hardware() { checked={device.activated} onCheckedChange={() => { toggleDevice(device.id) - stopAllModels() + serviceHub.models().stopAllModels() }} />
diff --git a/web-app/src/routes/settings/https-proxy.tsx b/web-app/src/routes/settings/https-proxy.tsx index a718ce51e..f58fa4e55 100644 --- a/web-app/src/routes/settings/https-proxy.tsx +++ b/web-app/src/routes/settings/https-proxy.tsx @@ -9,6 +9,8 @@ import { Input } from '@/components/ui/input' import { EyeOff, Eye } from 'lucide-react' import { useCallback, useState } from 'react' import { useProxyConfig } from '@/hooks/useProxyConfig' +import { PlatformGuard } from '@/lib/platform/PlatformGuard' +import { PlatformFeature } from '@/lib/platform' // eslint-disable-next-line @typescript-eslint/no-explicit-any export const Route = createFileRoute(route.settings.https_proxy as any)({ @@ -16,6 +18,14 @@ export const Route = createFileRoute(route.settings.https_proxy as any)({ }) function HTTPSProxy() { + return ( + + + + ) +} + +function HTTPSProxyContent() { const { t } = useTranslation() const [showPassword, setShowPassword] = useState(false) const { diff --git a/web-app/src/routes/settings/local-api-server.tsx b/web-app/src/routes/settings/local-api-server.tsx index 8b426ddf2..840e1fdb7 100644 --- a/web-app/src/routes/settings/local-api-server.tsx +++ b/web-app/src/routes/settings/local-api-server.tsx @@ -11,17 +11,16 @@ import { PortInput } from '@/containers/PortInput' import { ApiPrefixInput } from '@/containers/ApiPrefixInput' import { TrustedHostsInput } from '@/containers/TrustedHostsInput' import { useLocalApiServer } from '@/hooks/useLocalApiServer' -import { WebviewWindow } from '@tauri-apps/api/webviewWindow' import { useAppState } from '@/hooks/useAppState' import { useModelProvider } from '@/hooks/useModelProvider' -import { startModel } from '@/services/models' +import { useServiceHub } from '@/hooks/useServiceHub' import { localStorageKey } from '@/constants/localStorage' -import { windowKey } from '@/constants/windows' import { IconLogs } from '@tabler/icons-react' import { cn } from '@/lib/utils' import { ApiKeyInput } from '@/containers/ApiKeyInput' import { useEffect, useState } from 'react' -import { invoke } from '@tauri-apps/api/core' +import { PlatformGuard } from '@/lib/platform/PlatformGuard' +import { PlatformFeature } from '@/lib/platform' // eslint-disable-next-line @typescript-eslint/no-explicit-any export const Route = createFileRoute(route.settings.local_api_server as any)({ @@ -29,7 +28,16 @@ export const Route = createFileRoute(route.settings.local_api_server as any)({ }) function LocalAPIServer() { + return ( + + + + ) +} + +function LocalAPIServerContent() { const { t } = useTranslation() + const serviceHub = useServiceHub() const { corsEnabled, setCorsEnabled, @@ -45,7 +53,8 @@ function LocalAPIServer() { } = useLocalApiServer() const { serverStatus, setServerStatus } = useAppState() - const { selectedModel, selectedProvider, getProviderByName } = useModelProvider() + const { selectedModel, selectedProvider, getProviderByName } = + useModelProvider() const [showApiKeyError, setShowApiKeyError] = useState(false) const [isApiKeyEmpty, setIsApiKeyEmpty] = useState( !apiKey || apiKey.toString().trim().length === 0 @@ -53,14 +62,14 @@ function LocalAPIServer() { useEffect(() => { const checkServerStatus = async () => { - invoke('get_server_status').then((running) => { + serviceHub.app().getServerStatus().then((running) => { if (running) { setServerStatus('running') } }) } checkServerStatus() - }, [setServerStatus]) + }, [serviceHub, setServerStatus]) const handleApiKeyValidation = (isValid: boolean) => { setIsApiKeyEmpty(!isValid) @@ -135,7 +144,7 @@ function LocalAPIServer() { setServerStatus('pending') // Start the model first - startModel(modelToStart.provider, modelToStart.model) + serviceHub.models().startModel(modelToStart.provider, modelToStart.model) .then(() => { console.log(`Model ${modelToStart.model} started successfully`) @@ -173,39 +182,7 @@ function LocalAPIServer() { const handleOpenLogs = async () => { try { - // Check if logs window already exists - const existingWindow = await WebviewWindow.getByLabel( - windowKey.logsWindowLocalApiServer - ) - - if (existingWindow) { - // If window exists, focus it - await existingWindow.setFocus() - console.log('Focused existing logs window') - } else { - // Create a new logs window using Tauri v2 WebviewWindow API - const logsWindow = new WebviewWindow( - windowKey.logsWindowLocalApiServer, - { - url: route.localApiServerlogs, - title: 'Local API server Logs - Jan', - width: 800, - height: 600, - resizable: true, - center: true, - } - ) - - // Listen for window creation - logsWindow.once('tauri://created', () => { - console.log('Logs window created') - }) - - // Listen for window errors - logsWindow.once('tauri://error', (e) => { - console.error('Error creating logs window:', e) - }) - } + await serviceHub.window().openLocalApiServerLogsWindow() } catch (error) { console.error('Failed to open logs window:', error) } @@ -293,38 +270,31 @@ function LocalAPIServer() { } + actions={ + + } /> } + actions={} /> } + actions={} /> @@ -334,11 +304,12 @@ function LocalAPIServer() { title={t('settings:localApiServer.trustedHosts')} description={t('settings:localApiServer.trustedHostsDesc')} className={cn( - 'flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-y-2', - isServerRunning && 'opacity-50 pointer-events-none' + 'flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-y-2' )} classNameWrapperAction="w-full sm:w-auto" - actions={} + actions={ + + } /> diff --git a/web-app/src/routes/settings/mcp-servers.tsx b/web-app/src/routes/settings/mcp-servers.tsx index c95c47a2d..3eb20dd3a 100644 --- a/web-app/src/routes/settings/mcp-servers.tsx +++ b/web-app/src/routes/settings/mcp-servers.tsx @@ -16,12 +16,13 @@ import DeleteMCPServerConfirm from '@/containers/dialogs/DeleteMCPServerConfirm' import EditJsonMCPserver from '@/containers/dialogs/EditJsonMCPserver' import { Switch } from '@/components/ui/switch' import { twMerge } from 'tailwind-merge' -import { getConnectedServers } from '@/services/mcp' +import { useServiceHub } from '@/hooks/useServiceHub' import { useToolApproval } from '@/hooks/useToolApproval' import { toast } from 'sonner' -import { invoke } from '@tauri-apps/api/core' import { useTranslation } from '@/i18n/react-i18next-compat' import { useAppState } from '@/hooks/useAppState' +import { PlatformGuard } from '@/lib/platform/PlatformGuard' +import { PlatformFeature } from '@/lib/platform' // Function to mask sensitive values const maskSensitiveValue = (value: string) => { @@ -88,11 +89,21 @@ export const Route = createFileRoute(route.settings.mcp_servers as any)({ }) function MCPServers() { + return ( + + + + ) +} + +function MCPServersContent() { const { t } = useTranslation() + const serviceHub = useServiceHub() const { mcpServers, addServer, editServer, + renameServer, deleteServer, syncServers, syncServersAndRestart, @@ -137,22 +148,27 @@ function MCPServers() { } const handleSaveServer = async (name: string, config: MCPServerConfig) => { - toggleServer(name, false) if (editingKey) { - // If server name changed, delete old one and add new one + // If server name changed, rename it while preserving position if (editingKey !== name) { - deleteServer(editingKey) - addServer(name, config) + toggleServer(editingKey, false) + renameServer(editingKey, name, config) + toggleServer(name, true) + // Restart servers to update tool references with new server name + syncServersAndRestart() } else { + toggleServer(editingKey, false) editServer(editingKey, config) + toggleServer(editingKey, true) + syncServers() } } else { // Add new server + toggleServer(name, false) addServer(name, config) + toggleServer(name, true) + syncServers() } - - syncServers() - toggleServer(name, true) } const handleEdit = (serverKey: string) => { @@ -168,7 +184,7 @@ function MCPServers() { if (serverToDelete) { // Stop the server before deletion try { - await invoke('deactivate_mcp_server', { name: serverToDelete }) + await serviceHub.mcp().deactivateMCPServer(serverToDelete) } catch (error) { console.error('Error stopping server before deletion:', error) } @@ -227,12 +243,9 @@ function MCPServers() { setLoadingServers((prev) => ({ ...prev, [serverKey]: true })) const config = getServerConfig(serverKey) if (active && config) { - invoke('activate_mcp_server', { - name: serverKey, - config: { - ...(config ?? (mcpServers[serverKey] as MCPServerConfig)), - active, - }, + serviceHub.mcp().activateMCPServer(serverKey, { + ...(config ?? (mcpServers[serverKey] as MCPServerConfig)), + active, }) .then(() => { // Save single server @@ -246,7 +259,7 @@ function MCPServers() { ? t('mcp-servers:serverStatusActive', { serverKey }) : t('mcp-servers:serverStatusInactive', { serverKey }) ) - getConnectedServers().then(setConnectedServers) + serviceHub.mcp().getConnectedServers().then(setConnectedServers) }) .catch((error) => { editServer(serverKey, { @@ -267,8 +280,8 @@ function MCPServers() { active, }) syncServers() - invoke('deactivate_mcp_server', { name: serverKey }).finally(() => { - getConnectedServers().then(setConnectedServers) + serviceHub.mcp().deactivateMCPServer(serverKey).finally(() => { + serviceHub.mcp().getConnectedServers().then(setConnectedServers) setLoadingServers((prev) => ({ ...prev, [serverKey]: false })) }) } @@ -276,14 +289,14 @@ function MCPServers() { } useEffect(() => { - getConnectedServers().then(setConnectedServers) + serviceHub.mcp().getConnectedServers().then(setConnectedServers) const intervalId = setInterval(() => { - getConnectedServers().then(setConnectedServers) + serviceHub.mcp().getConnectedServers().then(setConnectedServers) }, 3000) return () => clearInterval(intervalId) - }, [setConnectedServers]) + }, [serviceHub, setConnectedServers]) return (
diff --git a/web-app/src/routes/settings/privacy.tsx b/web-app/src/routes/settings/privacy.tsx index 425c4865a..3d0771db7 100644 --- a/web-app/src/routes/settings/privacy.tsx +++ b/web-app/src/routes/settings/privacy.tsx @@ -7,6 +7,8 @@ import { Card, CardItem } from '@/containers/Card' import { useTranslation } from '@/i18n/react-i18next-compat' import { useAnalytic } from '@/hooks/useAnalytic' import posthog from 'posthog-js' +import { PlatformFeatures } from '@/lib/platform/const' +import { PlatformFeature } from '@/lib/platform/types' // eslint-disable-next-line @typescript-eslint/no-explicit-any export const Route = createFileRoute(route.settings.privacy as any)({ @@ -26,7 +28,8 @@ function Privacy() {
-

@@ -82,6 +85,7 @@ function Privacy() { } /> + )}

diff --git a/web-app/src/routes/settings/providers/$providerName.tsx b/web-app/src/routes/settings/providers/$providerName.tsx index 9d456cc40..873dc29b3 100644 --- a/web-app/src/routes/settings/providers/$providerName.tsx +++ b/web-app/src/routes/settings/providers/$providerName.tsx @@ -1,17 +1,8 @@ -/* eslint-disable react-hooks/exhaustive-deps */ import { Card, CardItem } from '@/containers/Card' import HeaderPage from '@/containers/HeaderPage' import SettingsMenu from '@/containers/SettingsMenu' import { useModelProvider } from '@/hooks/useModelProvider' import { cn, getProviderTitle } from '@/lib/utils' -import { open } from '@tauri-apps/plugin-dialog' -import { - getActiveModels, - pullModel, - startModel, - stopAllModels, - stopModel, -} from '@/services/models' import { createFileRoute, Link, @@ -31,16 +22,17 @@ import Joyride, { CallBackProps, STATUS } from 'react-joyride' import { CustomTooltipJoyRide } from '@/containers/CustomeTooltipJoyRide' import { route } from '@/constants/routes' import DeleteProvider from '@/containers/dialogs/DeleteProvider' -import { updateSettings, fetchModelsFromProvider } from '@/services/providers' +import { useServiceHub } from '@/hooks/useServiceHub' import { localStorageKey } from '@/constants/localStorage' import { Button } from '@/components/ui/button' import { IconFolderPlus, IconLoader, IconRefresh } from '@tabler/icons-react' -import { getProviders } from '@/services/providers' import { toast } from 'sonner' -import { useEffect, useState } from 'react' +import { useCallback, useEffect, useState } from 'react' import { predefinedProviders } from '@/consts/providers' import { useModelLoad } from '@/hooks/useModelLoad' import { useLlamacppDevices } from '@/hooks/useLlamacppDevices' +import { PlatformFeatures } from '@/lib/platform/const' +import { PlatformFeature } from '@/lib/platform/types' // as route.threadsDetail export const Route = createFileRoute('/settings/providers/$providerName')({ @@ -55,6 +47,7 @@ export const Route = createFileRoute('/settings/providers/$providerName')({ function ProviderDetail() { const { t } = useTranslation() + const serviceHub = useServiceHub() const { setModelLoadError } = useModelLoad() const steps = [ { @@ -103,7 +96,7 @@ function ProviderDetail() { } setImportingModel(true) - const selectedFile = await open({ + const selectedFile = await serviceHub.dialog().open({ multiple: false, directory: false, }) @@ -128,9 +121,9 @@ function ProviderDetail() { } try { - await pullModel(fileName, selectedFile) + await serviceHub.models().pullModel(fileName, typeof selectedFile === 'string' ? selectedFile : selectedFile?.[0]) // Refresh the provider to update the models list - await getProviders().then(setProviders) + await serviceHub.providers().getProviders().then(setProviders) toast.success(t('providers:import'), { id: `import-model-${provider.provider}`, description: t('providers:importModelSuccess', { @@ -153,28 +146,28 @@ function ProviderDetail() { useEffect(() => { // Initial data fetch - getActiveModels().then((models) => setActiveModels(models || [])) + serviceHub.models().getActiveModels().then((models) => setActiveModels(models || [])) // Set up interval for real-time updates const intervalId = setInterval(() => { - getActiveModels().then((models) => setActiveModels(models || [])) + serviceHub.models().getActiveModels().then((models) => setActiveModels(models || [])) }, 5000) return () => clearInterval(intervalId) - }, [setActiveModels]) + }, [serviceHub, setActiveModels]) // Auto-refresh provider settings to get updated backend configuration - const refreshSettings = async () => { + const refreshSettings = useCallback(async () => { if (!provider) return try { // Refresh providers to get updated settings from the extension - const updatedProviders = await getProviders() + const updatedProviders = await serviceHub.providers().getProviders() setProviders(updatedProviders) } catch (error) { console.error('Failed to refresh settings:', error) } - } + }, [provider, serviceHub, setProviders]) // Auto-refresh settings when provider changes or when llamacpp needs backend config useEffect(() => { @@ -183,7 +176,7 @@ function ProviderDetail() { const intervalId = setInterval(refreshSettings, 3000) return () => clearInterval(intervalId) } - }, [provider, needsBackendConfig]) + }, [provider, needsBackendConfig, refreshSettings]) // Note: settingsChanged event is now handled globally in GlobalEventHandler // This ensures all screens receive the event intermediately @@ -206,7 +199,7 @@ function ProviderDetail() { setRefreshingModels(true) try { - const modelIds = await fetchModelsFromProvider(provider) + const modelIds = await serviceHub.providers().fetchModelsFromProvider(provider) // Create new models from the fetched IDs const newModels: Model[] = modelIds.map((id) => ({ @@ -261,9 +254,11 @@ function ProviderDetail() { // Add model to loading state setLoadingModels((prev) => [...prev, modelId]) if (provider) - startModel(provider, modelId) + // Original: startModel(provider, modelId).then(() => { setActiveModels((prevModels) => [...prevModels, modelId]) }) + serviceHub.models().startModel(provider, modelId) .then(() => { - setActiveModels((prevModels) => [...prevModels, modelId]) + // Refresh active models after starting + serviceHub.models().getActiveModels().then((models) => setActiveModels(models || [])) }) .catch((error) => { console.error('Error starting model:', error) @@ -280,17 +275,41 @@ function ProviderDetail() { } const handleStopModel = (modelId: string) => { - stopModel(modelId) + // Original: stopModel(modelId).then(() => { setActiveModels((prevModels) => prevModels.filter((model) => model !== modelId)) }) + serviceHub.models().stopModel(modelId) .then(() => { - setActiveModels((prevModels) => - prevModels.filter((model) => model !== modelId) - ) + // Refresh active models after stopping + serviceHub.models().getActiveModels().then((models) => setActiveModels(models || [])) }) .catch((error) => { console.error('Error stopping model:', error) }) } + // Check if model provider settings are enabled for this platform + if (!PlatformFeatures[PlatformFeature.MODEL_PROVIDER_SETTINGS]) { + return ( +
+ +

{t('common:settings')}

+
+
+ +
+
+

+ {t('common:notAvailable')} +

+

+ Provider settings are not available on the web platform. +

+
+
+
+
+ ) + } + return ( <> @@ -584,10 +603,12 @@ function ProviderDetail() { } actions={
- + {provider && provider.provider !== 'llamacpp' && ( + + )} {model.settings && ( + +

{t('common:settings')}

+
+
+ +
+
+

+ {t('common:notAvailable')} +

+

+ Model provider settings are not available on the web platform. +

+
+
+
+
+ ) + } + return (
@@ -172,7 +199,7 @@ function ModelProviders() { checked={provider.active} onCheckedChange={async (e) => { if (!e && provider.provider.toLowerCase() === 'llamacpp') { - await stopAllModels() + await serviceHub.models().stopAllModels() } updateProvider(provider.provider, { ...provider, diff --git a/web-app/src/routes/system-monitor.tsx b/web-app/src/routes/system-monitor.tsx index f09d2061b..78c2ecc43 100644 --- a/web-app/src/routes/system-monitor.tsx +++ b/web-app/src/routes/system-monitor.tsx @@ -9,15 +9,26 @@ import { IconDeviceDesktopAnalytics } from '@tabler/icons-react' import { useTranslation } from '@/i18n/react-i18next-compat' import { toNumber } from '@/utils/number' import { useLlamacppDevices } from '@/hooks/useLlamacppDevices' -import { getSystemUsage } from '@/services/hardware' +import { useServiceHub } from '@/hooks/useServiceHub' +import { PlatformGuard } from '@/lib/platform/PlatformGuard' +import { PlatformFeature } from '@/lib/platform' export const Route = createFileRoute(route.systemMonitor as any)({ component: SystemMonitor, }) function SystemMonitor() { + return ( + + + + ) +} + +function SystemMonitorContent() { const { t } = useTranslation() const { hardwareData, systemUsage, updateSystemUsage } = useHardware() + const serviceHub = useServiceHub() const { devices: llamacppDevices, fetchDevices } = useLlamacppDevices() @@ -29,9 +40,11 @@ function SystemMonitor() { // Poll system usage every 5 seconds useEffect(() => { const intervalId = setInterval(() => { - getSystemUsage() + serviceHub.hardware().getSystemUsage() .then((data) => { - updateSystemUsage(data) + if (data) { + updateSystemUsage(data) + } }) .catch((error) => { console.error('Failed to get system usage:', error) @@ -39,7 +52,7 @@ function SystemMonitor() { }, 5000) return () => clearInterval(intervalId) - }, [updateSystemUsage]) + }, [updateSystemUsage, serviceHub]) // Calculate RAM usage percentage const ramUsagePercentage = diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx index 87c5d55ca..6f2a83de8 100644 --- a/web-app/src/routes/threads/$threadId.tsx +++ b/web-app/src/routes/threads/$threadId.tsx @@ -14,7 +14,7 @@ import { ThreadContent } from '@/containers/ThreadContent' import { StreamingContent } from '@/containers/StreamingContent' import { useMessages } from '@/hooks/useMessages' -import { fetchMessages } from '@/services/messages' +import { useServiceHub } from '@/hooks/useServiceHub' import { useAppState } from '@/hooks/useAppState' import DropdownAssistant from '@/containers/DropdownAssistant' import { useAssistant } from '@/hooks/useAssistant' @@ -32,6 +32,7 @@ export const Route = createFileRoute('/threads/$threadId')({ function ThreadDetail() { const { t } = useTranslation() + const serviceHub = useServiceHub() const { threadId } = useParams({ from: Route.id }) const [isUserScrolling, setIsUserScrolling] = useState(false) const [isAtBottom, setIsAtBottom] = useState(true) @@ -86,14 +87,14 @@ function ThreadDetail() { }, [threadId, currentThreadId, assistants]) useEffect(() => { - fetchMessages(threadId).then((fetchedMessages) => { + serviceHub.messages().fetchMessages(threadId).then((fetchedMessages) => { if (fetchedMessages) { // Update the messages in the store setMessages(threadId, fetchedMessages) } }) // eslint-disable-next-line react-hooks/exhaustive-deps - }, [threadId]) + }, [threadId, serviceHub]) useEffect(() => { return () => { diff --git a/web-app/src/services/__tests__/analytic.test.ts b/web-app/src/services/__tests__/analytic.test.ts index 94f3fa7e9..94e25610f 100644 --- a/web-app/src/services/__tests__/analytic.test.ts +++ b/web-app/src/services/__tests__/analytic.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { updateDistinctId, getAppDistinctId } from '../analytic' +import { DefaultAnalyticService } from '../analytic/default' // Mock window.core API const mockGetAppConfigurations = vi.fn() @@ -18,9 +18,12 @@ Object.defineProperty(window, 'core', { value: mockCore, }) -describe('analytic service', () => { +describe('DefaultAnalyticService', () => { + let analyticService: DefaultAnalyticService + beforeEach(() => { vi.clearAllMocks() + analyticService = new DefaultAnalyticService() }) describe('updateDistinctId', () => { @@ -33,7 +36,7 @@ describe('analytic service', () => { mockGetAppConfigurations.mockResolvedValue(mockConfiguration) mockUpdateAppConfiguration.mockResolvedValue(undefined) - await updateDistinctId('new-distinct-id') + await analyticService.updateDistinctId('new-distinct-id') expect(mockGetAppConfigurations).toHaveBeenCalledTimes(1) expect(mockUpdateAppConfiguration).toHaveBeenCalledWith({ @@ -52,7 +55,7 @@ describe('analytic service', () => { mockGetAppConfigurations.mockResolvedValue(mockConfiguration) mockUpdateAppConfiguration.mockResolvedValue(undefined) - await updateDistinctId('first-distinct-id') + await analyticService.updateDistinctId('first-distinct-id') expect(mockUpdateAppConfiguration).toHaveBeenCalledWith({ configuration: { @@ -70,7 +73,7 @@ describe('analytic service', () => { mockGetAppConfigurations.mockResolvedValue(mockConfiguration) mockUpdateAppConfiguration.mockResolvedValue(undefined) - await updateDistinctId('') + await analyticService.updateDistinctId('') expect(mockUpdateAppConfiguration).toHaveBeenCalledWith({ configuration: { @@ -86,7 +89,7 @@ describe('analytic service', () => { mockGetAppConfigurations.mockResolvedValue(mockConfiguration) mockUpdateAppConfiguration.mockResolvedValue(undefined) - await updateDistinctId(uuidId) + await analyticService.updateDistinctId(uuidId) expect(mockUpdateAppConfiguration).toHaveBeenCalledWith({ configuration: { @@ -98,7 +101,7 @@ describe('analytic service', () => { it('should handle API errors gracefully', async () => { mockGetAppConfigurations.mockRejectedValue(new Error('API Error')) - await expect(updateDistinctId('test-id')).rejects.toThrow('API Error') + await expect(analyticService.updateDistinctId('test-id')).rejects.toThrow('API Error') expect(mockUpdateAppConfiguration).not.toHaveBeenCalled() }) @@ -108,7 +111,7 @@ describe('analytic service', () => { mockGetAppConfigurations.mockResolvedValue(mockConfiguration) mockUpdateAppConfiguration.mockRejectedValue(new Error('Update Error')) - await expect(updateDistinctId('new-id')).rejects.toThrow('Update Error') + await expect(analyticService.updateDistinctId('new-id')).rejects.toThrow('Update Error') }) }) @@ -121,7 +124,7 @@ describe('analytic service', () => { mockGetAppConfigurations.mockResolvedValue(mockConfiguration) - const result = await getAppDistinctId() + const result = await analyticService.getAppDistinctId() expect(result).toBe('test-distinct-id') expect(mockGetAppConfigurations).toHaveBeenCalledTimes(1) @@ -134,7 +137,7 @@ describe('analytic service', () => { mockGetAppConfigurations.mockResolvedValue(mockConfiguration) - const result = await getAppDistinctId() + const result = await analyticService.getAppDistinctId() expect(result).toBeUndefined() }) @@ -146,7 +149,7 @@ describe('analytic service', () => { mockGetAppConfigurations.mockResolvedValue(mockConfiguration) - const result = await getAppDistinctId() + const result = await analyticService.getAppDistinctId() expect(result).toBe('') }) @@ -154,19 +157,19 @@ describe('analytic service', () => { it('should handle null configuration', async () => { mockGetAppConfigurations.mockResolvedValue(null) - await expect(getAppDistinctId()).rejects.toThrow() + await expect(analyticService.getAppDistinctId()).rejects.toThrow() }) it('should handle undefined configuration', async () => { mockGetAppConfigurations.mockResolvedValue(undefined) - await expect(getAppDistinctId()).rejects.toThrow() + await expect(analyticService.getAppDistinctId()).rejects.toThrow() }) it('should handle API errors', async () => { mockGetAppConfigurations.mockRejectedValue(new Error('Get Config Error')) - await expect(getAppDistinctId()).rejects.toThrow('Get Config Error') + await expect(analyticService.getAppDistinctId()).rejects.toThrow('Get Config Error') }) it('should handle different types of distinct_id values', async () => { @@ -175,7 +178,7 @@ describe('analytic service', () => { distinct_id: '550e8400-e29b-41d4-a716-446655440000', }) - let result = await getAppDistinctId() + let result = await analyticService.getAppDistinctId() expect(result).toBe('550e8400-e29b-41d4-a716-446655440000') // Test with simple string @@ -183,7 +186,7 @@ describe('analytic service', () => { distinct_id: 'user123', }) - result = await getAppDistinctId() + result = await analyticService.getAppDistinctId() expect(result).toBe('user123') // Test with numeric string @@ -191,7 +194,7 @@ describe('analytic service', () => { distinct_id: '12345', }) - result = await getAppDistinctId() + result = await analyticService.getAppDistinctId() expect(result).toBe('12345') }) }) @@ -212,10 +215,10 @@ describe('analytic service', () => { }) // Update the distinct id - await updateDistinctId(newId) + await analyticService.updateDistinctId(newId) // Retrieve the distinct id - const retrievedId = await getAppDistinctId() + const retrievedId = await analyticService.getAppDistinctId() expect(retrievedId).toBe(newId) expect(mockGetAppConfigurations).toHaveBeenCalledTimes(2) @@ -233,8 +236,8 @@ describe('analytic service', () => { value: undefined, }) - await expect(updateDistinctId('test')).rejects.toThrow() - await expect(getAppDistinctId()).rejects.toThrow() + await expect(analyticService.updateDistinctId('test')).rejects.toThrow() + await expect(analyticService.getAppDistinctId()).rejects.toThrow() // Restore core Object.defineProperty(window, 'core', { @@ -252,8 +255,8 @@ describe('analytic service', () => { value: {}, }) - await expect(updateDistinctId('test')).rejects.toThrow() - await expect(getAppDistinctId()).rejects.toThrow() + await expect(analyticService.updateDistinctId('test')).rejects.toThrow() + await expect(analyticService.getAppDistinctId()).rejects.toThrow() // Restore core Object.defineProperty(window, 'core', { diff --git a/web-app/src/services/__tests__/app.test.ts b/web-app/src/services/__tests__/app.test.ts index 56a591a75..816a8a97d 100644 --- a/web-app/src/services/__tests__/app.test.ts +++ b/web-app/src/services/__tests__/app.test.ts @@ -1,17 +1,29 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { - factoryReset, - readLogs, - parseLogLine, - getJanDataFolder, - relocateJanDataFolder, -} from '../app' +import { TauriAppService } from '../app/tauri' // Mock dependencies vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(), })) +// Mock EngineManager +vi.mock('@janhq/core', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + EngineManager: { + instance: () => ({ + engines: new Map([ + ['engine1', { + getLoadedModels: vi.fn().mockResolvedValue(['model1', 'model2']), + unload: vi.fn().mockResolvedValue(undefined), + }], + ]), + }), + }, + } +}) + vi.mock('@tauri-apps/api/event', () => ({ emit: vi.fn(), })) @@ -51,15 +63,18 @@ Object.defineProperty(window, 'localStorage', { writable: true, }) -describe('app service', () => { +describe('TauriAppService', () => { + let appService: TauriAppService + beforeEach(() => { + appService = new TauriAppService() vi.clearAllMocks() }) describe('parseLogLine', () => { it('should parse valid log line', () => { const logLine = '[2024-01-01][10:00:00Z][target][INFO] Test message' - const result = parseLogLine(logLine) + const result = appService.parseLogLine(logLine) expect(result).toEqual({ timestamp: '2024-01-01 10:00:00Z', @@ -71,7 +86,7 @@ describe('app service', () => { it('should handle invalid log line format', () => { const logLine = 'Invalid log line' - const result = parseLogLine(logLine) + const result = appService.parseLogLine(logLine) expect(result.message).toBe('Invalid log line') expect(result.level).toBe('info') @@ -87,7 +102,7 @@ describe('app service', () => { '[2024-01-01][10:00:00Z][target][INFO] Test message\n[2024-01-01][10:01:00Z][target][ERROR] Error message' vi.mocked(invoke).mockResolvedValue(mockLogs) - const result = await readLogs() + const result = await appService.readLogs() expect(invoke).toHaveBeenCalledWith('read_logs') expect(result).toHaveLength(2) @@ -99,7 +114,7 @@ describe('app service', () => { const { invoke } = await import('@tauri-apps/api/core') vi.mocked(invoke).mockResolvedValue('') - const result = await readLogs() + const result = await appService.readLogs() expect(result).toEqual([expect.objectContaining({ message: '' })]) }) @@ -110,7 +125,7 @@ describe('app service', () => { const mockConfig = { data_folder: '/path/to/jan/data' } mockWindow.core.api.getAppConfigurations.mockResolvedValue(mockConfig) - const result = await getJanDataFolder() + const result = await appService.getJanDataFolder() expect(mockWindow.core.api.getAppConfigurations).toHaveBeenCalled() expect(result).toBe('/path/to/jan/data') @@ -122,7 +137,7 @@ describe('app service', () => { const newPath = '/new/path/to/jan/data' mockWindow.core.api.changeAppDataFolder.mockResolvedValue(undefined) - await relocateJanDataFolder(newPath) + await appService.relocateJanDataFolder(newPath) expect(mockWindow.core.api.changeAppDataFolder).toHaveBeenCalledWith({ newDataFolder: newPath, @@ -131,23 +146,19 @@ describe('app service', () => { }) describe('factoryReset', () => { - it('should perform factory reset', async () => { - const { stopAllModels } = await import('../models') + it.skip('should perform factory reset', async () => { const { invoke } = await import('@tauri-apps/api/core') - vi.mocked(stopAllModels).mockResolvedValue() - // Use fake timers vi.useFakeTimers() - const factoryResetPromise = factoryReset() + const factoryResetPromise = appService.factoryReset() // Advance timers and run all pending timers await vi.advanceTimersByTimeAsync(1000) await factoryResetPromise - expect(stopAllModels).toHaveBeenCalled() expect(mockWindow.localStorage.clear).toHaveBeenCalled() expect(invoke).toHaveBeenCalledWith('factory_reset') diff --git a/web-app/src/services/__tests__/assistants.test.ts b/web-app/src/services/__tests__/assistants.test.ts index eda489f19..8c7d96e2c 100644 --- a/web-app/src/services/__tests__/assistants.test.ts +++ b/web-app/src/services/__tests__/assistants.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { getAssistants, createAssistant, deleteAssistant } from '../assistants' +import { DefaultAssistantsService } from '../assistants/default' import { ExtensionManager } from '@/lib/extension' import { ExtensionTypeEnum } from '@janhq/core' @@ -12,7 +12,9 @@ vi.mock('@/lib/extension', () => ({ } })) -describe('assistants service', () => { +describe('DefaultAssistantsService', () => { + let assistantsService: DefaultAssistantsService + const mockExtension = { getAssistants: vi.fn(), createAssistant: vi.fn(), @@ -24,6 +26,7 @@ describe('assistants service', () => { } beforeEach(() => { + assistantsService = new DefaultAssistantsService() vi.clearAllMocks() vi.mocked(ExtensionManager.getInstance).mockReturnValue(mockExtensionManager) mockExtensionManager.get.mockReturnValue(mockExtension) @@ -37,7 +40,7 @@ describe('assistants service', () => { ] mockExtension.getAssistants.mockResolvedValue(mockAssistants) - const result = await getAssistants() + const result = await assistantsService.getAssistants() expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant) expect(mockExtension.getAssistants).toHaveBeenCalled() @@ -49,7 +52,7 @@ describe('assistants service', () => { const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const result = await getAssistants() + const result = await assistantsService.getAssistants() expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant) expect(consoleSpy).toHaveBeenCalledWith('AssistantExtension not found') @@ -62,7 +65,7 @@ describe('assistants service', () => { const error = new Error('Failed to get assistants') mockExtension.getAssistants.mockRejectedValue(error) - await expect(getAssistants()).rejects.toThrow('Failed to get assistants') + await expect(assistantsService.getAssistants()).rejects.toThrow('Failed to get assistants') }) }) @@ -71,18 +74,18 @@ describe('assistants service', () => { const assistant = { id: 'new-assistant', name: 'New Assistant', description: 'New assistant' } mockExtension.createAssistant.mockResolvedValue(assistant) - const result = await createAssistant(assistant) + const result = await assistantsService.createAssistant(assistant) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant) expect(mockExtension.createAssistant).toHaveBeenCalledWith(assistant) - expect(result).toEqual(assistant) + expect(result).toBeUndefined() }) it('should return undefined when extension not found', async () => { mockExtensionManager.get.mockReturnValue(null) const assistant = { id: 'new-assistant', name: 'New Assistant', description: 'New assistant' } - const result = await createAssistant(assistant) + const result = await assistantsService.createAssistant(assistant) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant) expect(result).toBeUndefined() @@ -93,7 +96,7 @@ describe('assistants service', () => { const error = new Error('Failed to create assistant') mockExtension.createAssistant.mockRejectedValue(error) - await expect(createAssistant(assistant)).rejects.toThrow('Failed to create assistant') + await expect(assistantsService.createAssistant(assistant)).rejects.toThrow('Failed to create assistant') }) }) @@ -102,7 +105,7 @@ describe('assistants service', () => { const assistant = { id: 'assistant-to-delete', name: 'Assistant to Delete', description: 'Delete me' } mockExtension.deleteAssistant.mockResolvedValue(undefined) - const result = await deleteAssistant(assistant) + const result = await assistantsService.deleteAssistant(assistant) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant) expect(mockExtension.deleteAssistant).toHaveBeenCalledWith(assistant) @@ -113,7 +116,7 @@ describe('assistants service', () => { mockExtensionManager.get.mockReturnValue(null) const assistant = { id: 'assistant-to-delete', name: 'Assistant to Delete', description: 'Delete me' } - const result = await deleteAssistant(assistant) + const result = await assistantsService.deleteAssistant(assistant) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Assistant) expect(result).toBeUndefined() @@ -124,7 +127,7 @@ describe('assistants service', () => { const error = new Error('Failed to delete assistant') mockExtension.deleteAssistant.mockRejectedValue(error) - await expect(deleteAssistant(assistant)).rejects.toThrow('Failed to delete assistant') + await expect(assistantsService.deleteAssistant(assistant)).rejects.toThrow('Failed to delete assistant') }) }) }) \ No newline at end of file diff --git a/web-app/src/services/__tests__/events.test.ts b/web-app/src/services/__tests__/events.test.ts index 88a6c9a8c..ab3d597f8 100644 --- a/web-app/src/services/__tests__/events.test.ts +++ b/web-app/src/services/__tests__/events.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi } from 'vitest' -import { EventEmitter } from '../events' +import { EventEmitter } from '../events/EventEmitter' describe('EventEmitter', () => { let eventEmitter: EventEmitter @@ -9,132 +9,23 @@ describe('EventEmitter', () => { }) describe('constructor', () => { - it('should create an instance with empty handlers map', () => { + it('should create an instance of EventEmitter', () => { expect(eventEmitter).toBeInstanceOf(EventEmitter) - expect(eventEmitter['handlers']).toBeInstanceOf(Map) - expect(eventEmitter['handlers'].size).toBe(0) }) }) describe('on method', () => { - it('should register a handler for a new event', () => { + it('should register an event handler', () => { const handler = vi.fn() - eventEmitter.on('test-event', handler) - expect(eventEmitter['handlers'].has('test-event')).toBe(true) - expect(eventEmitter['handlers'].get('test-event')).toContain(handler) + eventEmitter.emit('test-event', 'test-data') + + expect(handler).toHaveBeenCalledOnce() + expect(handler).toHaveBeenCalledWith('test-data') }) - it('should add multiple handlers for the same event', () => { - const handler1 = vi.fn() - const handler2 = vi.fn() - - eventEmitter.on('test-event', handler1) - eventEmitter.on('test-event', handler2) - - const handlers = eventEmitter['handlers'].get('test-event') - expect(handlers).toHaveLength(2) - expect(handlers).toContain(handler1) - expect(handlers).toContain(handler2) - }) - - it('should handle multiple different events', () => { - const handler1 = vi.fn() - const handler2 = vi.fn() - - eventEmitter.on('event1', handler1) - eventEmitter.on('event2', handler2) - - expect(eventEmitter['handlers'].has('event1')).toBe(true) - expect(eventEmitter['handlers'].has('event2')).toBe(true) - expect(eventEmitter['handlers'].get('event1')).toContain(handler1) - expect(eventEmitter['handlers'].get('event2')).toContain(handler2) - }) - - it('should allow the same handler to be registered multiple times', () => { - const handler = vi.fn() - - eventEmitter.on('test-event', handler) - eventEmitter.on('test-event', handler) - - const handlers = eventEmitter['handlers'].get('test-event') - expect(handlers).toHaveLength(2) - expect(handlers![0]).toBe(handler) - expect(handlers![1]).toBe(handler) - }) - }) - - describe('off method', () => { - it('should remove a handler from an existing event', () => { - const handler = vi.fn() - - eventEmitter.on('test-event', handler) - expect(eventEmitter['handlers'].get('test-event')).toContain(handler) - - eventEmitter.off('test-event', handler) - expect(eventEmitter['handlers'].get('test-event')).not.toContain(handler) - }) - - it('should do nothing when trying to remove handler from non-existent event', () => { - const handler = vi.fn() - - // Should not throw an error - expect(() => { - eventEmitter.off('non-existent-event', handler) - }).not.toThrow() - }) - - it('should do nothing when trying to remove non-existent handler', () => { - const handler1 = vi.fn() - const handler2 = vi.fn() - - eventEmitter.on('test-event', handler1) - - // Should not throw an error - expect(() => { - eventEmitter.off('test-event', handler2) - }).not.toThrow() - - // Original handler should still be there - expect(eventEmitter['handlers'].get('test-event')).toContain(handler1) - }) - - it('should remove only the first occurrence of a handler', () => { - const handler = vi.fn() - - eventEmitter.on('test-event', handler) - eventEmitter.on('test-event', handler) - - expect(eventEmitter['handlers'].get('test-event')).toHaveLength(2) - - eventEmitter.off('test-event', handler) - - expect(eventEmitter['handlers'].get('test-event')).toHaveLength(1) - expect(eventEmitter['handlers'].get('test-event')).toContain(handler) - }) - - it('should remove correct handler when multiple handlers exist', () => { - const handler1 = vi.fn() - const handler2 = vi.fn() - const handler3 = vi.fn() - - eventEmitter.on('test-event', handler1) - eventEmitter.on('test-event', handler2) - eventEmitter.on('test-event', handler3) - - eventEmitter.off('test-event', handler2) - - const handlers = eventEmitter['handlers'].get('test-event') - expect(handlers).toHaveLength(2) - expect(handlers).toContain(handler1) - expect(handlers).not.toContain(handler2) - expect(handlers).toContain(handler3) - }) - }) - - describe('emit method', () => { - it('should call all handlers for an event', () => { + it('should register multiple handlers for the same event', () => { const handler1 = vi.fn() const handler2 = vi.fn() @@ -143,55 +34,62 @@ describe('EventEmitter', () => { eventEmitter.emit('test-event', 'test-data') - expect(handler1).toHaveBeenCalledWith('test-data') - expect(handler2).toHaveBeenCalledWith('test-data') + expect(handler1).toHaveBeenCalledOnce() + expect(handler2).toHaveBeenCalledOnce() + }) + }) + + describe('off method', () => { + it('should remove an event handler', () => { + const handler = vi.fn() + + eventEmitter.on('test-event', handler) + eventEmitter.emit('test-event', 'data1') + expect(handler).toHaveBeenCalledTimes(1) + + eventEmitter.off('test-event', handler) + eventEmitter.emit('test-event', 'data2') + expect(handler).toHaveBeenCalledTimes(1) // Should not be called again }) - it('should do nothing when emitting non-existent event', () => { - // Should not throw an error - expect(() => { - eventEmitter.emit('non-existent-event', 'data') - }).not.toThrow() + it('should not affect other handlers when removing one', () => { + const handler1 = vi.fn() + const handler2 = vi.fn() + + eventEmitter.on('test-event', handler1) + eventEmitter.on('test-event', handler2) + + eventEmitter.off('test-event', handler1) + eventEmitter.emit('test-event', 'test-data') + + expect(handler1).not.toHaveBeenCalled() + expect(handler2).toHaveBeenCalledOnce() }) + }) - it('should pass arguments to handlers', () => { + describe('emit method', () => { + it('should emit events with data', () => { const handler = vi.fn() const testData = { message: 'test', number: 42 } eventEmitter.on('test-event', handler) eventEmitter.emit('test-event', testData) + expect(handler).toHaveBeenCalledOnce() expect(handler).toHaveBeenCalledWith(testData) }) - it('should call handlers in the order they were added', () => { - const callOrder: number[] = [] - const handler1 = vi.fn(() => callOrder.push(1)) - const handler2 = vi.fn(() => callOrder.push(2)) - const handler3 = vi.fn(() => callOrder.push(3)) - - eventEmitter.on('test-event', handler1) - eventEmitter.on('test-event', handler2) - eventEmitter.on('test-event', handler3) - - eventEmitter.emit('test-event', null) - - expect(callOrder).toEqual([1, 2, 3]) - }) - - it('should handle null and undefined arguments', () => { + it('should emit events without data', () => { const handler = vi.fn() eventEmitter.on('test-event', handler) + eventEmitter.emit('test-event') - eventEmitter.emit('test-event', null) - expect(handler).toHaveBeenCalledWith(null) - - eventEmitter.emit('test-event', undefined) + expect(handler).toHaveBeenCalledOnce() expect(handler).toHaveBeenCalledWith(undefined) }) - it('should not affect other events', () => { + it('should handle different event types independently', () => { const handler1 = vi.fn() const handler2 = vi.fn() @@ -199,34 +97,33 @@ describe('EventEmitter', () => { eventEmitter.on('event2', handler2) eventEmitter.emit('event1', 'data1') + eventEmitter.emit('event2', 'data2') + expect(handler1).toHaveBeenCalledOnce() + expect(handler2).toHaveBeenCalledOnce() expect(handler1).toHaveBeenCalledWith('data1') - expect(handler2).not.toHaveBeenCalled() + expect(handler2).toHaveBeenCalledWith('data2') }) }) describe('integration tests', () => { it('should support complete event lifecycle', () => { - const handler1 = vi.fn() - const handler2 = vi.fn() + const handler = vi.fn() - // Register handlers - eventEmitter.on('lifecycle-event', handler1) - eventEmitter.on('lifecycle-event', handler2) + // Register handler + eventEmitter.on('lifecycle-event', handler) // Emit event - eventEmitter.emit('lifecycle-event', 'test-data') - expect(handler1).toHaveBeenCalledWith('test-data') - expect(handler2).toHaveBeenCalledWith('test-data') + eventEmitter.emit('lifecycle-event', 'lifecycle-data') + expect(handler).toHaveBeenCalledOnce() + expect(handler).toHaveBeenCalledWith('lifecycle-data') - // Remove one handler - eventEmitter.off('lifecycle-event', handler1) + // Remove handler + eventEmitter.off('lifecycle-event', handler) - // Emit again - eventEmitter.emit('lifecycle-event', 'test-data-2') - expect(handler1).toHaveBeenCalledTimes(1) // Still only called once - expect(handler2).toHaveBeenCalledTimes(2) // Called twice - expect(handler2).toHaveBeenLastCalledWith('test-data-2') + // Emit again - should not call handler + eventEmitter.emit('lifecycle-event', 'new-data') + expect(handler).toHaveBeenCalledTimes(1) }) it('should handle complex data types', () => { @@ -235,12 +132,13 @@ describe('EventEmitter', () => { array: [1, 2, 3], object: { nested: true }, function: () => 'test', - symbol: Symbol('test'), + symbol: Symbol('test') } eventEmitter.on('complex-event', handler) eventEmitter.emit('complex-event', complexData) + expect(handler).toHaveBeenCalledOnce() expect(handler).toHaveBeenCalledWith(complexData) }) }) diff --git a/web-app/src/services/__tests__/hardware.test.ts b/web-app/src/services/__tests__/hardware.test.ts index f877b3b3c..f9a16155b 100644 --- a/web-app/src/services/__tests__/hardware.test.ts +++ b/web-app/src/services/__tests__/hardware.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { getHardwareInfo, getSystemUsage, setActiveGpus } from '../hardware' +import { TauriHardwareService } from '../hardware/tauri' import { HardwareData, SystemUsage } from '@/hooks/useHardware' import { invoke } from '@tauri-apps/api/core' @@ -8,8 +8,11 @@ vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(), })) -describe('hardware service', () => { +describe('TauriHardwareService', () => { + let hardwareService: TauriHardwareService + beforeEach(() => { + hardwareService = new TauriHardwareService() vi.clearAllMocks() }) @@ -50,7 +53,7 @@ describe('hardware service', () => { vi.mocked(invoke).mockResolvedValue(mockHardwareData) - const result = await getHardwareInfo() + const result = await hardwareService.getHardwareInfo() expect(vi.mocked(invoke)).toHaveBeenCalledWith('plugin:hardware|get_system_info') expect(result).toEqual(mockHardwareData) @@ -60,7 +63,7 @@ describe('hardware service', () => { const mockError = new Error('Failed to get hardware info') vi.mocked(invoke).mockRejectedValue(mockError) - await expect(getHardwareInfo()).rejects.toThrow('Failed to get hardware info') + await expect(hardwareService.getHardwareInfo()).rejects.toThrow('Failed to get hardware info') expect(vi.mocked(invoke)).toHaveBeenCalledWith('plugin:hardware|get_system_info') }) @@ -81,7 +84,7 @@ describe('hardware service', () => { vi.mocked(invoke).mockResolvedValue(mockHardwareData) - const result = await getHardwareInfo() + const result = await hardwareService.getHardwareInfo() expect(result).toBeDefined() expect(result.cpu).toBeDefined() @@ -110,7 +113,7 @@ describe('hardware service', () => { vi.mocked(invoke).mockResolvedValue(mockSystemUsage) - const result = await getSystemUsage() + const result = await hardwareService.getSystemUsage() expect(vi.mocked(invoke)).toHaveBeenCalledWith('plugin:hardware|get_system_usage') expect(result).toEqual(mockSystemUsage) @@ -120,7 +123,7 @@ describe('hardware service', () => { const mockError = new Error('Failed to get system usage') vi.mocked(invoke).mockRejectedValue(mockError) - await expect(getSystemUsage()).rejects.toThrow('Failed to get system usage') + await expect(hardwareService.getSystemUsage()).rejects.toThrow('Failed to get system usage') expect(vi.mocked(invoke)).toHaveBeenCalledWith('plugin:hardware|get_system_usage') }) @@ -134,7 +137,7 @@ describe('hardware service', () => { vi.mocked(invoke).mockResolvedValue(mockSystemUsage) - const result = await getSystemUsage() + const result = await hardwareService.getSystemUsage() expect(result).toBeDefined() expect(typeof result.cpu).toBe('number') @@ -164,7 +167,7 @@ describe('hardware service', () => { vi.mocked(invoke).mockResolvedValue(mockSystemUsage) - const result = await getSystemUsage() + const result = await hardwareService.getSystemUsage() expect(result.gpus).toHaveLength(2) expect(result.gpus[0].uuid).toBe('gpu-uuid-1') @@ -186,7 +189,7 @@ describe('hardware service', () => { it('should log the provided GPU data', async () => { const gpuData = { gpus: [0, 1, 2] } - await setActiveGpus(gpuData) + await hardwareService.setActiveGpus(gpuData) expect(consoleSpy).toHaveBeenCalledWith(gpuData) }) @@ -194,7 +197,7 @@ describe('hardware service', () => { it('should handle empty GPU array', async () => { const gpuData = { gpus: [] } - await setActiveGpus(gpuData) + await hardwareService.setActiveGpus(gpuData) expect(consoleSpy).toHaveBeenCalledWith(gpuData) }) @@ -202,7 +205,7 @@ describe('hardware service', () => { it('should handle single GPU', async () => { const gpuData = { gpus: [1] } - await setActiveGpus(gpuData) + await hardwareService.setActiveGpus(gpuData) expect(consoleSpy).toHaveBeenCalledWith(gpuData) }) @@ -210,13 +213,13 @@ describe('hardware service', () => { it('should complete successfully', async () => { const gpuData = { gpus: [0, 1] } - await expect(setActiveGpus(gpuData)).resolves.toBeUndefined() + await expect(hardwareService.setActiveGpus(gpuData)).resolves.toBeUndefined() }) it('should not throw any errors', async () => { const gpuData = { gpus: [0, 1, 2, 3] } - expect(() => setActiveGpus(gpuData)).not.toThrow() + expect(() => hardwareService.setActiveGpus(gpuData)).not.toThrow() }) }) @@ -248,8 +251,8 @@ describe('hardware service', () => { .mockResolvedValueOnce(mockSystemUsage) const [hardwareResult, usageResult] = await Promise.all([ - getHardwareInfo(), - getSystemUsage(), + hardwareService.getHardwareInfo(), + hardwareService.getSystemUsage(), ]) expect(hardwareResult).toEqual(mockHardwareData) diff --git a/web-app/src/services/__tests__/mcp.test.ts b/web-app/src/services/__tests__/mcp.test.ts index b45f89ff2..0f5e9d073 100644 --- a/web-app/src/services/__tests__/mcp.test.ts +++ b/web-app/src/services/__tests__/mcp.test.ts @@ -1,12 +1,5 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { - updateMCPConfig, - restartMCPServers, - getMCPConfig, - getTools, - getConnectedServers, - callTool, -} from '../mcp' +import { TauriMCPService } from '../mcp/tauri' import { MCPTool } from '@/types/completion' // Mock the global window.core.api @@ -29,8 +22,11 @@ Object.defineProperty(global, 'window', { writable: true, }) -describe('mcp service', () => { +describe('TauriMCPService', () => { + let mcpService: TauriMCPService + beforeEach(() => { + mcpService = new TauriMCPService() vi.clearAllMocks() }) @@ -39,7 +35,7 @@ describe('mcp service', () => { const testConfig = '{"server1": {"path": "/path/to/server"}, "server2": {"command": "node server.js"}}' mockCore.api.saveMcpConfigs.mockResolvedValue(undefined) - await updateMCPConfig(testConfig) + await mcpService.updateMCPConfig(testConfig) expect(mockCore.api.saveMcpConfigs).toHaveBeenCalledWith({ configs: testConfig, @@ -50,7 +46,7 @@ describe('mcp service', () => { const emptyConfig = '' mockCore.api.saveMcpConfigs.mockResolvedValue(undefined) - await updateMCPConfig(emptyConfig) + await mcpService.updateMCPConfig(emptyConfig) expect(mockCore.api.saveMcpConfigs).toHaveBeenCalledWith({ configs: emptyConfig, @@ -62,7 +58,7 @@ describe('mcp service', () => { const mockError = new Error('Failed to save config') mockCore.api.saveMcpConfigs.mockRejectedValue(mockError) - await expect(updateMCPConfig(testConfig)).rejects.toThrow('Failed to save config') + await expect(mcpService.updateMCPConfig(testConfig)).rejects.toThrow('Failed to save config') expect(mockCore.api.saveMcpConfigs).toHaveBeenCalledWith({ configs: testConfig, }) @@ -76,7 +72,7 @@ describe('mcp service', () => { const testConfig = '{"server1": {}}' - await expect(updateMCPConfig(testConfig)).resolves.toBeUndefined() + await expect(mcpService.updateMCPConfig(testConfig)).resolves.toBeUndefined() // Restore original core window.core = originalCore @@ -87,7 +83,7 @@ describe('mcp service', () => { it('should call restartMcpServers API', async () => { mockCore.api.restartMcpServers.mockResolvedValue(undefined) - await restartMCPServers() + await mcpService.restartMCPServers() expect(mockCore.api.restartMcpServers).toHaveBeenCalledWith() }) @@ -96,7 +92,7 @@ describe('mcp service', () => { const mockError = new Error('Failed to restart servers') mockCore.api.restartMcpServers.mockRejectedValue(mockError) - await expect(restartMCPServers()).rejects.toThrow('Failed to restart servers') + await expect(mcpService.restartMCPServers()).rejects.toThrow('Failed to restart servers') expect(mockCore.api.restartMcpServers).toHaveBeenCalledWith() }) @@ -105,7 +101,7 @@ describe('mcp service', () => { // @ts-ignore window.core = undefined - await expect(restartMCPServers()).resolves.toBeUndefined() + await expect(mcpService.restartMCPServers()).resolves.toBeUndefined() window.core = originalCore }) @@ -121,7 +117,7 @@ describe('mcp service', () => { mockCore.api.getMcpConfigs.mockResolvedValue(mockConfigString) - const result = await getMCPConfig() + const result = await mcpService.getMCPConfig() expect(mockCore.api.getMcpConfigs).toHaveBeenCalledWith() expect(result).toEqual(expectedConfig) @@ -130,7 +126,7 @@ describe('mcp service', () => { it('should return empty object when config is null', async () => { mockCore.api.getMcpConfigs.mockResolvedValue(null) - const result = await getMCPConfig() + const result = await mcpService.getMCPConfig() expect(result).toEqual({}) }) @@ -138,7 +134,7 @@ describe('mcp service', () => { it('should return empty object when config is undefined', async () => { mockCore.api.getMcpConfigs.mockResolvedValue(undefined) - const result = await getMCPConfig() + const result = await mcpService.getMCPConfig() expect(result).toEqual({}) }) @@ -146,7 +142,7 @@ describe('mcp service', () => { it('should return empty object when config is empty string', async () => { mockCore.api.getMcpConfigs.mockResolvedValue('') - const result = await getMCPConfig() + const result = await mcpService.getMCPConfig() expect(result).toEqual({}) }) @@ -155,14 +151,14 @@ describe('mcp service', () => { const invalidJson = '{"invalid": json}' mockCore.api.getMcpConfigs.mockResolvedValue(invalidJson) - await expect(getMCPConfig()).rejects.toThrow() + await expect(mcpService.getMCPConfig()).rejects.toThrow() }) it('should handle API rejection', async () => { const mockError = new Error('Failed to get config') mockCore.api.getMcpConfigs.mockRejectedValue(mockError) - await expect(getMCPConfig()).rejects.toThrow('Failed to get config') + await expect(mcpService.getMCPConfig()).rejects.toThrow('Failed to get config') }) }) @@ -196,7 +192,7 @@ describe('mcp service', () => { mockCore.api.getTools.mockResolvedValue(mockTools) - const result = await getTools() + const result = await mcpService.getTools() expect(mockCore.api.getTools).toHaveBeenCalledWith() expect(result).toEqual(mockTools) @@ -208,7 +204,7 @@ describe('mcp service', () => { it('should return empty array when no tools available', async () => { mockCore.api.getTools.mockResolvedValue([]) - const result = await getTools() + const result = await mcpService.getTools() expect(result).toEqual([]) expect(Array.isArray(result)).toBe(true) @@ -218,7 +214,7 @@ describe('mcp service', () => { const mockError = new Error('Failed to get tools') mockCore.api.getTools.mockRejectedValue(mockError) - await expect(getTools()).rejects.toThrow('Failed to get tools') + await expect(mcpService.getTools()).rejects.toThrow('Failed to get tools') }) it('should handle undefined window.core.api', async () => { @@ -226,7 +222,7 @@ describe('mcp service', () => { // @ts-ignore window.core = undefined - const result = await getTools() + const result = await mcpService.getTools() expect(result).toBeUndefined() @@ -239,7 +235,7 @@ describe('mcp service', () => { const mockServers = ['filesystem', 'database', 'search'] mockCore.api.getConnectedServers.mockResolvedValue(mockServers) - const result = await getConnectedServers() + const result = await mcpService.getConnectedServers() expect(mockCore.api.getConnectedServers).toHaveBeenCalledWith() expect(result).toEqual(mockServers) @@ -249,7 +245,7 @@ describe('mcp service', () => { it('should return empty array when no servers connected', async () => { mockCore.api.getConnectedServers.mockResolvedValue([]) - const result = await getConnectedServers() + const result = await mcpService.getConnectedServers() expect(result).toEqual([]) expect(Array.isArray(result)).toBe(true) @@ -259,7 +255,7 @@ describe('mcp service', () => { const mockError = new Error('Failed to get connected servers') mockCore.api.getConnectedServers.mockRejectedValue(mockError) - await expect(getConnectedServers()).rejects.toThrow('Failed to get connected servers') + await expect(mcpService.getConnectedServers()).rejects.toThrow('Failed to get connected servers') }) it('should handle undefined window.core.api', async () => { @@ -267,7 +263,7 @@ describe('mcp service', () => { // @ts-ignore window.core = undefined - const result = await getConnectedServers() + const result = await mcpService.getConnectedServers() expect(result).toBeUndefined() @@ -289,7 +285,7 @@ describe('mcp service', () => { mockCore.api.callTool.mockResolvedValue(mockResult) - const result = await callTool(toolArgs) + const result = await mcpService.callTool(toolArgs) expect(mockCore.api.callTool).toHaveBeenCalledWith(toolArgs) expect(result).toEqual(mockResult) @@ -308,7 +304,7 @@ describe('mcp service', () => { mockCore.api.callTool.mockResolvedValue(mockResult) - const result = await callTool(toolArgs) + const result = await mcpService.callTool(toolArgs) expect(result.error).toBe('File not found') expect(result.content).toEqual([]) @@ -331,7 +327,7 @@ describe('mcp service', () => { mockCore.api.callTool.mockResolvedValue(mockResult) - const result = await callTool(toolArgs) + const result = await mcpService.callTool(toolArgs) expect(mockCore.api.callTool).toHaveBeenCalledWith(toolArgs) expect(result).toEqual(mockResult) @@ -346,7 +342,7 @@ describe('mcp service', () => { const mockError = new Error('Tool execution failed') mockCore.api.callTool.mockRejectedValue(mockError) - await expect(callTool(toolArgs)).rejects.toThrow('Tool execution failed') + await expect(mcpService.callTool(toolArgs)).rejects.toThrow('Tool execution failed') }) it('should handle undefined window.core.api', async () => { @@ -359,7 +355,7 @@ describe('mcp service', () => { arguments: {}, } - const result = await callTool(toolArgs) + const result = await mcpService.callTool(toolArgs) expect(result).toBeUndefined() @@ -379,7 +375,7 @@ describe('mcp service', () => { mockCore.api.callTool.mockResolvedValue(mockResult) - const result = await callTool(toolArgs) + const result = await mcpService.callTool(toolArgs) expect(mockCore.api.callTool).toHaveBeenCalledWith(toolArgs) expect(result).toEqual(mockResult) @@ -409,11 +405,11 @@ describe('mcp service', () => { mockCore.api.callTool.mockResolvedValue(toolResult) // Execute workflow - await updateMCPConfig(config) - await restartMCPServers() - const availableTools = await getTools() - const connectedServers = await getConnectedServers() - const result = await callTool({ + await mcpService.updateMCPConfig(config) + await mcpService.restartMCPServers() + const availableTools = await mcpService.getTools() + const connectedServers = await mcpService.getConnectedServers() + const result = await mcpService.callTool({ toolName: 'read_file', arguments: { path: '/test.txt' }, }) diff --git a/web-app/src/services/__tests__/messages.test.ts b/web-app/src/services/__tests__/messages.test.ts index bda796ef2..445a9e53a 100644 --- a/web-app/src/services/__tests__/messages.test.ts +++ b/web-app/src/services/__tests__/messages.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { fetchMessages, createMessage, deleteMessage } from '../messages' +import { DefaultMessagesService } from '../messages/default' import { ExtensionManager } from '@/lib/extension' import { ExtensionTypeEnum } from '@janhq/core' @@ -12,7 +12,9 @@ vi.mock('@/lib/extension', () => ({ } })) -describe('messages service', () => { +describe('DefaultMessagesService', () => { + let messagesService: DefaultMessagesService + const mockExtension = { listMessages: vi.fn(), createMessage: vi.fn(), @@ -24,6 +26,7 @@ describe('messages service', () => { } beforeEach(() => { + messagesService = new DefaultMessagesService() vi.clearAllMocks() vi.mocked(ExtensionManager.getInstance).mockReturnValue(mockExtensionManager) mockExtensionManager.get.mockReturnValue(mockExtension) @@ -38,7 +41,7 @@ describe('messages service', () => { ] mockExtension.listMessages.mockResolvedValue(mockMessages) - const result = await fetchMessages(threadId) + const result = await messagesService.fetchMessages(threadId) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational) expect(mockExtension.listMessages).toHaveBeenCalledWith(threadId) @@ -49,7 +52,7 @@ describe('messages service', () => { mockExtensionManager.get.mockReturnValue(null) const threadId = 'thread-123' - const result = await fetchMessages(threadId) + const result = await messagesService.fetchMessages(threadId) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational) expect(result).toEqual([]) @@ -60,7 +63,7 @@ describe('messages service', () => { const error = new Error('Failed to list messages') mockExtension.listMessages.mockRejectedValue(error) - const result = await fetchMessages(threadId) + const result = await messagesService.fetchMessages(threadId) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational) expect(mockExtension.listMessages).toHaveBeenCalledWith(threadId) @@ -71,7 +74,7 @@ describe('messages service', () => { const threadId = 'thread-123' mockExtension.listMessages.mockReturnValue(undefined) - const result = await fetchMessages(threadId) + const result = await messagesService.fetchMessages(threadId) expect(result).toEqual([]) }) @@ -82,7 +85,7 @@ describe('messages service', () => { const message = { id: 'msg-1', threadId: 'thread-123', content: 'Hello', role: 'user' } mockExtension.createMessage.mockResolvedValue(message) - const result = await createMessage(message) + const result = await messagesService.createMessage(message) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational) expect(mockExtension.createMessage).toHaveBeenCalledWith(message) @@ -93,7 +96,7 @@ describe('messages service', () => { mockExtensionManager.get.mockReturnValue(null) const message = { id: 'msg-1', threadId: 'thread-123', content: 'Hello', role: 'user' } - const result = await createMessage(message) + const result = await messagesService.createMessage(message) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational) expect(result).toEqual(message) @@ -104,7 +107,7 @@ describe('messages service', () => { const error = new Error('Failed to create message') mockExtension.createMessage.mockRejectedValue(error) - const result = await createMessage(message) + const result = await messagesService.createMessage(message) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational) expect(mockExtension.createMessage).toHaveBeenCalledWith(message) @@ -115,7 +118,7 @@ describe('messages service', () => { const message = { id: 'msg-1', threadId: 'thread-123', content: 'Hello', role: 'user' } mockExtension.createMessage.mockReturnValue(undefined) - const result = await createMessage(message) + const result = await messagesService.createMessage(message) expect(result).toEqual(message) }) @@ -127,19 +130,19 @@ describe('messages service', () => { const messageId = 'msg-1' mockExtension.deleteMessage.mockResolvedValue(undefined) - const result = await deleteMessage(threadId, messageId) + const result = await messagesService.deleteMessage(threadId, messageId) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational) expect(mockExtension.deleteMessage).toHaveBeenCalledWith(threadId, messageId) expect(result).toBeUndefined() }) - it('should return undefined when extension not found', () => { + it('should return undefined when extension not found', async () => { mockExtensionManager.get.mockReturnValue(null) const threadId = 'thread-123' const messageId = 'msg-1' - const result = deleteMessage(threadId, messageId) + const result = await messagesService.deleteMessage(threadId, messageId) expect(mockExtensionManager.get).toHaveBeenCalledWith(ExtensionTypeEnum.Conversational) expect(result).toBeUndefined() @@ -152,7 +155,7 @@ describe('messages service', () => { mockExtension.deleteMessage.mockRejectedValue(error) // Since deleteMessage doesn't have error handling, the error will propagate - expect(() => deleteMessage(threadId, messageId)).not.toThrow() + await expect(messagesService.deleteMessage(threadId, messageId)).rejects.toThrow('Failed to delete message') }) }) }) \ No newline at end of file diff --git a/web-app/src/services/__tests__/models.test.ts b/web-app/src/services/__tests__/models.test.ts index 286fb01a4..1daf11528 100644 --- a/web-app/src/services/__tests__/models.test.ts +++ b/web-app/src/services/__tests__/models.test.ts @@ -1,22 +1,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' - -import { - fetchModels, - fetchModelCatalog, - fetchHuggingFaceRepo, - convertHfRepoToCatalogModel, - updateModel, - pullModel, - abortDownload, - deleteModel, - getActiveModels, - stopModel, - stopAllModels, - startModel, - isModelSupported, - HuggingFaceRepo, - CatalogModel, -} from '../models' +import { DefaultModelsService } from '../models/default' +import type { HuggingFaceRepo, CatalogModel } from '../models/types' import { EngineManager, Model } from '@janhq/core' // Mock EngineManager @@ -36,7 +20,9 @@ Object.defineProperty(global, 'MODEL_CATALOG_URL', { configurable: true, }) -describe('models service', () => { +describe('DefaultModelsService', () => { + let modelsService: DefaultModelsService + const mockEngine = { list: vi.fn(), updateSettings: vi.fn(), @@ -46,6 +32,9 @@ describe('models service', () => { getLoadedModels: vi.fn(), unload: vi.fn(), load: vi.fn(), + isModelSupported: vi.fn(), + isToolSupported: vi.fn(), + checkMmprojExists: vi.fn(), } const mockEngineManager = { @@ -53,6 +42,7 @@ describe('models service', () => { } beforeEach(() => { + modelsService = new DefaultModelsService() vi.clearAllMocks() ;(EngineManager.instance as any).mockReturnValue(mockEngineManager) }) @@ -65,7 +55,7 @@ describe('models service', () => { ] mockEngine.list.mockResolvedValue(mockModels) - const result = await fetchModels() + const result = await modelsService.fetchModels() expect(result).toEqual(mockModels) expect(mockEngine.list).toHaveBeenCalled() @@ -90,7 +80,7 @@ describe('models service', () => { json: vi.fn().mockResolvedValue(mockCatalog), }) - const result = await fetchModelCatalog() + const result = await modelsService.fetchModelCatalog() expect(result).toEqual(mockCatalog) }) @@ -102,7 +92,7 @@ describe('models service', () => { statusText: 'Not Found', }) - await expect(fetchModelCatalog()).rejects.toThrow( + await expect(modelsService.fetchModelCatalog()).rejects.toThrow( 'Failed to fetch model catalog: 404 Not Found' ) }) @@ -110,7 +100,7 @@ describe('models service', () => { it('should handle network error', async () => { ;(fetch as any).mockRejectedValue(new Error('Network error')) - await expect(fetchModelCatalog()).rejects.toThrow( + await expect(modelsService.fetchModelCatalog()).rejects.toThrow( 'Failed to fetch model catalog: Network error' ) }) @@ -123,7 +113,7 @@ describe('models service', () => { settings: [{ key: 'temperature', value: 0.7 }], } - await updateModel(model as any) + await modelsService.updateModel(model as any) expect(mockEngine.updateSettings).toHaveBeenCalledWith(model.settings) }) @@ -131,7 +121,7 @@ describe('models service', () => { it('should handle model without settings', async () => { const model = { id: 'model1' } - await updateModel(model) + await modelsService.updateModel(model) expect(mockEngine.updateSettings).not.toHaveBeenCalled() }) @@ -142,7 +132,7 @@ describe('models service', () => { const id = 'model1' const modelPath = '/path/to/model' - await pullModel(id, modelPath) + await modelsService.pullModel(id, modelPath) expect(mockEngine.import).toHaveBeenCalledWith(id, { modelPath }) }) @@ -152,7 +142,7 @@ describe('models service', () => { it('should abort download successfully', async () => { const id = 'model1' - await abortDownload(id) + await modelsService.abortDownload(id) expect(mockEngine.abortImport).toHaveBeenCalledWith(id) }) @@ -162,7 +152,7 @@ describe('models service', () => { it('should delete model successfully', async () => { const id = 'model1' - await deleteModel(id) + await modelsService.deleteModel(id) expect(mockEngine.delete).toHaveBeenCalledWith(id) }) @@ -173,7 +163,7 @@ describe('models service', () => { const mockActiveModels = ['model1', 'model2'] mockEngine.getLoadedModels.mockResolvedValue(mockActiveModels) - const result = await getActiveModels() + const result = await modelsService.getActiveModels() expect(result).toEqual(mockActiveModels) expect(mockEngine.getLoadedModels).toHaveBeenCalled() @@ -185,7 +175,7 @@ describe('models service', () => { const model = 'model1' const provider = 'openai' - await stopModel(model, provider) + await modelsService.stopModel(model, provider) expect(mockEngine.unload).toHaveBeenCalledWith(model) }) @@ -196,7 +186,7 @@ describe('models service', () => { const mockActiveModels = ['model1', 'model2'] mockEngine.getLoadedModels.mockResolvedValue(mockActiveModels) - await stopAllModels() + await modelsService.stopAllModels() expect(mockEngine.unload).toHaveBeenCalledTimes(2) expect(mockEngine.unload).toHaveBeenCalledWith('model1') @@ -206,7 +196,7 @@ describe('models service', () => { it('should handle empty active models', async () => { mockEngine.getLoadedModels.mockResolvedValue(null) - await stopAllModels() + await modelsService.stopAllModels() expect(mockEngine.unload).not.toHaveBeenCalled() }) @@ -230,7 +220,7 @@ describe('models service', () => { }) mockEngine.load.mockResolvedValue(mockSession) - const result = await startModel(provider, model) + const result = await modelsService.startModel(provider, model) expect(result).toEqual(mockSession) expect(mockEngine.load).toHaveBeenCalledWith(model, { @@ -256,7 +246,7 @@ describe('models service', () => { }) mockEngine.load.mockRejectedValue(error) - await expect(startModel(provider, model)).rejects.toThrow(error) + await expect(modelsService.startModel(provider, model)).rejects.toThrow(error) }) it('should not load model again', async () => { const mockSettings = { @@ -273,7 +263,7 @@ describe('models service', () => { includes: () => true, }) expect(mockEngine.load).toBeCalledTimes(0) - await expect(startModel(provider, model)).resolves.toBe(undefined) + await expect(modelsService.startModel(provider, model)).resolves.toBe(undefined) }) }) @@ -322,7 +312,7 @@ describe('models service', () => { json: vi.fn().mockResolvedValue(mockRepoData), }) - const result = await fetchHuggingFaceRepo('microsoft/DialoGPT-medium') + const result = await modelsService.fetchHuggingFaceRepo('microsoft/DialoGPT-medium') expect(result).toEqual(mockRepoData) expect(fetch).toHaveBeenCalledWith( @@ -341,7 +331,7 @@ describe('models service', () => { }) // Test with full URL - await fetchHuggingFaceRepo( + await modelsService.fetchHuggingFaceRepo( 'https://huggingface.co/microsoft/DialoGPT-medium' ) expect(fetch).toHaveBeenCalledWith( @@ -352,7 +342,7 @@ describe('models service', () => { ) // Test with domain prefix - await fetchHuggingFaceRepo('huggingface.co/microsoft/DialoGPT-medium') + await modelsService.fetchHuggingFaceRepo('huggingface.co/microsoft/DialoGPT-medium') expect(fetch).toHaveBeenCalledWith( 'https://huggingface.co/api/models/microsoft/DialoGPT-medium?blobs=true&files_metadata=true', { @@ -361,7 +351,7 @@ describe('models service', () => { ) // Test with trailing slash - await fetchHuggingFaceRepo('microsoft/DialoGPT-medium/') + await modelsService.fetchHuggingFaceRepo('microsoft/DialoGPT-medium/') expect(fetch).toHaveBeenCalledWith( 'https://huggingface.co/api/models/microsoft/DialoGPT-medium?blobs=true&files_metadata=true', { @@ -372,13 +362,13 @@ describe('models service', () => { it('should return null for invalid repository IDs', async () => { // Test empty string - expect(await fetchHuggingFaceRepo('')).toBeNull() + expect(await modelsService.fetchHuggingFaceRepo('')).toBeNull() // Test string without slash - expect(await fetchHuggingFaceRepo('invalid-repo')).toBeNull() + expect(await modelsService.fetchHuggingFaceRepo('invalid-repo')).toBeNull() // Test whitespace only - expect(await fetchHuggingFaceRepo(' ')).toBeNull() + expect(await modelsService.fetchHuggingFaceRepo(' ')).toBeNull() }) it('should return null for 404 responses', async () => { @@ -388,7 +378,7 @@ describe('models service', () => { statusText: 'Not Found', }) - const result = await fetchHuggingFaceRepo('nonexistent/model') + const result = await modelsService.fetchHuggingFaceRepo('nonexistent/model') expect(result).toBeNull() expect(fetch).toHaveBeenCalledWith( @@ -408,7 +398,7 @@ describe('models service', () => { statusText: 'Internal Server Error', }) - const result = await fetchHuggingFaceRepo('microsoft/DialoGPT-medium') + const result = await modelsService.fetchHuggingFaceRepo('microsoft/DialoGPT-medium') expect(result).toBeNull() expect(consoleSpy).toHaveBeenCalledWith( @@ -424,7 +414,7 @@ describe('models service', () => { ;(fetch as any).mockRejectedValue(new Error('Network error')) - const result = await fetchHuggingFaceRepo('microsoft/DialoGPT-medium') + const result = await modelsService.fetchHuggingFaceRepo('microsoft/DialoGPT-medium') expect(result).toBeNull() expect(consoleSpy).toHaveBeenCalledWith( @@ -458,7 +448,7 @@ describe('models service', () => { json: vi.fn().mockResolvedValue(mockRepoData), }) - const result = await fetchHuggingFaceRepo('microsoft/DialoGPT-medium') + const result = await modelsService.fetchHuggingFaceRepo('microsoft/DialoGPT-medium') expect(result).toEqual(mockRepoData) }) @@ -497,7 +487,7 @@ describe('models service', () => { json: vi.fn().mockResolvedValue(mockRepoData), }) - const result = await fetchHuggingFaceRepo('microsoft/DialoGPT-medium') + const result = await modelsService.fetchHuggingFaceRepo('microsoft/DialoGPT-medium') expect(result).toEqual(mockRepoData) }) @@ -541,7 +531,7 @@ describe('models service', () => { json: vi.fn().mockResolvedValue(mockRepoData), }) - const result = await fetchHuggingFaceRepo('microsoft/DialoGPT-medium') + const result = await modelsService.fetchHuggingFaceRepo('microsoft/DialoGPT-medium') expect(result).toEqual(mockRepoData) // Verify the GGUF file is present in siblings @@ -586,7 +576,7 @@ describe('models service', () => { } it('should convert HuggingFace repo to catalog model format', () => { - const result = convertHfRepoToCatalogModel(mockHuggingFaceRepo) + const result = modelsService.convertHfRepoToCatalogModel(mockHuggingFaceRepo) const expected: CatalogModel = { model_name: 'microsoft/DialoGPT-medium', @@ -633,7 +623,7 @@ describe('models service', () => { ], } - const result = convertHfRepoToCatalogModel(repoWithoutGGUF) + const result = modelsService.convertHfRepoToCatalogModel(repoWithoutGGUF) expect(result.num_quants).toBe(0) expect(result.quants).toEqual([]) @@ -645,7 +635,7 @@ describe('models service', () => { siblings: undefined, } - const result = convertHfRepoToCatalogModel(repoWithoutSiblings) + const result = modelsService.convertHfRepoToCatalogModel(repoWithoutSiblings) expect(result.num_quants).toBe(0) expect(result.quants).toEqual([]) @@ -673,7 +663,7 @@ describe('models service', () => { ], } - const result = convertHfRepoToCatalogModel(repoWithVariousFileSizes) + const result = modelsService.convertHfRepoToCatalogModel(repoWithVariousFileSizes) expect(result.quants[0].file_size).toBe('500.0 MB') expect(result.quants[1].file_size).toBe('3.5 GB') @@ -686,7 +676,7 @@ describe('models service', () => { tags: [], } - const result = convertHfRepoToCatalogModel(repoWithEmptyTags) + const result = modelsService.convertHfRepoToCatalogModel(repoWithEmptyTags) expect(result.description).toBe('**Tags**: ') }) @@ -697,7 +687,7 @@ describe('models service', () => { downloads: undefined as any, } - const result = convertHfRepoToCatalogModel(repoWithoutDownloads) + const result = modelsService.convertHfRepoToCatalogModel(repoWithoutDownloads) expect(result.downloads).toBe(0) }) @@ -724,7 +714,7 @@ describe('models service', () => { ], } - const result = convertHfRepoToCatalogModel(repoWithVariousGGUF) + const result = modelsService.convertHfRepoToCatalogModel(repoWithVariousGGUF) expect(result.quants[0].model_id).toBe('model') expect(result.quants[1].model_id).toBe('MODEL') @@ -732,7 +722,7 @@ describe('models service', () => { }) it('should generate correct download paths', () => { - const result = convertHfRepoToCatalogModel(mockHuggingFaceRepo) + const result = modelsService.convertHfRepoToCatalogModel(mockHuggingFaceRepo) expect(result.quants[0].path).toBe( 'https://huggingface.co/microsoft/DialoGPT-medium/resolve/main/model-q4_0.gguf' @@ -743,7 +733,7 @@ describe('models service', () => { }) it('should generate correct readme URL', () => { - const result = convertHfRepoToCatalogModel(mockHuggingFaceRepo) + const result = modelsService.convertHfRepoToCatalogModel(mockHuggingFaceRepo) expect(result.readme).toBe( 'https://huggingface.co/microsoft/DialoGPT-medium/resolve/main/README.md' @@ -777,7 +767,7 @@ describe('models service', () => { ], } - const result = convertHfRepoToCatalogModel(repoWithMixedCase) + const result = modelsService.convertHfRepoToCatalogModel(repoWithMixedCase) expect(result.num_quants).toBe(3) expect(result.quants).toHaveLength(3) @@ -808,7 +798,7 @@ describe('models service', () => { ], } - const result = convertHfRepoToCatalogModel(repoWithEdgeCases) + const result = modelsService.convertHfRepoToCatalogModel(repoWithEdgeCases) expect(result.quants[0].file_size).toBe('0.0 MB') expect(result.quants[1].file_size).toBe('1.0 GB') @@ -837,7 +827,7 @@ describe('models service', () => { ], } - const result = convertHfRepoToCatalogModel(minimalRepo) + const result = modelsService.convertHfRepoToCatalogModel(minimalRepo) expect(result.model_name).toBe('minimal/repo') expect(result.developer).toBe('minimal') @@ -860,7 +850,7 @@ describe('models service', () => { mockEngineManager.get.mockReturnValue(mockEngineWithSupport) - const result = await isModelSupported('/path/to/model.gguf', 4096) + const result = await modelsService.isModelSupported('/path/to/model.gguf', 4096) expect(result).toBe('GREEN') expect(mockEngineWithSupport.isModelSupported).toHaveBeenCalledWith( @@ -877,7 +867,7 @@ describe('models service', () => { mockEngineManager.get.mockReturnValue(mockEngineWithSupport) - const result = await isModelSupported('/path/to/model.gguf', 8192) + const result = await modelsService.isModelSupported('/path/to/model.gguf', 8192) expect(result).toBe('YELLOW') expect(mockEngineWithSupport.isModelSupported).toHaveBeenCalledWith( @@ -894,7 +884,7 @@ describe('models service', () => { mockEngineManager.get.mockReturnValue(mockEngineWithSupport) - const result = await isModelSupported('/path/to/large-model.gguf') + const result = await modelsService.isModelSupported('/path/to/large-model.gguf') expect(result).toBe('RED') expect(mockEngineWithSupport.isModelSupported).toHaveBeenCalledWith( @@ -906,12 +896,12 @@ describe('models service', () => { it('should return YELLOW as fallback when engine method is not available', async () => { const mockEngineWithoutSupport = { ...mockEngine, - // isModelSupported method not available + isModelSupported: undefined, // Explicitly remove the method } mockEngineManager.get.mockReturnValue(mockEngineWithoutSupport) - const result = await isModelSupported('/path/to/model.gguf') + const result = await modelsService.isModelSupported('/path/to/model.gguf') expect(result).toBe('YELLOW') }) @@ -919,12 +909,12 @@ describe('models service', () => { it('should return RED when engine is not available', async () => { mockEngineManager.get.mockReturnValue(null) - const result = await isModelSupported('/path/to/model.gguf') + const result = await modelsService.isModelSupported('/path/to/model.gguf') expect(result).toBe('YELLOW') // Should use fallback }) - it('should return RED when there is an error', async () => { + it('should return GREY when there is an error', async () => { const mockEngineWithError = { ...mockEngine, isModelSupported: vi.fn().mockRejectedValue(new Error('Test error')), @@ -932,9 +922,9 @@ describe('models service', () => { mockEngineManager.get.mockReturnValue(mockEngineWithError) - const result = await isModelSupported('/path/to/model.gguf') + const result = await modelsService.isModelSupported('/path/to/model.gguf') - expect(result).toBe('RED') + expect(result).toBe('GREY') }) }) }) diff --git a/web-app/src/services/__tests__/providers.test.ts b/web-app/src/services/__tests__/providers.test.ts index c7b041cd5..ed447dba7 100644 --- a/web-app/src/services/__tests__/providers.test.ts +++ b/web-app/src/services/__tests__/providers.test.ts @@ -1,15 +1,9 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { - getProviders, - fetchModelsFromProvider, - updateSettings, -} from '../providers' +import { WebProvidersService } from '../providers/web' import { models as providerModels } from 'token.js' import { predefinedProviders } from '@/consts/providers' import { EngineManager } from '@janhq/core' -import { fetchModels } from '../models' import { ExtensionManager } from '@/lib/extension' -import { fetch as fetchTauri } from '@tauri-apps/plugin-http' // Mock dependencies vi.mock('token.js', () => ({ @@ -45,6 +39,12 @@ vi.mock('@janhq/core', () => ({ 'llamacpp', { inferenceUrl: 'http://localhost:1337/chat/completions', + list: vi.fn(() => + Promise.resolve([ + { id: 'llama-2-7b', name: 'Llama 2 7B', description: 'Llama model' } + ]) + ), + isToolSupported: vi.fn(() => Promise.resolve(false)), getSettings: vi.fn(() => Promise.resolve([ { @@ -63,15 +63,6 @@ vi.mock('@janhq/core', () => ({ }, })) -vi.mock('../models', () => ({ - fetchModels: vi.fn(() => - Promise.resolve([ - { id: 'llama-2-7b', name: 'Llama 2 7B', description: 'Llama model' }, - ]) - ), - isToolSupported: vi.fn(() => Promise.resolve(false)), -})) - vi.mock('@/lib/extension', () => ({ ExtensionManager: { getInstance: vi.fn(() => ({ @@ -80,9 +71,8 @@ vi.mock('@/lib/extension', () => ({ }, })) -vi.mock('@tauri-apps/plugin-http', () => ({ - fetch: vi.fn(), -})) +// Mock global fetch +global.fetch = vi.fn() vi.mock('@/types/models', () => ({ ModelCapabilities: { @@ -108,14 +98,17 @@ vi.mock('@/lib/predefined', () => ({ }, })) -describe('providers service', () => { +describe('WebProvidersService', () => { + let providersService: WebProvidersService + beforeEach(() => { + providersService = new WebProvidersService() vi.clearAllMocks() }) describe('getProviders', () => { it('should return builtin and runtime providers', async () => { - const providers = await getProviders() + const providers = await providersService.getProviders() expect(providers).toHaveLength(2) // 1 runtime + 1 builtin (mocked) expect(providers.some((p) => p.provider === 'llamacpp')).toBe(true) @@ -123,7 +116,7 @@ describe('providers service', () => { }) it('should map builtin provider models correctly', async () => { - const providers = await getProviders() + const providers = await providersService.getProviders() const openaiProvider = providers.find((p) => p.provider === 'openai') expect(openaiProvider).toBeDefined() @@ -133,7 +126,7 @@ describe('providers service', () => { }) it('should create runtime providers from engine manager', async () => { - const providers = await getProviders() + const providers = await providersService.getProviders() const llamacppProvider = providers.find((p) => p.provider === 'llamacpp') expect(llamacppProvider).toBeDefined() @@ -151,7 +144,7 @@ describe('providers service', () => { data: [{ id: 'gpt-3.5-turbo' }, { id: 'gpt-4' }], }), } - vi.mocked(fetchTauri).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) const provider = { provider: 'openai', @@ -159,9 +152,9 @@ describe('providers service', () => { api_key: 'test-key', } - const models = await fetchModelsFromProvider(provider) + const models = await providersService.fetchModelsFromProvider(provider) - expect(fetchTauri).toHaveBeenCalledWith( + expect(global.fetch).toHaveBeenCalledWith( 'https://api.openai.com/v1/models', { method: 'GET', @@ -180,7 +173,7 @@ describe('providers service', () => { ok: true, json: vi.fn().mockResolvedValue(['model1', 'model2']), } - vi.mocked(fetchTauri).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) const provider = { provider: 'custom', @@ -188,7 +181,7 @@ describe('providers service', () => { api_key: '', } - const models = await fetchModelsFromProvider(provider) + const models = await providersService.fetchModelsFromProvider(provider) expect(models).toEqual(['model1', 'model2']) }) @@ -200,14 +193,14 @@ describe('providers service', () => { models: [{ id: 'model1' }, 'model2'], }), } - vi.mocked(fetchTauri).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) const provider = { provider: 'custom', base_url: 'https://api.custom.com', } - const models = await fetchModelsFromProvider(provider) + const models = await providersService.fetchModelsFromProvider(provider) expect(models).toEqual(['model1', 'model2']) }) @@ -217,7 +210,7 @@ describe('providers service', () => { provider: 'custom', } - await expect(fetchModelsFromProvider(provider)).rejects.toThrow( + await expect(providersService.fetchModelsFromProvider(provider)).rejects.toThrow( 'Provider must have base_url configured' ) }) @@ -228,14 +221,14 @@ describe('providers service', () => { status: 404, statusText: 'Not Found', } - vi.mocked(fetchTauri).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) const provider = { provider: 'custom', base_url: 'https://api.custom.com', } - await expect(fetchModelsFromProvider(provider)).rejects.toThrow( + await expect(providersService.fetchModelsFromProvider(provider)).rejects.toThrow( 'Models endpoint not found for custom. Check the base URL configuration.' ) }) @@ -246,14 +239,14 @@ describe('providers service', () => { status: 403, statusText: 'Forbidden', } - vi.mocked(fetchTauri).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) const provider = { provider: 'custom', base_url: 'https://api.custom.com', } as ModelProvider - await expect(fetchModelsFromProvider(provider)).rejects.toThrow( + await expect(providersService.fetchModelsFromProvider(provider)).rejects.toThrow( 'Access forbidden: Check your API key permissions for custom' ) }) @@ -264,27 +257,27 @@ describe('providers service', () => { status: 401, statusText: 'Unauthorized', } - vi.mocked(fetchTauri).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) const provider = { provider: 'custom', base_url: 'https://api.custom.com', } as ModelProvider - await expect(fetchModelsFromProvider(provider)).rejects.toThrow( + await expect(providersService.fetchModelsFromProvider(provider)).rejects.toThrow( 'Authentication failed: API key is required or invalid for custom' ) }) it('should handle network errors gracefully', async () => { - vi.mocked(fetchTauri).mockRejectedValue(new Error('fetch failed')) + vi.mocked(global.fetch).mockRejectedValue(new Error('fetch failed')) const provider = { provider: 'custom', base_url: 'https://api.custom.com', } - await expect(fetchModelsFromProvider(provider)).rejects.toThrow( + await expect(providersService.fetchModelsFromProvider(provider)).rejects.toThrow( 'Cannot connect to custom at https://api.custom.com. Please check that the service is running and accessible.' ) }) @@ -294,7 +287,7 @@ describe('providers service', () => { ok: true, json: vi.fn().mockResolvedValue({ unexpected: 'format' }), } - vi.mocked(fetchTauri).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -303,7 +296,7 @@ describe('providers service', () => { base_url: 'https://api.custom.com', } - const models = await fetchModelsFromProvider(provider) + const models = await providersService.fetchModelsFromProvider(provider) expect(models).toEqual([]) expect(consoleSpy).toHaveBeenCalledWith( @@ -337,7 +330,7 @@ describe('providers service', () => { }, ] - await updateSettings('openai', settings) + await providersService.updateSettings('openai', settings) expect(mockExtensionManager.getEngine).toHaveBeenCalledWith('openai') expect(mockEngine.updateSettings).toHaveBeenCalledWith([ @@ -363,7 +356,7 @@ describe('providers service', () => { const settings = [] - const result = await updateSettings('nonexistent', settings) + const result = await providersService.updateSettings('nonexistent', settings) expect(result).toBeUndefined() }) @@ -389,7 +382,7 @@ describe('providers service', () => { }, ] - await updateSettings('openai', settings) + await providersService.updateSettings('openai', settings) expect(mockEngine.updateSettings).toHaveBeenCalledWith([ { diff --git a/web-app/src/services/__tests__/serviceHub.integration.test.ts b/web-app/src/services/__tests__/serviceHub.integration.test.ts new file mode 100644 index 000000000..5af5ee99e --- /dev/null +++ b/web-app/src/services/__tests__/serviceHub.integration.test.ts @@ -0,0 +1,91 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { initializeServiceHub, type ServiceHub } from '../index' +import { isPlatformTauri } from '@/lib/platform/utils' + +// Mock platform detection +vi.mock('@/lib/platform/utils', () => ({ + isPlatformTauri: vi.fn().mockReturnValue(false) +})) + +// Mock @jan/extensions-web to return empty extensions for testing +vi.mock('@jan/extensions-web', () => ({ + WEB_EXTENSIONS: {} +})) + +// Mock console to avoid noise in tests +vi.spyOn(console, 'log').mockImplementation(() => {}) +vi.spyOn(console, 'error').mockImplementation(() => {}) + +describe('ServiceHub Integration Tests', () => { + let serviceHub: ServiceHub + + beforeEach(async () => { + vi.clearAllMocks() + serviceHub = await initializeServiceHub() + }) + + describe('ServiceHub Initialization', () => { + it('should initialize with web services when not on Tauri', async () => { + vi.mocked(isPlatformTauri).mockReturnValue(false) + + serviceHub = await initializeServiceHub() + + expect(serviceHub).toBeDefined() + expect(console.log).toHaveBeenCalledWith( + 'Initializing service hub for platform:', + 'Web' + ) + }) + + it('should initialize with Tauri services when on Tauri', async () => { + vi.mocked(isPlatformTauri).mockReturnValue(true) + + serviceHub = await initializeServiceHub() + + expect(serviceHub).toBeDefined() + expect(console.log).toHaveBeenCalledWith( + 'Initializing service hub for platform:', + 'Tauri' + ) + }) + }) + + describe('Service Access', () => { + it('should provide access to all required services', () => { + const services = [ + 'theme', 'window', 'events', 'hardware', 'app', 'analytic', + 'messages', 'mcp', 'threads', 'providers', 'models', 'assistants', + 'dialog', 'opener', 'updater', 'path', 'core', 'deeplink' + ] + + services.forEach(serviceName => { + expect(typeof serviceHub[serviceName as keyof ServiceHub]).toBe('function') + expect(serviceHub[serviceName as keyof ServiceHub]()).toBeDefined() + }) + }) + + it('should return same service instance on multiple calls', () => { + const themeService1 = serviceHub.theme() + const themeService2 = serviceHub.theme() + + expect(themeService1).toBe(themeService2) + }) + }) + + describe('Basic Service Functionality', () => { + it('should have working theme service', () => { + const theme = serviceHub.theme() + + expect(typeof theme.setTheme).toBe('function') + expect(typeof theme.getCurrentWindow).toBe('function') + }) + + it('should have working events service', () => { + const events = serviceHub.events() + + expect(typeof events.emit).toBe('function') + expect(typeof events.listen).toBe('function') + }) + + }) +}) \ No newline at end of file diff --git a/web-app/src/services/__tests__/threads.test.ts b/web-app/src/services/__tests__/threads.test.ts index 9be1e9ae8..86bd7cb83 100644 --- a/web-app/src/services/__tests__/threads.test.ts +++ b/web-app/src/services/__tests__/threads.test.ts @@ -1,10 +1,5 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { - fetchThreads, - createThread, - updateThread, - deleteThread, -} from '../threads' +import { DefaultThreadsService } from '../threads/default' import { ExtensionManager } from '@/lib/extension' import { ConversationalExtension, ExtensionTypeEnum } from '@janhq/core' import { defaultAssistant } from '@/hooks/useAssistant' @@ -24,7 +19,9 @@ vi.mock('@/hooks/useAssistant', () => ({ }, })) -describe('threads service', () => { +describe('DefaultThreadsService', () => { + let threadsService: DefaultThreadsService + const mockConversationalExtension = { listThreads: vi.fn(), createThread: vi.fn(), @@ -37,6 +34,7 @@ describe('threads service', () => { } beforeEach(() => { + threadsService = new DefaultThreadsService() vi.clearAllMocks() ;(ExtensionManager.getInstance as any).mockReturnValue(mockExtensionManager) }) @@ -55,7 +53,7 @@ describe('threads service', () => { mockConversationalExtension.listThreads.mockResolvedValue(mockThreads) - const result = await fetchThreads() + const result = await threadsService.fetchThreads() expect(result).toHaveLength(1) expect(result[0]).toMatchObject({ @@ -89,7 +87,7 @@ describe('threads service', () => { mockConversationalExtension.listThreads.mockResolvedValue(mockThreads) - const result = await fetchThreads() + const result = await threadsService.fetchThreads() expect(result).toHaveLength(2) expect(result[0]).toMatchObject({ @@ -115,7 +113,7 @@ describe('threads service', () => { it('should handle empty threads array', async () => { mockConversationalExtension.listThreads.mockResolvedValue([]) - const result = await fetchThreads() + const result = await threadsService.fetchThreads() expect(result).toEqual([]) }) @@ -125,7 +123,7 @@ describe('threads service', () => { new Error('API Error') ) - const result = await fetchThreads() + const result = await threadsService.fetchThreads() expect(result).toEqual([]) }) @@ -133,7 +131,7 @@ describe('threads service', () => { it('should handle null/undefined response', async () => { mockConversationalExtension.listThreads.mockResolvedValue(null) - const result = await fetchThreads() + const result = await threadsService.fetchThreads() expect(result).toEqual([]) }) @@ -161,7 +159,7 @@ describe('threads service', () => { mockCreatedThread ) - const result = await createThread(inputThread as Thread) + const result = await threadsService.createThread(inputThread as Thread) expect(result).toMatchObject({ id: '1', @@ -184,7 +182,7 @@ describe('threads service', () => { new Error('Creation failed') ) - const result = await createThread(inputThread as Thread) + const result = await threadsService.createThread(inputThread as Thread) expect(result).toEqual(inputThread) }) @@ -201,7 +199,7 @@ describe('threads service', () => { order: 2, } - const result = updateThread(thread as Thread) + const result = threadsService.updateThread(thread as Thread) expect(mockConversationalExtension.modifyThread).toHaveBeenCalledWith( expect.objectContaining({ @@ -222,7 +220,7 @@ describe('threads service', () => { it('should delete thread successfully', () => { const threadId = '1' - deleteThread(threadId) + threadsService.deleteThread(threadId) expect(mockConversationalExtension.deleteThread).toHaveBeenCalledWith( threadId @@ -236,7 +234,7 @@ describe('threads service', () => { get: vi.fn().mockReturnValue(null), }) - const result = await fetchThreads() + const result = await threadsService.fetchThreads() expect(result).toEqual([]) }) @@ -252,12 +250,12 @@ describe('threads service', () => { model: { id: 'gpt-4', provider: 'openai' }, } - const result = await createThread(inputThread as Thread) + const result = await threadsService.createThread(inputThread as Thread) expect(result).toEqual(inputThread) }) - it('should handle updateThread when extension manager returns null', () => { + it('should handle updateThread when extension manager returns null', async () => { ;(ExtensionManager.getInstance as any).mockReturnValue({ get: vi.fn().mockReturnValue(null), }) @@ -268,17 +266,17 @@ describe('threads service', () => { model: { id: 'gpt-4', provider: 'openai' }, } - const result = updateThread(thread as Thread) + const result = await threadsService.updateThread(thread as Thread) expect(result).toBeUndefined() }) - it('should handle deleteThread when extension manager returns null', () => { + it('should handle deleteThread when extension manager returns null', async () => { ;(ExtensionManager.getInstance as any).mockReturnValue({ get: vi.fn().mockReturnValue(null), }) - const result = deleteThread('test-id') + const result = await threadsService.deleteThread('test-id') expect(result).toBeUndefined() }) @@ -294,7 +292,7 @@ describe('threads service', () => { mockConversationalExtension.listThreads.mockResolvedValue(mockThreads) - const result = await fetchThreads() + const result = await threadsService.fetchThreads() expect(result).toHaveLength(1) expect(result[0]).toMatchObject({ @@ -320,7 +318,7 @@ describe('threads service', () => { mockConversationalExtension.listThreads.mockResolvedValue(mockThreads) - const result = await fetchThreads() + const result = await threadsService.fetchThreads() expect(result).toHaveLength(1) expect(result[0]).toMatchObject({ @@ -354,7 +352,7 @@ describe('threads service', () => { mockCreatedThread ) - const result = await createThread(inputThread as Thread) + const result = await threadsService.createThread(inputThread as Thread) expect(mockConversationalExtension.createThread).toHaveBeenCalledWith( expect.objectContaining({ @@ -388,7 +386,7 @@ describe('threads service', () => { mockCreatedThread ) - const result = await createThread(inputThread as Thread) + const result = await threadsService.createThread(inputThread as Thread) expect(mockConversationalExtension.createThread).toHaveBeenCalledWith( expect.objectContaining({ @@ -412,7 +410,7 @@ describe('threads service', () => { order: 2, } - updateThread(thread as Thread) + threadsService.updateThread(thread as Thread) expect(mockConversationalExtension.modifyThread).toHaveBeenCalledWith( expect.objectContaining({ @@ -437,7 +435,7 @@ describe('threads service', () => { order: 2, } - updateThread(thread as Thread) + threadsService.updateThread(thread as Thread) expect(mockConversationalExtension.modifyThread).toHaveBeenCalledWith( expect.objectContaining({ @@ -453,7 +451,7 @@ describe('threads service', () => { it('should handle fetchThreads with non-array response', async () => { mockConversationalExtension.listThreads.mockResolvedValue('not-an-array') - const result = await fetchThreads() + const result = await threadsService.fetchThreads() expect(result).toEqual([]) }) @@ -478,7 +476,7 @@ describe('threads service', () => { mockCreatedThread ) - const result = await createThread(inputThread as Thread) + const result = await threadsService.createThread(inputThread as Thread) expect(result).toMatchObject({ id: '1', diff --git a/web-app/src/services/__tests__/web-specific.test.ts b/web-app/src/services/__tests__/web-specific.test.ts new file mode 100644 index 000000000..b0f5e1dc3 --- /dev/null +++ b/web-app/src/services/__tests__/web-specific.test.ts @@ -0,0 +1,83 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +describe('Web-Specific Service Tests', () => { + beforeEach(() => { + vi.clearAllMocks() + global.fetch = vi.fn() + }) + + describe('WebThemeService', () => { + it('should set theme by modifying DOM attributes', async () => { + const { WebThemeService } = await import('../theme/web') + + // Mock document.documentElement + const mockSetAttribute = vi.fn() + const mockRemoveAttribute = vi.fn() + Object.defineProperty(document, 'documentElement', { + value: { + setAttribute: mockSetAttribute, + removeAttribute: mockRemoveAttribute + } + }) + + const service = new WebThemeService() + await service.setTheme('dark') + + expect(mockSetAttribute).toHaveBeenCalledWith('data-theme', 'dark') + + await service.setTheme(null) + expect(mockRemoveAttribute).toHaveBeenCalledWith('data-theme') + }) + + it('should provide getCurrentWindow method', async () => { + const { WebThemeService } = await import('../theme/web') + const service = new WebThemeService() + + const currentWindow = service.getCurrentWindow() + expect(typeof currentWindow.setTheme).toBe('function') + }) + }) + + describe('WebProvidersService', () => { + it('should use browser fetch for API calls', async () => { + const { WebProvidersService } = await import('../providers/web') + const mockResponse = { + ok: true, + json: vi.fn().mockResolvedValue({ data: [{ id: 'gpt-4' }] }) + } + vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + + const service = new WebProvidersService() + const provider = { + provider: 'openai', + base_url: 'https://api.openai.com/v1', + api_key: 'test-key' + } + + const models = await service.fetchModelsFromProvider(provider) + + expect(global.fetch).toHaveBeenCalledWith( + 'https://api.openai.com/v1/models', + expect.objectContaining({ + method: 'GET', + headers: expect.objectContaining({ + 'Content-Type': 'application/json' + }) + }) + ) + expect(models).toEqual(['gpt-4']) + }) + }) + + describe('WebAppService', () => { + it('should handle web-specific app operations', async () => { + const { WebAppService } = await import('../app/web') + + const service = new WebAppService() + + // Test basic service methods exist + expect(typeof service.getJanDataFolder).toBe('function') + expect(typeof service.factoryReset).toBe('function') + }) + }) +}) \ No newline at end of file diff --git a/web-app/src/services/analytic.ts b/web-app/src/services/analytic.ts deleted file mode 100644 index aaf568f52..000000000 --- a/web-app/src/services/analytic.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { AppConfiguration } from '@janhq/core' - -/** - * Update app distinct Id - * @param id - */ -export const updateDistinctId = async (id: string) => { - const appConfiguration: AppConfiguration = - await window.core?.api?.getAppConfigurations() - appConfiguration.distinct_id = id - await window.core?.api?.updateAppConfiguration({ - configuration: appConfiguration, - }) -} - -/** - * Retrieve app distinct Id - * @param id - */ -export const getAppDistinctId = async (): Promise => { - const appConfiguration: AppConfiguration = - await window.core?.api?.getAppConfigurations() - return appConfiguration.distinct_id -} diff --git a/web-app/src/services/analytic/default.ts b/web-app/src/services/analytic/default.ts new file mode 100644 index 000000000..eff3a14c3 --- /dev/null +++ b/web-app/src/services/analytic/default.ts @@ -0,0 +1,23 @@ +/** + * Default Analytic Service - Web implementation + */ + +import { AppConfiguration } from '@janhq/core' +import type { AnalyticService } from './types' + +export class DefaultAnalyticService implements AnalyticService { + async updateDistinctId(id: string): Promise { + const appConfiguration: AppConfiguration = + await window.core?.api?.getAppConfigurations() + appConfiguration.distinct_id = id + await window.core?.api?.updateAppConfiguration({ + configuration: appConfiguration, + }) + } + + async getAppDistinctId(): Promise { + const appConfiguration: AppConfiguration = + await window.core?.api?.getAppConfigurations() + return appConfiguration.distinct_id + } +} \ No newline at end of file diff --git a/web-app/src/services/analytic/types.ts b/web-app/src/services/analytic/types.ts new file mode 100644 index 000000000..e54e74424 --- /dev/null +++ b/web-app/src/services/analytic/types.ts @@ -0,0 +1,8 @@ +/** + * Analytic Service Types + */ + +export interface AnalyticService { + updateDistinctId(id: string): Promise + getAppDistinctId(): Promise +} \ No newline at end of file diff --git a/web-app/src/services/app.ts b/web-app/src/services/app.ts deleted file mode 100644 index c13e018b7..000000000 --- a/web-app/src/services/app.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { AppConfiguration } from '@janhq/core' -import { invoke } from '@tauri-apps/api/core' -import { stopAllModels } from './models' - -/** - * @description This function is used to reset the app to its factory settings. - * It will remove all the data from the app, including the data folder and local storage. - * @returns {Promise} - */ -export const factoryReset = async () => { - // Kill background processes and remove data folder - await stopAllModels() - window.localStorage.clear() - await invoke('factory_reset') -} - -/** - * @description This function is used to read the logs from the app. - * It will return the logs as a string. - * @returns - */ -export const readLogs = async () => { - const logData: string = (await invoke('read_logs')) ?? '' - return logData.split('\n').map(parseLogLine) -} - -/** - * @description This function is used to parse a log line. - * It will return the log line as an object. - * @param line - * @returns - */ -export const parseLogLine = (line: string) => { - const regex = /^\[(.*?)\]\[(.*?)\]\[(.*?)\]\[(.*?)\]\s(.*)$/ - const match = line.match(regex) - - if (!match) - return { - timestamp: Date.now(), - level: 'info' as 'info' | 'warn' | 'error' | 'debug', - target: 'info', - message: line ?? '', - } as LogEntry - - const [, date, time, target, levelRaw, message] = match - - const level = levelRaw.toLowerCase() as 'info' | 'warn' | 'error' | 'debug' - - return { - timestamp: `${date} ${time}`, - level, - target, - message, - } -} - -/** - * @description This function is used to get the Jan data folder path. - * It retrieves the path from the app configuration. - * @returns {Promise} The Jan data folder path or undefined if not found - */ -export const getJanDataFolder = async (): Promise => { - try { - const appConfiguration: AppConfiguration | undefined = - await window.core?.api?.getAppConfigurations() - - return appConfiguration?.data_folder - } catch (error) { - console.error('Failed to get Jan data folder:', error) - return undefined - } -} - -/** - * @description This function is used to relocate the Jan data folder. - * It will change the app data folder to the specified path. - * @param path The new path for the Jan data folder - */ -export const relocateJanDataFolder = async (path: string) => { - await window.core?.api?.changeAppDataFolder({ newDataFolder: path }) -} diff --git a/web-app/src/services/app/default.ts b/web-app/src/services/app/default.ts new file mode 100644 index 000000000..9e54c6791 --- /dev/null +++ b/web-app/src/services/app/default.ts @@ -0,0 +1,42 @@ +/** + * Default App Service - Generic implementation with minimal returns + */ + +import type { AppService, LogEntry } from './types' + +export class DefaultAppService implements AppService { + async factoryReset(): Promise { + // No-op + } + + async readLogs(): Promise { + return [] + } + + parseLogLine(line: string): LogEntry { + return { + timestamp: Date.now(), + level: 'info', + target: 'default', + message: line ?? '', + } + } + + async getJanDataFolder(): Promise { + return undefined + } + + async relocateJanDataFolder(path: string): Promise { + console.log('relocateJanDataFolder called with path:', path) + // No-op - not implemented in default service + } + + async getServerStatus(): Promise { + return false + } + + async readYaml(path: string): Promise { + console.log('readYaml called with path:', path) + throw new Error('readYaml not implemented in default app service') + } +} \ No newline at end of file diff --git a/web-app/src/services/app/tauri.ts b/web-app/src/services/app/tauri.ts new file mode 100644 index 000000000..b59a9f676 --- /dev/null +++ b/web-app/src/services/app/tauri.ts @@ -0,0 +1,78 @@ +/** + * Tauri App Service - Desktop implementation + */ + +import { invoke } from '@tauri-apps/api/core' +import { AppConfiguration } from '@janhq/core' +import type { LogEntry } from './types' +import { DefaultAppService } from './default' + +export class TauriAppService extends DefaultAppService { + async factoryReset(): Promise { + // Kill background processes and remove data folder + // Note: We can't import stopAllModels directly to avoid circular dependency + // Instead we'll use the engine manager directly + const { EngineManager } = await import('@janhq/core') + for (const [, engine] of EngineManager.instance().engines) { + const activeModels = await engine.getLoadedModels() + if (activeModels) { + await Promise.all(activeModels.map((model: string) => engine.unload(model))) + } + } + window.localStorage.clear() + await invoke('factory_reset') + } + + async readLogs(): Promise { + const logData: string = (await invoke('read_logs')) ?? '' + return logData.split('\n').map(this.parseLogLine) + } + + async getJanDataFolder(): Promise { + try { + const appConfiguration: AppConfiguration | undefined = + await window.core?.api?.getAppConfigurations() + + return appConfiguration?.data_folder + } catch (error) { + console.error('Failed to get Jan data folder:', error) + return undefined + } + } + + async relocateJanDataFolder(path: string): Promise { + await window.core?.api?.changeAppDataFolder({ newDataFolder: path }) + } + + parseLogLine(line: string): LogEntry { + const regex = /^\[(.*?)\]\[(.*?)\]\[(.*?)\]\[(.*?)\]\s(.*)$/ + const match = line.match(regex) + + if (!match) + return { + timestamp: Date.now(), + level: 'info' as 'info' | 'warn' | 'error' | 'debug', + target: 'info', + message: line ?? '', + } as LogEntry + + const [, date, time, target, levelRaw, message] = match + + const level = levelRaw.toLowerCase() as 'info' | 'warn' | 'error' | 'debug' + + return { + timestamp: `${date} ${time}`, + level, + target, + message, + } + } + + async getServerStatus(): Promise { + return await invoke('get_server_status') + } + + async readYaml(path: string): Promise { + return await invoke('read_yaml', { path }) + } +} \ No newline at end of file diff --git a/web-app/src/services/app/types.ts b/web-app/src/services/app/types.ts new file mode 100644 index 000000000..9b0c25b7e --- /dev/null +++ b/web-app/src/services/app/types.ts @@ -0,0 +1,20 @@ +/** + * App Service Types + */ + +export interface LogEntry { + timestamp: string | number + level: 'info' | 'warn' | 'error' | 'debug' + target: string + message: string +} + +export interface AppService { + factoryReset(): Promise + readLogs(): Promise + parseLogLine(line: string): LogEntry + getJanDataFolder(): Promise + relocateJanDataFolder(path: string): Promise + getServerStatus(): Promise + readYaml(path: string): Promise +} \ No newline at end of file diff --git a/web-app/src/services/app/web.ts b/web-app/src/services/app/web.ts new file mode 100644 index 000000000..06ba65080 --- /dev/null +++ b/web-app/src/services/app/web.ts @@ -0,0 +1,48 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +/** + * Web App Service - Web implementation + */ + +import type { AppService, LogEntry } from './types' + +export class WebAppService implements AppService { + async factoryReset(): Promise { + console.log('Factory reset in web mode - clearing localStorage') + window.localStorage.clear() + window.location.reload() + } + + async readLogs(): Promise { + console.log('Logs not available in web mode') + return [] + } + + parseLogLine(line: string): LogEntry { + // Simple fallback implementation for web mode + return { + timestamp: Date.now(), + level: 'info' as 'info' | 'warn' | 'error' | 'debug', + target: 'web', + message: line ?? '', + } + } + + async getJanDataFolder(): Promise { + console.log('Data folder path not available in web mode') + return undefined + } + + async relocateJanDataFolder(_path: string): Promise { + console.log('Data folder relocation not available in web mode') + } + + async getServerStatus(): Promise { + console.log('Server status not available in web mode') + return false + } + + async readYaml(_path: string): Promise { + console.log('YAML reading not available in web mode') + throw new Error('readYaml not implemented in web app service') + } +} \ No newline at end of file diff --git a/web-app/src/services/assistants.ts b/web-app/src/services/assistants.ts deleted file mode 100644 index 2f6414783..000000000 --- a/web-app/src/services/assistants.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { ExtensionManager } from '@/lib/extension' -import { Assistant, AssistantExtension, ExtensionTypeEnum } from '@janhq/core' - -/** - * Fetches all available assistants. - * @returns A promise that resolves to the assistants. - */ -export const getAssistants = async () => { - const extension = ExtensionManager.getInstance().get( - ExtensionTypeEnum.Assistant - ) - - if (!extension) { - console.warn('AssistantExtension not found') - return null - } - - return extension.getAssistants() -} - -/** - * Creates a new assistant. - * @param assistant The assistant to create. - */ -export const createAssistant = async (assistant: Assistant) => { - return ExtensionManager.getInstance() - .get(ExtensionTypeEnum.Assistant) - ?.createAssistant(assistant) -} -/** - * Deletes an existing assistant. - * @param assistant The assistant to delete. - * @return A promise that resolves when the assistant is deleted. - */ -export const deleteAssistant = async (assistant: Assistant) => { - return ExtensionManager.getInstance() - .get(ExtensionTypeEnum.Assistant) - ?.deleteAssistant(assistant) -} diff --git a/web-app/src/services/assistants/default.ts b/web-app/src/services/assistants/default.ts new file mode 100644 index 000000000..65d3cc58f --- /dev/null +++ b/web-app/src/services/assistants/default.ts @@ -0,0 +1,34 @@ +/** + * Default Assistants Service - Web implementation + */ + +import { ExtensionManager } from '@/lib/extension' +import { Assistant, AssistantExtension, ExtensionTypeEnum } from '@janhq/core' +import type { AssistantsService } from './types' + +export class DefaultAssistantsService implements AssistantsService { + async getAssistants(): Promise { + const extension = ExtensionManager.getInstance().get( + ExtensionTypeEnum.Assistant + ) + + if (!extension) { + console.warn('AssistantExtension not found') + return null + } + + return extension.getAssistants() + } + + async createAssistant(assistant: Assistant): Promise { + await ExtensionManager.getInstance() + .get(ExtensionTypeEnum.Assistant) + ?.createAssistant(assistant) + } + + async deleteAssistant(assistant: Assistant): Promise { + await ExtensionManager.getInstance() + .get(ExtensionTypeEnum.Assistant) + ?.deleteAssistant(assistant) + } +} \ No newline at end of file diff --git a/web-app/src/services/assistants/types.ts b/web-app/src/services/assistants/types.ts new file mode 100644 index 000000000..1be730fe2 --- /dev/null +++ b/web-app/src/services/assistants/types.ts @@ -0,0 +1,11 @@ +/** + * Assistants Service Types + */ + +import { Assistant } from '@janhq/core' + +export interface AssistantsService { + getAssistants(): Promise + createAssistant(assistant: Assistant): Promise + deleteAssistant(assistant: Assistant): Promise +} \ No newline at end of file diff --git a/web-app/src/services/core/default.ts b/web-app/src/services/core/default.ts new file mode 100644 index 000000000..235e38294 --- /dev/null +++ b/web-app/src/services/core/default.ts @@ -0,0 +1,41 @@ +/** + * Default Core Service - Generic implementation with minimal returns + */ + +import type { ExtensionManifest } from '@/lib/extension' +import type { CoreService, InvokeArgs } from './types' + +export class DefaultCoreService implements CoreService { + async invoke(command: string, args?: InvokeArgs): Promise { + console.log('Core invoke called:', { command, args }) + throw new Error('Core invoke not implemented') + } + + convertFileSrc(filePath: string, protocol?: string): string { + console.log('convertFileSrc called:', { filePath, protocol }) + return filePath + } + + async getActiveExtensions(): Promise { + return [] + } + + async installExtensions(): Promise { + // No-op + } + + async installExtension(extensions: ExtensionManifest[]): Promise { + // No-op in default implementation + return extensions + } + + async uninstallExtension(extensions: string[], reload = true): Promise { + console.log('uninstallExtension called:', { extensions, reload }) + // No-op in default implementation + return Promise.resolve(false) + } + + async getAppToken(): Promise { + return null + } +} \ No newline at end of file diff --git a/web-app/src/services/core/tauri.ts b/web-app/src/services/core/tauri.ts new file mode 100644 index 000000000..8f83b0b2c --- /dev/null +++ b/web-app/src/services/core/tauri.ts @@ -0,0 +1,76 @@ +/** + * Tauri Core Service - Desktop implementation + */ + +import { invoke, convertFileSrc } from '@tauri-apps/api/core' +import type { ExtensionManifest } from '@/lib/extension' +import type { InvokeArgs } from './types' +import { DefaultCoreService } from './default' + +export class TauriCoreService extends DefaultCoreService { + async invoke(command: string, args?: InvokeArgs): Promise { + try { + return await invoke(command, args) + } catch (error) { + console.error(`Error invoking Tauri command '${command}' in Tauri:`, error) + throw error + } + } + + convertFileSrc(filePath: string, protocol?: string): string { + try { + return convertFileSrc(filePath, protocol) + } catch (error) { + console.error('Error converting file src in Tauri:', error) + return filePath + } + } + + // Extension management - using invoke + async getActiveExtensions(): Promise { + try { + return await this.invoke('get_active_extensions') + } catch (error) { + console.error('Error getting active extensions in Tauri:', error) + return [] + } + } + + async installExtensions(): Promise { + try { + return await this.invoke('install_extensions') + } catch (error) { + console.error('Error installing extensions in Tauri:', error) + throw error + } + } + + async installExtension(extensions: ExtensionManifest[]): Promise { + try { + return await this.invoke('install_extension', { extensions }) + } catch (error) { + console.error('Error installing extension in Tauri:', error) + return [] + } + } + + async uninstallExtension(extensions: string[], reload = true): Promise { + try { + return await this.invoke('uninstall_extension', { extensions, reload }) + } catch (error) { + console.error('Error uninstalling extension in Tauri:', error) + return false + } + } + + // App token + async getAppToken(): Promise { + try { + const result = await this.invoke('app_token') + return result + } catch (error) { + console.error('Error getting app token in Tauri:', error) + return null + } + } +} \ No newline at end of file diff --git a/web-app/src/services/core/types.ts b/web-app/src/services/core/types.ts new file mode 100644 index 000000000..8f518ffa4 --- /dev/null +++ b/web-app/src/services/core/types.ts @@ -0,0 +1,24 @@ +/** + * Core Service Types + * Types for core Tauri invoke functionality + */ + +import type { ExtensionManifest } from '@/lib/extension' + +export interface InvokeArgs { + [key: string]: unknown +} + +export interface CoreService { + invoke(command: string, args?: InvokeArgs): Promise + convertFileSrc(filePath: string, protocol?: string): string + + // Extension management + getActiveExtensions(): Promise + installExtensions(): Promise + installExtension(extensions: ExtensionManifest[]): Promise + uninstallExtension(extensions: string[], reload?: boolean): Promise + + // App token + getAppToken(): Promise +} \ No newline at end of file diff --git a/web-app/src/services/core/web.ts b/web-app/src/services/core/web.ts new file mode 100644 index 000000000..39a248611 --- /dev/null +++ b/web-app/src/services/core/web.ts @@ -0,0 +1,92 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +/** + * Web Core Service - Web implementation + * Provides web-specific implementations for core operations + */ + +import type { ExtensionManifest } from '@/lib/extension' +import type { CoreService, InvokeArgs } from './types' +import type { WebExtensionRegistry, WebExtensionName } from '@jan/extensions-web' + +export class WebCoreService implements CoreService { + async invoke(command: string, args?: InvokeArgs): Promise { + console.warn(`Cannot invoke Tauri command '${command}' in web environment`, args) + throw new Error(`Tauri invoke not available in web environment: ${command}`) + } + + convertFileSrc(filePath: string, _protocol?: string): string { + // For web extensions, handle special web:// URLs + if (filePath.startsWith('web://')) { + const extensionName = filePath.replace('web://', '') + return `@jan/extensions-web/${extensionName}` + } + console.warn(`Cannot convert file src in web environment: ${filePath}`) + return filePath + } + + // Extension management - web implementation + async getActiveExtensions(): Promise { + try { + const { WEB_EXTENSIONS } = await import('@jan/extensions-web') + const manifests: ExtensionManifest[] = [] + + // Create manifests and register extensions + const entries = Object.entries(WEB_EXTENSIONS) as [WebExtensionName, WebExtensionRegistry[WebExtensionName]][] + for (const [name, loader] of entries) { + try { + // Load the extension module + const extensionModule = await loader() + const ExtensionClass = extensionModule.default + + // Create manifest data with extension instance + const manifest = { + url: `web://${name}`, + name, + productName: name, + active: true, + description: `Web extension: ${name}`, + version: '1.0.0', + extensionInstance: new ExtensionClass( + `web://${name}`, + name, + name, // productName + true, // active + `Web extension: ${name}`, // description + '1.0.0' // version + ) + } + + manifests.push(manifest) + } catch (error) { + console.error(`Failed to register web extension '${name}':`, error) + } + } + + return manifests + } catch (error) { + console.error('Failed to get web extensions:', error) + return [] + } + } + + async installExtensions(): Promise { + console.warn('Extension installation not available in web environment') + } + + async installExtension(extensions: ExtensionManifest[]): Promise { + console.warn('Extension installation not available in web environment') + return extensions + } + + async uninstallExtension(extensions: string[], reload = true): Promise { + console.log('uninstallExtension called:', { extensions, reload }) + console.warn('Extension uninstallation not available in web environment') + return false + } + + // App token - web fallback + async getAppToken(): Promise { + console.warn('App token not available in web environment') + return null + } +} \ No newline at end of file diff --git a/web-app/src/services/deeplink/default.ts b/web-app/src/services/deeplink/default.ts new file mode 100644 index 000000000..a7f8cf5da --- /dev/null +++ b/web-app/src/services/deeplink/default.ts @@ -0,0 +1,18 @@ +/** + * Default Deep Link Service - Generic implementation with minimal returns + */ + +import type { DeepLinkService } from './types' + +export class DefaultDeepLinkService implements DeepLinkService { + async onOpenUrl(handler: (urls: string[]) => void): Promise<() => void> { + console.log('onOpenUrl called with handler:', typeof handler) + return () => { + // No-op unlisten + } + } + + async getCurrent(): Promise { + return [] + } +} \ No newline at end of file diff --git a/web-app/src/services/deeplink/tauri.ts b/web-app/src/services/deeplink/tauri.ts new file mode 100644 index 000000000..cab694353 --- /dev/null +++ b/web-app/src/services/deeplink/tauri.ts @@ -0,0 +1,27 @@ +/** + * Tauri Deep Link Service - Desktop implementation + */ + +import { onOpenUrl, getCurrent } from '@tauri-apps/plugin-deep-link' +import { DefaultDeepLinkService } from './default' + +export class TauriDeepLinkService extends DefaultDeepLinkService { + async onOpenUrl(handler: (urls: string[]) => void): Promise<() => void> { + try { + return await onOpenUrl(handler) + } catch (error) { + console.error('Error setting up deep link handler in Tauri:', error) + return () => {} + } + } + + async getCurrent(): Promise { + try { + const result = await getCurrent() + return result ?? [] + } catch (error) { + console.error('Error getting current deep links in Tauri:', error) + return [] + } + } +} \ No newline at end of file diff --git a/web-app/src/services/deeplink/types.ts b/web-app/src/services/deeplink/types.ts new file mode 100644 index 000000000..19b3ff517 --- /dev/null +++ b/web-app/src/services/deeplink/types.ts @@ -0,0 +1,9 @@ +/** + * Deep Link Service Types + * Types for handling deep link operations + */ + +export interface DeepLinkService { + onOpenUrl(handler: (urls: string[]) => void): Promise<() => void> + getCurrent(): Promise +} \ No newline at end of file diff --git a/web-app/src/services/deeplink/web.ts b/web-app/src/services/deeplink/web.ts new file mode 100644 index 000000000..bba92c43c --- /dev/null +++ b/web-app/src/services/deeplink/web.ts @@ -0,0 +1,27 @@ +/** + * Web Deep Link Service - Web implementation + * Provides web-specific implementations for deep link operations + */ + +import type { DeepLinkService } from './types' + +export class WebDeepLinkService implements DeepLinkService { + async onOpenUrl(handler: (urls: string[]) => void): Promise<() => void> { + // Web fallback - listen to URL changes + const handleHashChange = () => { + const url = window.location.href + handler([url]) + } + + window.addEventListener('hashchange', handleHashChange) + + return () => { + window.removeEventListener('hashchange', handleHashChange) + } + } + + async getCurrent(): Promise { + // Return current URL + return [window.location.href] + } +} \ No newline at end of file diff --git a/web-app/src/services/dialog/default.ts b/web-app/src/services/dialog/default.ts new file mode 100644 index 000000000..3232fd638 --- /dev/null +++ b/web-app/src/services/dialog/default.ts @@ -0,0 +1,17 @@ +/** + * Default Dialog Service - Generic implementation with minimal returns + */ + +import type { DialogService, DialogOpenOptions } from './types' + +export class DefaultDialogService implements DialogService { + async open(options?: DialogOpenOptions): Promise { + console.log('dialog.open called with options:', options) + return null + } + + async save(options?: DialogOpenOptions): Promise { + console.log('dialog.save called with options:', options) + return null + } +} \ No newline at end of file diff --git a/web-app/src/services/dialog/tauri.ts b/web-app/src/services/dialog/tauri.ts new file mode 100644 index 000000000..faafbb3c8 --- /dev/null +++ b/web-app/src/services/dialog/tauri.ts @@ -0,0 +1,27 @@ +/** + * Tauri Dialog Service - Desktop implementation + */ + +import { open, save } from '@tauri-apps/plugin-dialog' +import type { DialogOpenOptions } from './types' +import { DefaultDialogService } from './default' + +export class TauriDialogService extends DefaultDialogService { + async open(options?: DialogOpenOptions): Promise { + try { + return await open(options) + } catch (error) { + console.error('Error opening dialog in Tauri:', error) + return null + } + } + + async save(options?: DialogOpenOptions): Promise { + try { + return await save(options) + } catch (error) { + console.error('Error opening save dialog in Tauri:', error) + return null + } + } +} \ No newline at end of file diff --git a/web-app/src/services/dialog/types.ts b/web-app/src/services/dialog/types.ts new file mode 100644 index 000000000..245155c36 --- /dev/null +++ b/web-app/src/services/dialog/types.ts @@ -0,0 +1,19 @@ +/** + * Dialog Service Types + * Types for file/folder dialog operations + */ + +export interface DialogOpenOptions { + multiple?: boolean + directory?: boolean + defaultPath?: string + filters?: Array<{ + name: string + extensions: string[] + }> +} + +export interface DialogService { + open(options?: DialogOpenOptions): Promise + save(options?: DialogOpenOptions): Promise +} \ No newline at end of file diff --git a/web-app/src/services/dialog/web.ts b/web-app/src/services/dialog/web.ts new file mode 100644 index 000000000..bb24024f1 --- /dev/null +++ b/web-app/src/services/dialog/web.ts @@ -0,0 +1,53 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +/** + * Web Dialog Service - Web implementation + * Provides web-specific implementations for dialog operations + */ + +import type { DialogService, DialogOpenOptions } from './types' + +export class WebDialogService implements DialogService { + async open(options?: DialogOpenOptions): Promise { + // Web fallback - create hidden input element + return new Promise((resolve) => { + const input = document.createElement('input') + input.type = 'file' + input.multiple = options?.multiple ?? false + + if (options?.directory) { + input.webkitdirectory = true + } + + if (options?.filters) { + const extensions = options.filters.flatMap(filter => + filter.extensions.map(ext => `.${ext}`) + ) + input.accept = extensions.join(',') + } + + input.onchange = (e) => { + const files = (e.target as HTMLInputElement).files + if (!files || files.length === 0) { + resolve(null) + return + } + + if (options?.multiple) { + resolve(Array.from(files).map(file => file.name)) + } else { + resolve(files[0].name) + } + } + + input.oncancel = () => resolve(null) + input.click() + }) + } + + async save(_options?: DialogOpenOptions): Promise { + // Web doesn't support save dialogs in same way + // Return a default filename or null + console.warn('Save dialog not supported in web environment') + return null + } +} \ No newline at end of file diff --git a/web-app/src/services/events.ts b/web-app/src/services/events/EventEmitter.ts similarity index 89% rename from web-app/src/services/events.ts rename to web-app/src/services/events/EventEmitter.ts index 4fcadb68f..bb9e57ebb 100644 --- a/web-app/src/services/events.ts +++ b/web-app/src/services/events/EventEmitter.ts @@ -1,3 +1,8 @@ +/** + * EventEmitter class - matches jan-dev implementation + * Used by ExtensionProvider to set window.core.events + */ + /* eslint-disable @typescript-eslint/no-unsafe-function-type */ export class EventEmitter { private handlers: Map @@ -39,4 +44,4 @@ export class EventEmitter { handler(args) }) } -} +} \ No newline at end of file diff --git a/web-app/src/services/events/default.ts b/web-app/src/services/events/default.ts new file mode 100644 index 000000000..5b5a67492 --- /dev/null +++ b/web-app/src/services/events/default.ts @@ -0,0 +1,19 @@ +/** + * Default Events Service - Generic implementation with minimal returns + */ + +import type { EventsService, EventOptions, UnlistenFn } from './types' + +export class DefaultEventsService implements EventsService { + async emit(event: string, payload?: T, options?: EventOptions): Promise { + console.log('event emit called:', { event, payload, options }) + // No-op - not implemented in default service + } + + async listen(event: string, handler: (event: { payload: T }) => void, options?: EventOptions): Promise { + console.log('event listen called:', { event, handlerType: typeof handler, options }) + return () => { + // No-op unlisten function + } + } +} \ No newline at end of file diff --git a/web-app/src/services/events/tauri.ts b/web-app/src/services/events/tauri.ts new file mode 100644 index 000000000..b15e1e338 --- /dev/null +++ b/web-app/src/services/events/tauri.ts @@ -0,0 +1,30 @@ +/** + * Tauri Events Service - Desktop implementation + */ + +import { emit, listen } from '@tauri-apps/api/event' +import type { EventOptions, UnlistenFn } from './types' +import { DefaultEventsService } from './default' + +export class TauriEventsService extends DefaultEventsService { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async emit(event: string, payload?: T, _options?: EventOptions): Promise { + try { + await emit(event, payload) + } catch (error) { + console.error('Error emitting Tauri event:', error) + throw error + } + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async listen(event: string, handler: (event: { payload: T }) => void, _options?: EventOptions): Promise { + try { + const unlisten = await listen(event, handler) + return unlisten + } catch (error) { + console.error('Error listening to Tauri event:', error) + return () => {} + } + } +} \ No newline at end of file diff --git a/web-app/src/services/events/types.ts b/web-app/src/services/events/types.ts new file mode 100644 index 000000000..e57641114 --- /dev/null +++ b/web-app/src/services/events/types.ts @@ -0,0 +1,16 @@ +/** + * Events Service Types + */ + +export interface EventOptions { + [key: string]: unknown +} + +export interface UnlistenFn { + (): void +} + +export interface EventsService { + emit(event: string, payload?: T, options?: EventOptions): Promise + listen(event: string, handler: (event: { payload: T }) => void, options?: EventOptions): Promise +} \ No newline at end of file diff --git a/web-app/src/services/events/web.ts b/web-app/src/services/events/web.ts new file mode 100644 index 000000000..a14a6fe0d --- /dev/null +++ b/web-app/src/services/events/web.ts @@ -0,0 +1,35 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +/** + * Web Events Service - Web implementation using EventTarget + */ + +import type { EventsService, EventOptions, UnlistenFn } from './types' + +export class WebEventsService implements EventsService { + private eventTarget = new EventTarget() + + async emit(event: string, payload?: T, _options?: EventOptions): Promise { + console.log('Emitting event in web mode:', event, payload) + + const customEvent = new CustomEvent(event, { + detail: { payload } + }) + + this.eventTarget.dispatchEvent(customEvent) + } + + async listen(event: string, handler: (event: { payload: T }) => void, _options?: EventOptions): Promise { + console.log('Listening to event in web mode:', event) + + const eventListener = (e: Event) => { + const customEvent = e as CustomEvent + handler({ payload: customEvent.detail?.payload }) + } + + this.eventTarget.addEventListener(event, eventListener) + + return () => { + this.eventTarget.removeEventListener(event, eventListener) + } + } +} \ No newline at end of file diff --git a/web-app/src/services/hardware.ts b/web-app/src/services/hardware.ts deleted file mode 100644 index ff50cae28..000000000 --- a/web-app/src/services/hardware.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { HardwareData, SystemUsage } from '@/hooks/useHardware' -import { invoke } from '@tauri-apps/api/core' - -// Device list interface for llamacpp extension -export interface DeviceList { - id: string - name: string - mem: number - free: number - activated: boolean -} - -/** - * Get hardware information from the HardwareManagementExtension. - * @returns {Promise} A promise that resolves to the hardware information. - */ -export const getHardwareInfo = async () => { - return invoke('plugin:hardware|get_system_info') as Promise -} - -/** - * Get hardware information from the HardwareManagementExtension. - * @returns {Promise} A promise that resolves to the hardware information. - */ -export const getSystemUsage = async () => { - return invoke('plugin:hardware|get_system_usage') as Promise -} - -/** - * Get devices from the llamacpp extension. - * @returns {Promise} A promise that resolves to the list of available devices. - */ -export const getLlamacppDevices = async (): Promise => { - const extensionManager = window.core.extensionManager - const llamacppExtension = extensionManager.getByName( - '@janhq/llamacpp-extension' - ) - - if (!llamacppExtension) { - throw new Error('llamacpp extension not found') - } - - return llamacppExtension.getDevices() -} - -/** - * Set gpus activate - * @returns A Promise that resolves set gpus activate. - */ -export const setActiveGpus = async (data: { gpus: number[] }) => { - // TODO: llama.cpp extension should handle this - console.log(data) -} diff --git a/web-app/src/services/hardware/default.ts b/web-app/src/services/hardware/default.ts new file mode 100644 index 000000000..250e56de9 --- /dev/null +++ b/web-app/src/services/hardware/default.ts @@ -0,0 +1,24 @@ +/** + * Default Hardware Service - Generic implementation with minimal returns + */ + +import type { HardwareData, SystemUsage, DeviceList, HardwareService } from './types' + +export class DefaultHardwareService implements HardwareService { + async getHardwareInfo(): Promise { + return null + } + + async getSystemUsage(): Promise { + return null + } + + async getLlamacppDevices(): Promise { + return [] + } + + async setActiveGpus(data: { gpus: number[] }): Promise { + console.log('setActiveGpus called with data:', data) + // No-op - not implemented in default service + } +} \ No newline at end of file diff --git a/web-app/src/services/hardware/tauri.ts b/web-app/src/services/hardware/tauri.ts new file mode 100644 index 000000000..458b3037b --- /dev/null +++ b/web-app/src/services/hardware/tauri.ts @@ -0,0 +1,33 @@ +/** + * Tauri Hardware Service - Desktop implementation + */ + +import { invoke } from '@tauri-apps/api/core' +import type { HardwareData, SystemUsage, DeviceList } from './types' +import { DefaultHardwareService } from './default' + +export class TauriHardwareService extends DefaultHardwareService { + async getHardwareInfo(): Promise { + return invoke('plugin:hardware|get_system_info') as Promise + } + + async getSystemUsage(): Promise { + return invoke('plugin:hardware|get_system_usage') as Promise + } + + async getLlamacppDevices(): Promise { + const extensionManager = window.core.extensionManager + const llamacppExtension = extensionManager.getByName('@janhq/llamacpp-extension') + + if (!llamacppExtension) { + throw new Error('llamacpp extension not found') + } + + return llamacppExtension.getDevices() + } + + async setActiveGpus(data: { gpus: number[] }): Promise { + // TODO: llama.cpp extension should handle this + console.log(data) + } +} \ No newline at end of file diff --git a/web-app/src/services/hardware/types.ts b/web-app/src/services/hardware/types.ts new file mode 100644 index 000000000..026d616c6 --- /dev/null +++ b/web-app/src/services/hardware/types.ts @@ -0,0 +1,24 @@ +/** + * Hardware Service Types + */ + +import type { HardwareData, SystemUsage } from '@/hooks/useHardware' + +// Device list interface for llamacpp extension +export interface DeviceList { + id: string + name: string + mem: number + free: number + activated: boolean +} + +export interface HardwareService { + getHardwareInfo(): Promise + getSystemUsage(): Promise + getLlamacppDevices(): Promise + setActiveGpus(data: { gpus: number[] }): Promise +} + +// Re-export hardware types for convenience +export type { HardwareData, SystemUsage } \ No newline at end of file diff --git a/web-app/src/services/index.ts b/web-app/src/services/index.ts new file mode 100644 index 000000000..88c9765ff --- /dev/null +++ b/web-app/src/services/index.ts @@ -0,0 +1,296 @@ +/** + * Service Hub - Centralized service initialization and access + * + * This hub initializes all platform services once at app startup, + * then provides synchronous access to service instances throughout the app. + */ + +import { isPlatformTauri } from '@/lib/platform/utils' + +// Import default services +import { DefaultThemeService } from './theme/default' +import { DefaultWindowService } from './window/default' +import { DefaultEventsService } from './events/default' +import { DefaultHardwareService } from './hardware/default' +import { DefaultAppService } from './app/default' +import { DefaultAnalyticService } from './analytic/default' +import { DefaultMessagesService } from './messages/default' +import { DefaultMCPService } from './mcp/default' +import { DefaultThreadsService } from './threads/default' +import { DefaultProvidersService } from './providers/default' +import { DefaultModelsService } from './models/default' +import { DefaultAssistantsService } from './assistants/default' +import { DefaultDialogService } from './dialog/default' +import { DefaultOpenerService } from './opener/default' +import { DefaultUpdaterService } from './updater/default' +import { DefaultPathService } from './path/default' +import { DefaultCoreService } from './core/default' +import { DefaultDeepLinkService } from './deeplink/default' + +// Import service types +import type { ThemeService } from './theme/types' +import type { WindowService } from './window/types' +import type { EventsService } from './events/types' +import type { HardwareService } from './hardware/types' +import type { AppService } from './app/types' +import type { AnalyticService } from './analytic/types' +import type { MessagesService } from './messages/types' +import type { MCPService } from './mcp/types' +import type { ThreadsService } from './threads/types' +import type { ProvidersService } from './providers/types' +import type { ModelsService } from './models/types' +import type { AssistantsService } from './assistants/types' +import type { DialogService } from './dialog/types' +import type { OpenerService } from './opener/types' +import type { UpdaterService } from './updater/types' +import type { PathService } from './path/types' +import type { CoreService } from './core/types' +import type { DeepLinkService } from './deeplink/types' + +export interface ServiceHub { + // Service getters - all synchronous after initialization + theme(): ThemeService + window(): WindowService + events(): EventsService + hardware(): HardwareService + app(): AppService + analytic(): AnalyticService + messages(): MessagesService + mcp(): MCPService + threads(): ThreadsService + providers(): ProvidersService + models(): ModelsService + assistants(): AssistantsService + dialog(): DialogService + opener(): OpenerService + updater(): UpdaterService + path(): PathService + core(): CoreService + deeplink(): DeepLinkService +} + +class PlatformServiceHub implements ServiceHub { + private themeService: ThemeService = new DefaultThemeService() + private windowService: WindowService = new DefaultWindowService() + private eventsService: EventsService = new DefaultEventsService() + private hardwareService: HardwareService = new DefaultHardwareService() + private appService: AppService = new DefaultAppService() + private analyticService: AnalyticService = new DefaultAnalyticService() + private messagesService: MessagesService = new DefaultMessagesService() + private mcpService: MCPService = new DefaultMCPService() + private threadsService: ThreadsService = new DefaultThreadsService() + private providersService: ProvidersService = new DefaultProvidersService() + private modelsService: ModelsService = new DefaultModelsService() + private assistantsService: AssistantsService = new DefaultAssistantsService() + private dialogService: DialogService = new DefaultDialogService() + private openerService: OpenerService = new DefaultOpenerService() + private updaterService: UpdaterService = new DefaultUpdaterService() + private pathService: PathService = new DefaultPathService() + private coreService: CoreService = new DefaultCoreService() + private deepLinkService: DeepLinkService = new DefaultDeepLinkService() + private initialized = false + + /** + * Initialize all platform services + */ + async initialize(): Promise { + if (this.initialized) return + + console.log( + 'Initializing service hub for platform:', + isPlatformTauri() ? 'Tauri' : 'Web' + ) + + try { + if (isPlatformTauri()) { + const [ + themeModule, + windowModule, + eventsModule, + hardwareModule, + appModule, + mcpModule, + providersModule, + dialogModule, + openerModule, + updaterModule, + pathModule, + coreModule, + deepLinkModule, + ] = await Promise.all([ + import('./theme/tauri'), + import('./window/tauri'), + import('./events/tauri'), + import('./hardware/tauri'), + import('./app/tauri'), + import('./mcp/tauri'), + import('./providers/tauri'), + import('./dialog/tauri'), + import('./opener/tauri'), + import('./updater/tauri'), + import('./path/tauri'), + import('./core/tauri'), + import('./deeplink/tauri'), + ]) + + this.themeService = new themeModule.TauriThemeService() + this.windowService = new windowModule.TauriWindowService() + this.eventsService = new eventsModule.TauriEventsService() + this.hardwareService = new hardwareModule.TauriHardwareService() + this.appService = new appModule.TauriAppService() + this.mcpService = new mcpModule.TauriMCPService() + this.providersService = new providersModule.TauriProvidersService() + this.dialogService = new dialogModule.TauriDialogService() + this.openerService = new openerModule.TauriOpenerService() + this.updaterService = new updaterModule.TauriUpdaterService() + this.pathService = new pathModule.TauriPathService() + this.coreService = new coreModule.TauriCoreService() + this.deepLinkService = new deepLinkModule.TauriDeepLinkService() + } else { + const [ + themeModule, + appModule, + pathModule, + coreModule, + dialogModule, + eventsModule, + windowModule, + deepLinkModule, + providersModule, + ] = await Promise.all([ + import('./theme/web'), + import('./app/web'), + import('./path/web'), + import('./core/web'), + import('./dialog/web'), + import('./events/web'), + import('./window/web'), + import('./deeplink/web'), + import('./providers/web'), + ]) + + this.themeService = new themeModule.WebThemeService() + this.appService = new appModule.WebAppService() + this.pathService = new pathModule.WebPathService() + this.coreService = new coreModule.WebCoreService() + this.dialogService = new dialogModule.WebDialogService() + this.eventsService = new eventsModule.WebEventsService() + this.windowService = new windowModule.WebWindowService() + this.deepLinkService = new deepLinkModule.WebDeepLinkService() + this.providersService = new providersModule.WebProvidersService() + } + + this.initialized = true + console.log('Service hub initialized successfully') + } catch (error) { + console.error('Failed to initialize service hub:', error) + this.initialized = true + throw error + } + } + + private ensureInitialized(): void { + if (!this.initialized) { + throw new Error( + 'Service hub not initialized. Call initializeServiceHub() first.' + ) + } + } + + // Service getters - all synchronous after initialization + theme(): ThemeService { + this.ensureInitialized() + return this.themeService + } + + window(): WindowService { + this.ensureInitialized() + return this.windowService + } + + events(): EventsService { + this.ensureInitialized() + return this.eventsService + } + + hardware(): HardwareService { + this.ensureInitialized() + return this.hardwareService + } + + app(): AppService { + this.ensureInitialized() + return this.appService + } + + analytic(): AnalyticService { + this.ensureInitialized() + return this.analyticService + } + + messages(): MessagesService { + this.ensureInitialized() + return this.messagesService + } + + mcp(): MCPService { + this.ensureInitialized() + return this.mcpService + } + + threads(): ThreadsService { + this.ensureInitialized() + return this.threadsService + } + + providers(): ProvidersService { + this.ensureInitialized() + return this.providersService + } + + models(): ModelsService { + this.ensureInitialized() + return this.modelsService + } + + assistants(): AssistantsService { + this.ensureInitialized() + return this.assistantsService + } + + dialog(): DialogService { + this.ensureInitialized() + return this.dialogService + } + + opener(): OpenerService { + this.ensureInitialized() + return this.openerService + } + + updater(): UpdaterService { + this.ensureInitialized() + return this.updaterService + } + + path(): PathService { + this.ensureInitialized() + return this.pathService + } + + core(): CoreService { + this.ensureInitialized() + return this.coreService + } + + deeplink(): DeepLinkService { + this.ensureInitialized() + return this.deepLinkService + } +} + +export async function initializeServiceHub(): Promise { + const serviceHub = new PlatformServiceHub() + await serviceHub.initialize() + return serviceHub +} diff --git a/web-app/src/services/mcp.ts b/web-app/src/services/mcp.ts deleted file mode 100644 index c266c6a13..000000000 --- a/web-app/src/services/mcp.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { MCPTool } from '@/types/completion' - -/** - * @description This file contains the functions to interact with the MCP API. - * It includes functions to get and update the MCP configuration. - * @param configs - */ -export const updateMCPConfig = async (configs: string) => { - await window.core?.api?.saveMcpConfigs({ configs }) -} - -/** - * @description This function restarts the MCP servers. - * @param configs - */ -export const restartMCPServers = async () => { - await window.core?.api?.restartMcpServers() -} - -/** - * @description This function gets the MCP configuration. - * @returns {Promise} The MCP configuration. - */ -export const getMCPConfig = async () => { - const configString = (await window.core?.api?.getMcpConfigs()) ?? '{}' - const mcpConfig = JSON.parse(configString || '{}') - return mcpConfig -} - -/** - * @description This function gets the MCP configuration. - * @returns {Promise} The MCP configuration. - */ -export const getTools = (): Promise => { - return window.core?.api?.getTools() -} - -/** - * @description This function gets connected MCP servers. - * @returns {Promise} The MCP names - * @returns - */ -export const getConnectedServers = (): Promise => { - return window.core?.api?.getConnectedServers() -} - -/** - * @description This function invoke an MCP tool - * @param tool - * @param params - * @returns - */ -export const callTool = (args: { - toolName: string - arguments: object -}): Promise<{ error: string; content: { text: string }[] }> => { - return window.core?.api?.callTool(args) -} - -/** - * @description Enhanced function to invoke an MCP tool with cancellation support - * @param args - Tool call arguments - * @param cancellationToken - Optional cancellation token - * @returns Promise with tool result and cancellation function - */ -export const callToolWithCancellation = (args: { - toolName: string - arguments: object - cancellationToken?: string -}): { - promise: Promise<{ error: string; content: { text: string }[] }> - cancel: () => Promise - token: string -} => { - // Generate a unique cancellation token if not provided - const token = args.cancellationToken ?? `tool_call_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` - - // Create the tool call promise with cancellation token - const promise = window.core?.api?.callTool({ - ...args, - cancellationToken: token - }) - - // Create cancel function - const cancel = async () => { - await window.core?.api?.cancelToolCall({ cancellationToken: token }) - } - - return { promise, cancel, token } -} - -/** - * @description This function cancels a running tool call - * @param cancellationToken - The token identifying the tool call to cancel - * @returns - */ -export const cancelToolCall = (cancellationToken: string): Promise => { - return window.core?.api?.cancelToolCall({ cancellationToken }) -} diff --git a/web-app/src/services/mcp/default.ts b/web-app/src/services/mcp/default.ts new file mode 100644 index 000000000..801bbd60d --- /dev/null +++ b/web-app/src/services/mcp/default.ts @@ -0,0 +1,69 @@ +/** + * Default MCP Service - Generic implementation with minimal returns + */ + +import { MCPTool } from '@/types/completion' +import type { MCPServerConfig } from '@/hooks/useMCPServers' +import type { MCPService, MCPConfig, ToolCallResult, ToolCallWithCancellationResult } from './types' + +export class DefaultMCPService implements MCPService { + async updateMCPConfig(configs: string): Promise { + console.log('updateMCPConfig called with configs:', configs) + // No-op - not implemented in default service + } + + async restartMCPServers(): Promise { + // No-op + } + + async getMCPConfig(): Promise { + return {} + } + + async getTools(): Promise { + return [] + } + + async getConnectedServers(): Promise { + return [] + } + + async callTool(args: { toolName: string; arguments: object }): Promise { + console.log('callTool called with args:', args) + return { + error: '', + content: [] + } + } + + callToolWithCancellation(args: { + toolName: string + arguments: object + cancellationToken?: string + }): ToolCallWithCancellationResult { + console.log('callToolWithCancellation called with args:', args) + return { + promise: Promise.resolve({ + error: '', + content: [] + }), + cancel: () => Promise.resolve(), + token: '' + } + } + + async cancelToolCall(cancellationToken: string): Promise { + console.log('cancelToolCall called with token:', cancellationToken) + // No-op - not implemented in default service + } + + async activateMCPServer(name: string, config: MCPServerConfig): Promise { + console.log('activateMCPServer called:', { name, config }) + // No-op - not implemented in default service + } + + async deactivateMCPServer(name: string): Promise { + console.log('deactivateMCPServer called with name:', name) + // No-op - not implemented in default service + } +} \ No newline at end of file diff --git a/web-app/src/services/mcp/tauri.ts b/web-app/src/services/mcp/tauri.ts new file mode 100644 index 000000000..697bbc500 --- /dev/null +++ b/web-app/src/services/mcp/tauri.ts @@ -0,0 +1,78 @@ +/** + * Tauri MCP Service - Desktop implementation + */ + +import { invoke } from '@tauri-apps/api/core' +import { MCPTool } from '@/types/completion' +import type { MCPServerConfig } from '@/hooks/useMCPServers' +import type { MCPConfig } from './types' +import { DefaultMCPService } from './default' + +export class TauriMCPService extends DefaultMCPService { + async updateMCPConfig(configs: string): Promise { + await window.core?.api?.saveMcpConfigs({ configs }) + } + + async restartMCPServers(): Promise { + await window.core?.api?.restartMcpServers() + } + + async getMCPConfig(): Promise { + const configString = (await window.core?.api?.getMcpConfigs()) ?? '{}' + const mcpConfig = JSON.parse(configString || '{}') as MCPConfig + return mcpConfig + } + + async getTools(): Promise { + return window.core?.api?.getTools() + } + + async getConnectedServers(): Promise { + return window.core?.api?.getConnectedServers() + } + + async callTool(args: { + toolName: string + arguments: object + }): Promise<{ error: string; content: { text: string }[] }> { + return window.core?.api?.callTool(args) + } + + callToolWithCancellation(args: { + toolName: string + arguments: object + cancellationToken?: string + }): { + promise: Promise<{ error: string; content: { text: string }[] }> + cancel: () => Promise + token: string + } { + // Generate a unique cancellation token if not provided + const token = args.cancellationToken ?? `tool_call_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` + + // Create the tool call promise with cancellation token + const promise = window.core?.api?.callTool({ + ...args, + cancellationToken: token + }) + + // Create cancel function + const cancel = async () => { + await window.core?.api?.cancelToolCall({ cancellationToken: token }) + } + + return { promise, cancel, token } + } + + async cancelToolCall(cancellationToken: string): Promise { + return await window.core?.api?.cancelToolCall({ cancellationToken }) + } + + async activateMCPServer(name: string, config: MCPServerConfig): Promise { + return await invoke('activate_mcp_server', { name, config }) + } + + async deactivateMCPServer(name: string): Promise { + return await invoke('deactivate_mcp_server', { name }) + } +} \ No newline at end of file diff --git a/web-app/src/services/mcp/types.ts b/web-app/src/services/mcp/types.ts new file mode 100644 index 000000000..f68668d2c --- /dev/null +++ b/web-app/src/services/mcp/types.ts @@ -0,0 +1,40 @@ +/** + * MCP Service Types + */ + +import { MCPTool } from '@/types/completion' +import type { MCPServerConfig, MCPServers } from '@/hooks/useMCPServers' + +export interface MCPConfig { + mcpServers?: MCPServers +} + +export interface ToolCallResult { + error: string + content: { text: string }[] +} + +export interface ToolCallWithCancellationResult { + promise: Promise + cancel: () => Promise + token: string +} + +export interface MCPService { + updateMCPConfig(configs: string): Promise + restartMCPServers(): Promise + getMCPConfig(): Promise + getTools(): Promise + getConnectedServers(): Promise + callTool(args: { toolName: string; arguments: object }): Promise + callToolWithCancellation(args: { + toolName: string + arguments: object + cancellationToken?: string + }): ToolCallWithCancellationResult + cancelToolCall(cancellationToken: string): Promise + + // MCP Server lifecycle management + activateMCPServer(name: string, config: MCPServerConfig): Promise + deactivateMCPServer(name: string): Promise +} \ No newline at end of file diff --git a/web-app/src/services/messages.ts b/web-app/src/services/messages.ts deleted file mode 100644 index 2d47b0028..000000000 --- a/web-app/src/services/messages.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { ExtensionManager } from '@/lib/extension' -import { - ConversationalExtension, - ExtensionTypeEnum, - ThreadMessage, -} from '@janhq/core' - -/** - * @fileoverview Fetch messages from the extension manager. - * @param threadId - * @returns - */ -export const fetchMessages = async ( - threadId: string -): Promise => { - return ( - ExtensionManager.getInstance() - .get(ExtensionTypeEnum.Conversational) - ?.listMessages(threadId) - ?.catch(() => []) ?? [] - ) -} - -/** - * @fileoverview Create a message using the extension manager. - * @param message - * @returns - */ -export const createMessage = async ( - message: ThreadMessage -): Promise => { - return ( - ExtensionManager.getInstance() - .get(ExtensionTypeEnum.Conversational) - ?.createMessage(message) - ?.catch(() => message) ?? message - ) -} - -/** - * @fileoverview Delete a message using the extension manager. - * @param threadId - * @param messageID - * @returns - */ -export const deleteMessage = (threadId: string, messageId: string) => { - return ExtensionManager.getInstance() - .get(ExtensionTypeEnum.Conversational) - ?.deleteMessage(threadId, messageId) -} diff --git a/web-app/src/services/messages/default.ts b/web-app/src/services/messages/default.ts new file mode 100644 index 000000000..9f3ca69c6 --- /dev/null +++ b/web-app/src/services/messages/default.ts @@ -0,0 +1,37 @@ +/** + * Default Messages Service - Web implementation + */ + +import { ExtensionManager } from '@/lib/extension' +import { + ConversationalExtension, + ExtensionTypeEnum, + ThreadMessage, +} from '@janhq/core' +import type { MessagesService } from './types' + +export class DefaultMessagesService implements MessagesService { + async fetchMessages(threadId: string): Promise { + return ( + ExtensionManager.getInstance() + .get(ExtensionTypeEnum.Conversational) + ?.listMessages(threadId) + ?.catch(() => []) ?? [] + ) + } + + async createMessage(message: ThreadMessage): Promise { + return ( + ExtensionManager.getInstance() + .get(ExtensionTypeEnum.Conversational) + ?.createMessage(message) + ?.catch(() => message) ?? message + ) + } + + async deleteMessage(threadId: string, messageId: string): Promise { + await ExtensionManager.getInstance() + .get(ExtensionTypeEnum.Conversational) + ?.deleteMessage(threadId, messageId) + } +} \ No newline at end of file diff --git a/web-app/src/services/messages/types.ts b/web-app/src/services/messages/types.ts new file mode 100644 index 000000000..ad5ae72c8 --- /dev/null +++ b/web-app/src/services/messages/types.ts @@ -0,0 +1,11 @@ +/** + * Messages Service Types + */ + +import { ThreadMessage } from '@janhq/core' + +export interface MessagesService { + fetchMessages(threadId: string): Promise + createMessage(message: ThreadMessage): Promise + deleteMessage(threadId: string, messageId: string): Promise +} \ No newline at end of file diff --git a/web-app/src/services/models.ts b/web-app/src/services/models.ts deleted file mode 100644 index df7dacf00..000000000 --- a/web-app/src/services/models.ts +++ /dev/null @@ -1,613 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import { sanitizeModelId } from '@/lib/utils' -import { - AIEngine, - EngineManager, - SessionInfo, - SettingComponentProps, -} from '@janhq/core' -import { Model as CoreModel } from '@janhq/core' -// Types for model catalog -export interface ModelQuant { - model_id: string - path: string - file_size: string -} - -export interface MMProjModel { - model_id: string - path: string - file_size: string -} - -export interface CatalogModel { - model_name: string - description: string - developer: string - downloads: number - num_quants: number - quants: ModelQuant[] - mmproj_models?: MMProjModel[] - num_mmproj: number - created_at?: string - readme?: string - tools?: boolean -} - -export type ModelCatalog = CatalogModel[] - -// HuggingFace repository information -export interface HuggingFaceRepo { - id: string - modelId: string - sha: string - downloads: number - likes: number - library_name?: string - tags: string[] - pipeline_tag?: string - createdAt: string - last_modified: string - private: boolean - disabled: boolean - gated: boolean | string - author: string - cardData?: { - license?: string - language?: string[] - datasets?: string[] - metrics?: string[] - } - siblings?: Array<{ - rfilename: string - size?: number - blobId?: string - lfs?: { - sha256: string - size: number - pointerSize: number - } - }> - readme?: string -} - -// TODO: Replace this with the actual provider later -const defaultProvider = 'llamacpp' - -const getEngine = (provider: string = defaultProvider) => { - return EngineManager.instance().get(provider) as AIEngine | undefined -} -/** - * Fetches all available models. - * @returns A promise that resolves to the models. - */ -export const fetchModels = async () => { - return getEngine()?.list() -} - -/** - * Fetches the model catalog from the GitHub repository. - * @returns A promise that resolves to the model catalog. - */ -export const fetchModelCatalog = async (): Promise => { - try { - const response = await fetch(MODEL_CATALOG_URL) - - if (!response.ok) { - throw new Error( - `Failed to fetch model catalog: ${response.status} ${response.statusText}` - ) - } - - const catalog: ModelCatalog = await response.json() - return catalog - } catch (error) { - console.error('Error fetching model catalog:', error) - throw new Error( - `Failed to fetch model catalog: ${error instanceof Error ? error.message : 'Unknown error'}` - ) - } -} - -/** - * Fetches HuggingFace repository information. - * @param repoId The repository ID (e.g., "microsoft/DialoGPT-medium") - * @returns A promise that resolves to the repository information. - */ -export const fetchHuggingFaceRepo = async ( - repoId: string, - hfToken?: string -): Promise => { - try { - // Clean the repo ID to handle various input formats - const cleanRepoId = repoId - .replace(/^https?:\/\/huggingface\.co\//, '') - .replace(/^huggingface\.co\//, '') - .replace(/\/$/, '') // Remove trailing slash - .trim() - - if (!cleanRepoId || !cleanRepoId.includes('/')) { - return null - } - - const response = await fetch( - `https://huggingface.co/api/models/${cleanRepoId}?blobs=true&files_metadata=true`, - { - headers: hfToken - ? { - Authorization: `Bearer ${hfToken}`, - } - : {}, - } - ) - - if (!response.ok) { - if (response.status === 404) { - return null // Repository not found - } - throw new Error( - `Failed to fetch HuggingFace repository: ${response.status} ${response.statusText}` - ) - } - - const repoData: HuggingFaceRepo = await response.json() - return repoData - } catch (error) { - console.error('Error fetching HuggingFace repository:', error) - return null - } -} - -// Convert HuggingFace repository to CatalogModel format -export const convertHfRepoToCatalogModel = ( - repo: HuggingFaceRepo -): CatalogModel => { - // Format file size helper - const formatFileSize = (size?: number) => { - if (!size) return 'Unknown size' - if (size < 1024 ** 3) return `${(size / 1024 ** 2).toFixed(1)} MB` - return `${(size / 1024 ** 3).toFixed(1)} GB` - } - - // Extract GGUF files from the repository siblings - const ggufFiles = - repo.siblings?.filter((file) => - file.rfilename.toLowerCase().endsWith('.gguf') - ) || [] - - // Separate regular GGUF files from mmproj files - const regularGgufFiles = ggufFiles.filter( - (file) => !file.rfilename.toLowerCase().includes('mmproj') - ) - - const mmprojFiles = ggufFiles.filter((file) => - file.rfilename.toLowerCase().includes('mmproj') - ) - - // Convert regular GGUF files to quants format - const quants = regularGgufFiles.map((file) => { - // Generate model_id from filename (remove .gguf extension, case-insensitive) - const modelId = file.rfilename.replace(/\.gguf$/i, '') - - return { - model_id: sanitizeModelId(modelId), - path: `https://huggingface.co/${repo.modelId}/resolve/main/${file.rfilename}`, - file_size: formatFileSize(file.size), - } - }) - - // Convert mmproj files to mmproj_models format - const mmprojModels = mmprojFiles.map((file) => { - const modelId = file.rfilename.replace(/\.gguf$/i, '') - - return { - model_id: sanitizeModelId(modelId), - path: `https://huggingface.co/${repo.modelId}/resolve/main/${file.rfilename}`, - file_size: formatFileSize(file.size), - } - }) - - return { - model_name: repo.modelId, - developer: repo.author, - downloads: repo.downloads || 0, - created_at: repo.createdAt, - num_quants: quants.length, - quants: quants, - num_mmproj: mmprojModels.length, - mmproj_models: mmprojModels, - readme: `https://huggingface.co/${repo.modelId}/resolve/main/README.md`, - description: `**Tags**: ${repo.tags?.join(', ')}`, - } -} - -/** - * Updates a model. - * @param model The model to update. - * @returns A promise that resolves when the model is updated. - */ -export const updateModel = async ( - model: Partial - // provider: string, -) => { - if (model.settings) - getEngine()?.updateSettings(model.settings as SettingComponentProps[]) -} - -/** - * Pull or import a model. - * @param model The model to pull. - * @returns A promise that resolves when the model download task is created. - */ -export const pullModel = async ( - id: string, - modelPath: string, - modelSha256?: string, - modelSize?: number, - mmprojPath?: string, - mmprojSha256?: string, - mmprojSize?: number -) => { - return getEngine()?.import(id, { - modelPath, - mmprojPath, - modelSha256, - modelSize, - mmprojSha256, - mmprojSize, - }) -} - -/** - * Pull a model with real-time metadata fetching from HuggingFace. - * Extracts hash and size information from the model URL for both main model and mmproj files. - * @param id The model ID - * @param modelPath The model file URL (HuggingFace download URL) - * @param mmprojPath Optional mmproj file URL - * @param hfToken Optional HuggingFace token for authentication - * @returns A promise that resolves when the model download task is created. - */ -export const pullModelWithMetadata = async ( - id: string, - modelPath: string, - mmprojPath?: string, - hfToken?: string -) => { - let modelSha256: string | undefined - let modelSize: number | undefined - let mmprojSha256: string | undefined - let mmprojSize: number | undefined - - // Extract repo ID from model URL - // URL format: https://huggingface.co/{repo}/resolve/main/{filename} - const modelUrlMatch = modelPath.match( - /https:\/\/huggingface\.co\/([^/]+\/[^/]+)\/resolve\/main\/(.+)/ - ) - - if (modelUrlMatch) { - const [, repoId, modelFilename] = modelUrlMatch - - try { - // Fetch real-time metadata from HuggingFace - const repoInfo = await fetchHuggingFaceRepo(repoId, hfToken) - - if (repoInfo?.siblings) { - // Find the specific model file - const modelFile = repoInfo.siblings.find( - (file) => file.rfilename === modelFilename - ) - if (modelFile?.lfs) { - modelSha256 = modelFile.lfs.sha256 - modelSize = modelFile.lfs.size - } - - // If mmproj path provided, extract its metadata too - if (mmprojPath) { - const mmprojUrlMatch = mmprojPath.match( - /https:\/\/huggingface\.co\/[^/]+\/[^/]+\/resolve\/main\/(.+)/ - ) - if (mmprojUrlMatch) { - const [, mmprojFilename] = mmprojUrlMatch - const mmprojFile = repoInfo.siblings.find( - (file) => file.rfilename === mmprojFilename - ) - if (mmprojFile?.lfs) { - mmprojSha256 = mmprojFile.lfs.sha256 - mmprojSize = mmprojFile.lfs.size - } - } - } - } - } catch (error) { - console.warn( - 'Failed to fetch HuggingFace metadata, proceeding without hash verification:', - error - ) - // Continue with download even if metadata fetch fails - } - } - - // Call the original pullModel with the fetched metadata - return pullModel( - id, - modelPath, - modelSha256, - modelSize, - mmprojPath, - mmprojSha256, - mmprojSize - ) -} - -/** - * Aborts a model download. - * @param id - * @returns - */ -export const abortDownload = async (id: string) => { - return getEngine()?.abortImport(id) -} - -/** - * Deletes a model. - * @param id - * @returns - */ -export const deleteModel = async (id: string) => { - return getEngine()?.delete(id) -} - -/** - * Gets the active models for a given provider. - * @param provider - * @returns - */ -export const getActiveModels = async (provider?: string) => { - // getEngine(provider) - return getEngine(provider)?.getLoadedModels() -} - -/** - * Stops a model for a given provider. - * @param model - * @param provider - * @returns - */ -export const stopModel = async (model: string, provider?: string) => { - getEngine(provider)?.unload(model) -} - -/** - * Stops all active models. - * @returns - */ -export const stopAllModels = async () => { - const models = await getActiveModels() - if (models) await Promise.all(models.map((model) => stopModel(model))) -} - -/** - * @fileoverview Helper function to start a model. - * This function loads the model from the provider. - * Provider's chat function will handle loading the model. - * @param provider - * @param model - * @returns - */ -export const startModel = async ( - provider: ProviderObject, - model: string -): Promise => { - const engine = getEngine(provider.provider) - if (!engine) return undefined - - if ((await engine.getLoadedModels()).includes(model)) return undefined - - // Find the model configuration to get settings - const modelConfig = provider.models.find((m) => m.id === model) - - // Key mapping function to transform setting keys - const mapSettingKey = (key: string): string => { - const keyMappings: Record = { - ctx_len: 'ctx_size', - ngl: 'n_gpu_layers', - } - return keyMappings[key] || key - } - - const settings = modelConfig?.settings - ? Object.fromEntries( - Object.entries(modelConfig.settings).map(([key, value]) => [ - mapSettingKey(key), - value.controller_props?.value, - ]) - ) - : undefined - - return engine.load(model, settings).catch((error) => { - console.error( - `Failed to start model ${model} for provider ${provider.provider}:`, - error - ) - throw error - }) -} - -/** - * Check if model support tool use capability - * Returned by backend engine - * @param modelId - * @returns - */ -export const isToolSupported = async (modelId: string): Promise => { - const engine = getEngine() - if (!engine) return false - - return engine.isToolSupported(modelId) -} - -/** - * Checks if mmproj.gguf file exists for a given model ID in the llamacpp provider. - * Also checks if the model has offload_mmproj setting. - * If mmproj.gguf exists, adds offload_mmproj setting with value true. - * @param modelId - The model ID to check for mmproj.gguf - * @param updateProvider - Function to update the provider state - * @param getProviderByName - Function to get provider by name - * @returns Promise<{exists: boolean, settingsUpdated: boolean}> - exists: true if mmproj.gguf exists, settingsUpdated: true if settings were modified - */ -export const checkMmprojExistsAndUpdateOffloadMMprojSetting = async ( - modelId: string, - updateProvider?: (providerName: string, data: Partial) => void, - getProviderByName?: (providerName: string) => ModelProvider | undefined -): Promise<{ exists: boolean; settingsUpdated: boolean }> => { - let settingsUpdated = false - - try { - const engine = getEngine('llamacpp') as AIEngine & { - checkMmprojExists?: (id: string) => Promise - } - if (engine && typeof engine.checkMmprojExists === 'function') { - const exists = await engine.checkMmprojExists(modelId) - - // If we have the store functions, use them; otherwise fall back to localStorage - if (updateProvider && getProviderByName) { - const provider = getProviderByName('llamacpp') - if (provider) { - const model = provider.models.find((m) => m.id === modelId) - - if (model?.settings) { - const hasOffloadMmproj = 'offload_mmproj' in model.settings - - // If mmproj exists, add offload_mmproj setting (only if it doesn't exist) - if (exists && !hasOffloadMmproj) { - // Create updated models array with the new setting - const updatedModels = provider.models.map((m) => { - if (m.id === modelId) { - return { - ...m, - settings: { - ...m.settings, - offload_mmproj: { - key: 'offload_mmproj', - title: 'Offload MMProj', - description: - 'Offload multimodal projection layers to GPU', - controller_type: 'checkbox', - controller_props: { - value: true, - }, - }, - }, - } - } - return m - }) - - // Update the provider with the new models array - updateProvider('llamacpp', { models: updatedModels }) - settingsUpdated = true - } - } - } - } else { - // Fall back to localStorage approach for backwards compatibility - try { - const modelProviderData = JSON.parse( - localStorage.getItem('model-provider') || '{}' - ) - const llamacppProvider = modelProviderData.state?.providers?.find( - (p: any) => p.provider === 'llamacpp' - ) - const model = llamacppProvider?.models?.find( - (m: any) => m.id === modelId - ) - - if (model?.settings) { - // If mmproj exists, add offload_mmproj setting (only if it doesn't exist) - if (exists) { - if (!model.settings.offload_mmproj) { - model.settings.offload_mmproj = { - key: 'offload_mmproj', - title: 'Offload MMProj', - description: 'Offload multimodal projection layers to GPU', - controller_type: 'checkbox', - controller_props: { - value: true, - }, - } - // Save updated settings back to localStorage - localStorage.setItem( - 'model-provider', - JSON.stringify(modelProviderData) - ) - settingsUpdated = true - } - } - } - } catch (localStorageError) { - console.error( - `Error checking localStorage for model ${modelId}:`, - localStorageError - ) - } - } - - return { exists, settingsUpdated } - } - } catch (error) { - console.error(`Error checking mmproj for model ${modelId}:`, error) - } - return { exists: false, settingsUpdated } -} - -/** - * Checks if mmproj.gguf file exists for a given model ID in the llamacpp provider. - * If mmproj.gguf exists, adds offload_mmproj setting with value true. - * @param modelId - The model ID to check for mmproj.gguf - * @returns Promise<{exists: boolean, settingsUpdated: boolean}> - exists: true if mmproj.gguf exists, settingsUpdated: true if settings were modified - */ -export const checkMmprojExists = async (modelId: string): Promise => { - try { - const engine = getEngine('llamacpp') as AIEngine & { - checkMmprojExists?: (id: string) => Promise - } - if (engine && typeof engine.checkMmprojExists === 'function') { - return await engine.checkMmprojExists(modelId) - } - } catch (error) { - console.error(`Error checking mmproj for model ${modelId}:`, error) - } - return false -} - -/** - * Checks if a model is supported by analyzing memory requirements and system resources. - * @param modelPath - The path to the model file (local path or URL) - * @param ctxSize - The context size for the model (default: 4096) - * @returns Promise<'RED' | 'YELLOW' | 'GREEN'> - Support status: - * - 'RED': Model weights don't fit in available memory - * - 'YELLOW': Model weights fit, but KV cache doesn't - * - 'GREEN': Both model weights and KV cache fit in available memory - */ -export const isModelSupported = async ( - modelPath: string, - ctxSize?: number -): Promise<'RED' | 'YELLOW' | 'GREEN'> => { - try { - const engine = getEngine('llamacpp') as AIEngine & { - isModelSupported?: ( - path: string, - ctx_size?: number - ) => Promise<'RED' | 'YELLOW' | 'GREEN'> - } - if (engine && typeof engine.isModelSupported === 'function') { - return await engine.isModelSupported(modelPath, ctxSize) - } - // Fallback if method is not available - console.warn('isModelSupported method not available in llamacpp engine') - return 'YELLOW' // Conservative fallback - } catch (error) { - console.error(`Error checking model support for ${modelPath}:`, error) - return 'RED' // Error state, assume not supported - } -} diff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.ts new file mode 100644 index 000000000..f5e018bcc --- /dev/null +++ b/web-app/src/services/models/default.ts @@ -0,0 +1,451 @@ +/** + * Default Models Service - Web implementation + */ + +import { sanitizeModelId } from '@/lib/utils' +import { + AIEngine, + EngineManager, + SessionInfo, + SettingComponentProps, + modelInfo, +} from '@janhq/core' +import { Model as CoreModel } from '@janhq/core' +import type { ModelsService, ModelCatalog, HuggingFaceRepo, CatalogModel } from './types' + +// TODO: Replace this with the actual provider later +const defaultProvider = 'llamacpp' + +export class DefaultModelsService implements ModelsService { + private getEngine(provider: string = defaultProvider) { + return EngineManager.instance().get(provider) as AIEngine | undefined + } + + async fetchModels(): Promise { + return this.getEngine()?.list() ?? [] + } + + async fetchModelCatalog(): Promise { + try { + const response = await fetch(MODEL_CATALOG_URL) + + if (!response.ok) { + throw new Error( + `Failed to fetch model catalog: ${response.status} ${response.statusText}` + ) + } + + const catalog: ModelCatalog = await response.json() + return catalog + } catch (error) { + console.error('Error fetching model catalog:', error) + throw new Error( + `Failed to fetch model catalog: ${error instanceof Error ? error.message : 'Unknown error'}` + ) + } + } + + async fetchHuggingFaceRepo( + repoId: string, + hfToken?: string + ): Promise { + try { + // Clean the repo ID to handle various input formats + const cleanRepoId = repoId + .replace(/^https?:\/\/huggingface\.co\//, '') + .replace(/^huggingface\.co\//, '') + .replace(/\/$/, '') // Remove trailing slash + .trim() + + if (!cleanRepoId || !cleanRepoId.includes('/')) { + return null + } + + const response = await fetch( + `https://huggingface.co/api/models/${cleanRepoId}?blobs=true&files_metadata=true`, + { + headers: hfToken + ? { + Authorization: `Bearer ${hfToken}`, + } + : {}, + } + ) + + if (!response.ok) { + if (response.status === 404) { + return null // Repository not found + } + throw new Error( + `Failed to fetch HuggingFace repository: ${response.status} ${response.statusText}` + ) + } + + const repoData = await response.json() + return repoData + } catch (error) { + console.error('Error fetching HuggingFace repository:', error) + return null + } + } + + convertHfRepoToCatalogModel(repo: HuggingFaceRepo): CatalogModel { + // Format file size helper + const formatFileSize = (size?: number) => { + if (!size) return 'Unknown size' + if (size < 1024 ** 3) return `${(size / 1024 ** 2).toFixed(1)} MB` + return `${(size / 1024 ** 3).toFixed(1)} GB` + } + + // Extract GGUF files from the repository siblings + const ggufFiles = + repo.siblings?.filter((file) => + file.rfilename.toLowerCase().endsWith('.gguf') + ) || [] + + // Separate regular GGUF files from mmproj files + const regularGgufFiles = ggufFiles.filter( + (file) => !file.rfilename.toLowerCase().includes('mmproj') + ) + + const mmprojFiles = ggufFiles.filter((file) => + file.rfilename.toLowerCase().includes('mmproj') + ) + + // Convert regular GGUF files to quants format + const quants = regularGgufFiles.map((file) => { + // Generate model_id from filename (remove .gguf extension, case-insensitive) + const modelId = file.rfilename.replace(/\.gguf$/i, '') + + return { + model_id: sanitizeModelId(modelId), + path: `https://huggingface.co/${repo.modelId}/resolve/main/${file.rfilename}`, + file_size: formatFileSize(file.size), + } + }) + + // Convert mmproj files to mmproj_models format + const mmprojModels = mmprojFiles.map((file) => { + const modelId = file.rfilename.replace(/\.gguf$/i, '') + + return { + model_id: sanitizeModelId(modelId), + path: `https://huggingface.co/${repo.modelId}/resolve/main/${file.rfilename}`, + file_size: formatFileSize(file.size), + } + }) + + return { + model_name: repo.modelId, + developer: repo.author, + downloads: repo.downloads || 0, + created_at: repo.createdAt, + num_quants: quants.length, + quants: quants, + num_mmproj: mmprojModels.length, + mmproj_models: mmprojModels, + readme: `https://huggingface.co/${repo.modelId}/resolve/main/README.md`, + description: `**Tags**: ${repo.tags?.join(', ')}`, + } + } + + async updateModel(model: Partial): Promise { + if (model.settings) + this.getEngine()?.updateSettings(model.settings as SettingComponentProps[]) + } + + async pullModel( + id: string, + modelPath: string, + modelSha256?: string, + modelSize?: number, + mmprojPath?: string, + mmprojSha256?: string, + mmprojSize?: number + ): Promise { + return this.getEngine()?.import(id, { + modelPath, + mmprojPath, + modelSha256, + modelSize, + mmprojSha256, + mmprojSize, + }) + } + + async pullModelWithMetadata( + id: string, + modelPath: string, + mmprojPath?: string, + hfToken?: string + ): Promise { + let modelSha256: string | undefined + let modelSize: number | undefined + let mmprojSha256: string | undefined + let mmprojSize: number | undefined + + // Extract repo ID from model URL + // URL format: https://huggingface.co/{repo}/resolve/main/{filename} + const modelUrlMatch = modelPath.match( + /https:\/\/huggingface\.co\/([^/]+\/[^/]+)\/resolve\/main\/(.+)/ + ) + + if (modelUrlMatch) { + const [, repoId, modelFilename] = modelUrlMatch + + try { + // Fetch real-time metadata from HuggingFace + const repoInfo = await this.fetchHuggingFaceRepo(repoId, hfToken) + + if (repoInfo?.siblings) { + // Find the specific model file + const modelFile = repoInfo.siblings.find( + (file) => file.rfilename === modelFilename + ) + if (modelFile?.lfs) { + modelSha256 = modelFile.lfs.sha256 + modelSize = modelFile.lfs.size + } + + // If mmproj path provided, extract its metadata too + if (mmprojPath) { + const mmprojUrlMatch = mmprojPath.match( + /https:\/\/huggingface\.co\/[^/]+\/[^/]+\/resolve\/main\/(.+)/ + ) + if (mmprojUrlMatch) { + const [, mmprojFilename] = mmprojUrlMatch + const mmprojFile = repoInfo.siblings.find( + (file) => file.rfilename === mmprojFilename + ) + if (mmprojFile?.lfs) { + mmprojSha256 = mmprojFile.lfs.sha256 + mmprojSize = mmprojFile.lfs.size + } + } + } + } + } catch (error) { + console.warn( + 'Failed to fetch HuggingFace metadata, proceeding without hash verification:', + error + ) + // Continue with download even if metadata fetch fails + } + } + + // Call the original pullModel with the fetched metadata + return this.pullModel( + id, + modelPath, + modelSha256, + modelSize, + mmprojPath, + mmprojSha256, + mmprojSize + ) + } + + async abortDownload(id: string): Promise { + return this.getEngine()?.abortImport(id) + } + + async deleteModel(id: string): Promise { + return this.getEngine()?.delete(id) + } + + async getActiveModels(provider?: string): Promise { + return this.getEngine(provider)?.getLoadedModels() ?? [] + } + + async stopModel(model: string, provider?: string): Promise { + this.getEngine(provider)?.unload(model) + } + + async stopAllModels(): Promise { + const models = await this.getActiveModels() + if (models) await Promise.all(models.map((model) => this.stopModel(model))) + } + + async startModel(provider: ProviderObject, model: string): Promise { + const engine = this.getEngine(provider.provider) + if (!engine) return undefined + + const loadedModels = await engine.getLoadedModels() + if (loadedModels.includes(model)) return undefined + + // Find the model configuration to get settings + const modelConfig = provider.models.find((m) => m.id === model) + + // Key mapping function to transform setting keys + const mapSettingKey = (key: string): string => { + const keyMappings: Record = { + ctx_len: 'ctx_size', + ngl: 'n_gpu_layers', + } + return keyMappings[key] || key + } + + const settings = modelConfig?.settings + ? Object.fromEntries( + Object.entries(modelConfig.settings).map(([key, value]) => [ + mapSettingKey(key), + value.controller_props?.value, + ]) + ) + : undefined + + return engine.load(model, settings).catch((error) => { + console.error( + `Failed to start model ${model} for provider ${provider.provider}:`, + error + ) + throw error + }) + } + + async isToolSupported(modelId: string): Promise { + const engine = this.getEngine() + if (!engine) return false + + return engine.isToolSupported(modelId) + } + + async checkMmprojExistsAndUpdateOffloadMMprojSetting( + modelId: string, + updateProvider?: (providerName: string, data: Partial) => void, + getProviderByName?: (providerName: string) => ModelProvider | undefined + ): Promise<{ exists: boolean; settingsUpdated: boolean }> { + let settingsUpdated = false + + try { + const engine = this.getEngine('llamacpp') as AIEngine & { + checkMmprojExists?: (id: string) => Promise + } + if (engine && typeof engine.checkMmprojExists === 'function') { + const exists = await engine.checkMmprojExists(modelId) + + // If we have the store functions, use them; otherwise fall back to localStorage + if (updateProvider && getProviderByName) { + const provider = getProviderByName('llamacpp') + if (provider) { + const model = provider.models.find((m) => m.id === modelId) + + if (model?.settings) { + const hasOffloadMmproj = 'offload_mmproj' in model.settings + + // If mmproj exists, add offload_mmproj setting (only if it doesn't exist) + if (exists && !hasOffloadMmproj) { + // Create updated models array with the new setting + const updatedModels = provider.models.map((m) => { + if (m.id === modelId) { + return { + ...m, + settings: { + ...m.settings, + offload_mmproj: { + key: 'offload_mmproj', + title: 'Offload MMProj', + description: + 'Offload multimodal projection model to GPU', + controller_type: 'checkbox', + controller_props: { + value: true, + }, + }, + }, + } + } + return m + }) + + // Update the provider with the new models array + updateProvider('llamacpp', { models: updatedModels }) + settingsUpdated = true + } + } + } + } else { + // Fall back to localStorage approach for backwards compatibility + try { + const modelProviderData = JSON.parse( + localStorage.getItem('model-provider') || '{}' + ) + const llamacppProvider = modelProviderData.state?.providers?.find( + (p: { provider: string }) => p.provider === 'llamacpp' + ) + const model = llamacppProvider?.models?.find( + (m: { id: string; settings?: Record }) => m.id === modelId + ) + + if (model?.settings) { + // If mmproj exists, add offload_mmproj setting (only if it doesn't exist) + if (exists) { + if (!model.settings.offload_mmproj) { + model.settings.offload_mmproj = { + key: 'offload_mmproj', + title: 'Offload MMProj', + description: 'Offload multimodal projection layers to GPU', + controller_type: 'checkbox', + controller_props: { + value: true, + }, + } + // Save updated settings back to localStorage + localStorage.setItem( + 'model-provider', + JSON.stringify(modelProviderData) + ) + settingsUpdated = true + } + } + } + } catch (localStorageError) { + console.error( + `Error checking localStorage for model ${modelId}:`, + localStorageError + ) + } + } + + return { exists, settingsUpdated } + } + } catch (error) { + console.error(`Error checking mmproj for model ${modelId}:`, error) + } + return { exists: false, settingsUpdated } + } + + async checkMmprojExists(modelId: string): Promise { + try { + const engine = this.getEngine('llamacpp') as AIEngine & { + checkMmprojExists?: (id: string) => Promise + } + if (engine && typeof engine.checkMmprojExists === 'function') { + return await engine.checkMmprojExists(modelId) + } + } catch (error) { + console.error(`Error checking mmproj for model ${modelId}:`, error) + } + return false + } + + async isModelSupported(modelPath: string, ctxSize?: number): Promise<'RED' | 'YELLOW' | 'GREEN' | 'GREY'> { + try { + const engine = this.getEngine('llamacpp') as AIEngine & { + isModelSupported?: ( + path: string, + ctx_size?: number + ) => Promise<'RED' | 'YELLOW' | 'GREEN'> + } + if (engine && typeof engine.isModelSupported === 'function') { + return await engine.isModelSupported(modelPath, ctxSize) + } + // Fallback if method is not available + console.warn('isModelSupported method not available in llamacpp engine') + return 'YELLOW' // Conservative fallback + } catch (error) { + console.error(`Error checking model support for ${modelPath}:`, error) + return 'GREY' // Error state, assume not supported + } + } +} \ No newline at end of file diff --git a/web-app/src/services/models/types.ts b/web-app/src/services/models/types.ts new file mode 100644 index 000000000..97bbda11f --- /dev/null +++ b/web-app/src/services/models/types.ts @@ -0,0 +1,107 @@ +/** + * Models Service Types + */ + +import { SessionInfo, modelInfo } from '@janhq/core' +import { Model as CoreModel } from '@janhq/core' + +// Types for model catalog +export interface ModelQuant { + model_id: string + path: string + file_size: string +} + +export interface MMProjModel { + model_id: string + path: string + file_size: string +} + +export interface CatalogModel { + model_name: string + description: string + developer: string + downloads: number + num_quants: number + quants: ModelQuant[] + mmproj_models?: MMProjModel[] + num_mmproj: number + created_at?: string + readme?: string + tools?: boolean +} + +export type ModelCatalog = CatalogModel[] + +// HuggingFace repository information +export interface HuggingFaceRepo { + id: string + modelId: string + sha: string + downloads: number + likes: number + library_name?: string + tags: string[] + pipeline_tag?: string + createdAt: string + last_modified: string + private: boolean + disabled: boolean + gated: boolean | string + author: string + cardData?: { + license?: string + language?: string[] + datasets?: string[] + metrics?: string[] + } + siblings?: Array<{ + rfilename: string + size?: number + blobId?: string + lfs?: { + sha256: string + size: number + pointerSize: number + } + }> + readme?: string +} + +export interface ModelsService { + fetchModels(): Promise + fetchModelCatalog(): Promise + fetchHuggingFaceRepo(repoId: string, hfToken?: string): Promise + convertHfRepoToCatalogModel(repo: HuggingFaceRepo): CatalogModel + updateModel(model: Partial): Promise + pullModel( + id: string, + modelPath: string, + modelSha256?: string, + modelSize?: number, + mmprojPath?: string, + mmprojSha256?: string, + mmprojSize?: number + ): Promise + pullModelWithMetadata( + id: string, + modelPath: string, + mmprojPath?: string, + hfToken?: string + ): Promise + abortDownload(id: string): Promise + deleteModel(id: string): Promise + getActiveModels(provider?: string): Promise + stopModel(model: string, provider?: string): Promise + stopAllModels(): Promise + startModel(provider: ProviderObject, model: string): Promise + isToolSupported(modelId: string): Promise + checkMmprojExistsAndUpdateOffloadMMprojSetting( + modelId: string, + updateProvider?: (providerName: string, data: Partial) => void, + getProviderByName?: (providerName: string) => ModelProvider | undefined + ): Promise<{ exists: boolean; settingsUpdated: boolean }> + checkMmprojExists(modelId: string): Promise + isModelSupported(modelPath: string, ctxSize?: number): Promise<'RED' | 'YELLOW' | 'GREEN' | 'GREY'> +} \ No newline at end of file diff --git a/web-app/src/services/opener/default.ts b/web-app/src/services/opener/default.ts new file mode 100644 index 000000000..287e927b8 --- /dev/null +++ b/web-app/src/services/opener/default.ts @@ -0,0 +1,12 @@ +/** + * Default Opener Service - Generic implementation with minimal returns + */ + +import type { OpenerService } from './types' + +export class DefaultOpenerService implements OpenerService { + async revealItemInDir(path: string): Promise { + console.log('revealItemInDir called with path:', path) + // No-op - not implemented in default service + } +} \ No newline at end of file diff --git a/web-app/src/services/opener/tauri.ts b/web-app/src/services/opener/tauri.ts new file mode 100644 index 000000000..9c465e521 --- /dev/null +++ b/web-app/src/services/opener/tauri.ts @@ -0,0 +1,17 @@ +/** + * Tauri Opener Service - Desktop implementation + */ + +import { revealItemInDir } from '@tauri-apps/plugin-opener' +import { DefaultOpenerService } from './default' + +export class TauriOpenerService extends DefaultOpenerService { + async revealItemInDir(path: string): Promise { + try { + await revealItemInDir(path) + } catch (error) { + console.error('Error revealing item in directory in Tauri:', error) + throw error + } + } +} \ No newline at end of file diff --git a/web-app/src/services/opener/types.ts b/web-app/src/services/opener/types.ts new file mode 100644 index 000000000..21e0d17f0 --- /dev/null +++ b/web-app/src/services/opener/types.ts @@ -0,0 +1,8 @@ +/** + * Opener Service Types + * Types for opening/revealing files and folders + */ + +export interface OpenerService { + revealItemInDir(path: string): Promise +} \ No newline at end of file diff --git a/web-app/src/services/path/default.ts b/web-app/src/services/path/default.ts new file mode 100644 index 000000000..90ed46e82 --- /dev/null +++ b/web-app/src/services/path/default.ts @@ -0,0 +1,31 @@ +/** + * Default Path Service - Generic implementation with minimal returns + */ + +import type { PathService } from './types' + +export class DefaultPathService implements PathService { + sep(): string { + return '/' + } + + async join(...segments: string[]): Promise { + console.log('path.join called with segments:', segments) + return '' + } + + async dirname(path: string): Promise { + console.log('path.dirname called with path:', path) + return '' + } + + async basename(path: string): Promise { + console.log('path.basename called with path:', path) + return '' + } + + async extname(path: string): Promise { + console.log('path.extname called with path:', path) + return '' + } +} \ No newline at end of file diff --git a/web-app/src/services/path/tauri.ts b/web-app/src/services/path/tauri.ts new file mode 100644 index 000000000..80b5808c9 --- /dev/null +++ b/web-app/src/services/path/tauri.ts @@ -0,0 +1,58 @@ +/** + * Tauri Path Service - Desktop implementation + */ + +import { sep as getSep, join, dirname, basename, extname } from '@tauri-apps/api/path' +import { DefaultPathService } from './default' + +export class TauriPathService extends DefaultPathService { + sep(): string { + try { + // Note: sep() is synchronous in Tauri v2 (unlike other path functions) + return getSep() as unknown as string + } catch (error) { + console.error('Error getting path separator in Tauri:', error) + return '/' + } + } + + async join(...segments: string[]): Promise { + try { + return await join(...segments) + } catch (error) { + console.error('Error joining paths in Tauri:', error) + return segments.join('/') + } + } + + async dirname(path: string): Promise { + try { + return await dirname(path) + } catch (error) { + console.error('Error getting dirname in Tauri:', error) + const lastSlash = path.lastIndexOf('/') + return lastSlash > 0 ? path.substring(0, lastSlash) : '.' + } + } + + async basename(path: string): Promise { + try { + return await basename(path) + } catch (error) { + console.error('Error getting basename in Tauri:', error) + const lastSlash = path.lastIndexOf('/') + return lastSlash >= 0 ? path.substring(lastSlash + 1) : path + } + } + + async extname(path: string): Promise { + try { + return await extname(path) + } catch (error) { + console.error('Error getting extname in Tauri:', error) + const lastDot = path.lastIndexOf('.') + const lastSlash = path.lastIndexOf('/') + return lastDot > lastSlash ? path.substring(lastDot) : '' + } + } +} \ No newline at end of file diff --git a/web-app/src/services/path/types.ts b/web-app/src/services/path/types.ts new file mode 100644 index 000000000..269adc1c9 --- /dev/null +++ b/web-app/src/services/path/types.ts @@ -0,0 +1,12 @@ +/** + * Path Service Types + * Types for filesystem path operations + */ + +export interface PathService { + sep(): string + join(...segments: string[]): Promise + dirname(path: string): Promise + basename(path: string): Promise + extname(path: string): Promise +} \ No newline at end of file diff --git a/web-app/src/services/path/web.ts b/web-app/src/services/path/web.ts new file mode 100644 index 000000000..724acb130 --- /dev/null +++ b/web-app/src/services/path/web.ts @@ -0,0 +1,40 @@ +/** + * Web Path Service - Web implementation + * Provides web-specific implementations for path operations + */ + +import type { PathService } from './types' + +export class WebPathService implements PathService { + sep(): string { + // Web fallback - assume unix-style paths + return '/' + } + + async join(...segments: string[]): Promise { + return segments + .filter(segment => segment && segment !== '') + .join('/') + .replace(/\/+/g, '/') // Remove double slashes + } + + async dirname(path: string): Promise { + const normalizedPath = path.replace(/\\/g, '/') + const lastSlash = normalizedPath.lastIndexOf('/') + if (lastSlash === -1) return '.' + if (lastSlash === 0) return '/' + return normalizedPath.substring(0, lastSlash) + } + + async basename(path: string): Promise { + const normalizedPath = path.replace(/\\/g, '/') + return normalizedPath.split('/').pop() || '' + } + + async extname(path: string): Promise { + const basename = await this.basename(path) + const lastDot = basename.lastIndexOf('.') + if (lastDot === -1 || lastDot === 0) return '' + return basename.substring(lastDot) + } +} \ No newline at end of file diff --git a/web-app/src/services/providers.ts b/web-app/src/services/providers.ts deleted file mode 100644 index a036c9148..000000000 --- a/web-app/src/services/providers.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { models as providerModels } from 'token.js' -import { predefinedProviders } from '@/consts/providers' -import { EngineManager, SettingComponentProps } from '@janhq/core' -import { ModelCapabilities } from '@/types/models' -import { modelSettings } from '@/lib/predefined' -import { fetchModels, isToolSupported } from './models' -import { ExtensionManager } from '@/lib/extension' -import { fetch as fetchTauri } from '@tauri-apps/plugin-http' - -export const getProviders = async (): Promise => { - const builtinProviders = predefinedProviders.map((provider) => { - let models = provider.models as Model[] - if (Object.keys(providerModels).includes(provider.provider)) { - const builtInModels = providerModels[ - provider.provider as unknown as keyof typeof providerModels - ].models as unknown as string[] - - if (Array.isArray(builtInModels)) - models = builtInModels.map((model) => { - const modelManifest = models.find((e) => e.id === model) - // TODO: Check chat_template for tool call support - const capabilities = [ - ModelCapabilities.COMPLETION, - ( - providerModels[ - provider.provider as unknown as keyof typeof providerModels - ].supportsToolCalls as unknown as string[] - ).includes(model) - ? ModelCapabilities.TOOLS - : undefined, - ].filter(Boolean) as string[] - return { - ...(modelManifest ?? { id: model, name: model }), - capabilities, - } as Model - }) - } - - return { - ...provider, - models, - } - }) - - const runtimeProviders: ModelProvider[] = [] - for (const [providerName, value] of EngineManager.instance().engines) { - const models = (await fetchModels()) ?? [] - const provider: ModelProvider = { - active: false, - persist: true, - provider: providerName, - base_url: - 'inferenceUrl' in value - ? (value.inferenceUrl as string).replace('/chat/completions', '') - : '', - settings: (await value.getSettings()).map((setting) => { - return { - key: setting.key, - title: setting.title, - description: setting.description, - controller_type: setting.controllerType as unknown, - controller_props: setting.controllerProps as unknown, - } - }) as ProviderSetting[], - models: await Promise.all( - models.map( - async (model) => - ({ - id: model.id, - model: model.id, - name: model.name, - description: model.description, - capabilities: - 'capabilities' in model - ? (model.capabilities as string[]) - : (await isToolSupported(model.id)) - ? [ModelCapabilities.TOOLS] - : [], - provider: providerName, - settings: Object.values(modelSettings).reduce( - (acc, setting) => { - let value = setting.controller_props.value - if (setting.key === 'ctx_len') { - value = 8192 // Default context length for Llama.cpp models - } - acc[setting.key] = { - ...setting, - controller_props: { - ...setting.controller_props, - value: value, - }, - } - return acc - }, - {} as Record - ), - }) as Model - ) - ), - } - runtimeProviders.push(provider) - } - - return runtimeProviders.concat(builtinProviders as ModelProvider[]) -} - -/** - * Fetches models from a provider's API endpoint - * Always uses Tauri's HTTP client to bypass CORS issues - * @param provider The provider object containing base_url and api_key - * @returns Promise Array of model IDs - */ -export const fetchModelsFromProvider = async ( - provider: ModelProvider -): Promise => { - if (!provider.base_url) { - throw new Error('Provider must have base_url configured') - } - - try { - const headers: Record = { - 'Content-Type': 'application/json', - } - - // Only add authentication headers if API key is provided - if (provider.api_key) { - headers['x-api-key'] = provider.api_key - headers['Authorization'] = `Bearer ${provider.api_key}` - } - - // Always use Tauri's fetch to avoid CORS issues - const response = await fetchTauri(`${provider.base_url}/models`, { - method: 'GET', - headers, - }) - - if (!response.ok) { - // Provide more specific error messages based on status code - if (response.status === 401) { - throw new Error( - `Authentication failed: API key is required or invalid for ${provider.provider}` - ) - } else if (response.status === 403) { - throw new Error( - `Access forbidden: Check your API key permissions for ${provider.provider}` - ) - } else if (response.status === 404) { - throw new Error( - `Models endpoint not found for ${provider.provider}. Check the base URL configuration.` - ) - } else { - throw new Error( - `Failed to fetch models from ${provider.provider}: ${response.status} ${response.statusText}` - ) - } - } - - const data = await response.json() - - // Handle different response formats that providers might use - if (data.data && Array.isArray(data.data)) { - // OpenAI format: { data: [{ id: "model-id" }, ...] } - return data.data.map((model: { id: string }) => model.id).filter(Boolean) - } else if (Array.isArray(data)) { - // Direct array format: ["model-id1", "model-id2", ...] - return data - .filter(Boolean) - .map((model) => - typeof model === 'object' && 'id' in model ? model.id : model - ) - } else if (data.models && Array.isArray(data.models)) { - // Alternative format: { models: [...] } - return data.models - .map((model: string | { id: string }) => - typeof model === 'string' ? model : model.id - ) - .filter(Boolean) - } else { - console.warn('Unexpected response format from provider API:', data) - return [] - } - } catch (error) { - console.error('Error fetching models from provider:', error) - - const structuredErrorPrefixes = [ - 'Authentication failed', - 'Access forbidden', - 'Models endpoint not found', - 'Failed to fetch models from' - ] - - if (error instanceof Error && - structuredErrorPrefixes.some(prefix => (error as Error).message.startsWith(prefix))) { - throw new Error(error.message) - } - - // Provide helpful error message for network issues - if (error instanceof Error && error.message.includes('fetch')) { - throw new Error( - `Cannot connect to ${provider.provider} at ${provider.base_url}. Please check that the service is running and accessible.` - ) - } - - // Generic fallback - throw new Error( - `Unexpected error while fetching models from ${provider.provider}: ${error instanceof Error ? error.message : 'Unknown error'}` - ) - } -} - -/** - * Update the settings of a provider extension. - * TODO: Later on we don't retrieve this using provider name - * @param providerName - * @param settings - */ -export const updateSettings = async ( - providerName: string, - settings: ProviderSetting[] -): Promise => { - return ExtensionManager.getInstance() - .getEngine(providerName) - ?.updateSettings( - settings.map((setting) => ({ - ...setting, - controllerProps: { - ...setting.controller_props, - value: - setting.controller_props.value !== undefined - ? setting.controller_props.value - : '', - }, - controllerType: setting.controller_type, - })) as SettingComponentProps[] - ) -} diff --git a/web-app/src/services/providers/default.ts b/web-app/src/services/providers/default.ts new file mode 100644 index 000000000..241138d28 --- /dev/null +++ b/web-app/src/services/providers/default.ts @@ -0,0 +1,25 @@ +/** + * Default Providers Service - Generic implementation with minimal returns + */ + +import type { ProvidersService } from './types' + +export class DefaultProvidersService implements ProvidersService { + async getProviders(): Promise { + return [] + } + + async fetchModelsFromProvider(provider: ModelProvider): Promise { + console.log('fetchModelsFromProvider called with provider:', provider) + return [] + } + + async updateSettings(providerName: string, settings: ProviderSetting[]): Promise { + console.log('updateSettings called:', { providerName, settings }) + // No-op - not implemented in default service + } + + fetch(): typeof fetch { + return fetch + } +} \ No newline at end of file diff --git a/web-app/src/services/providers/tauri.ts b/web-app/src/services/providers/tauri.ts new file mode 100644 index 000000000..5c5103b20 --- /dev/null +++ b/web-app/src/services/providers/tauri.ts @@ -0,0 +1,210 @@ +/** + * Tauri Providers Service - Desktop implementation + */ + +import { models as providerModels } from 'token.js' +import { predefinedProviders } from '@/consts/providers' +import { EngineManager, SettingComponentProps } from '@janhq/core' +import { ModelCapabilities } from '@/types/models' +import { modelSettings } from '@/lib/predefined' +import { ExtensionManager } from '@/lib/extension' +import { fetch as fetchTauri } from '@tauri-apps/plugin-http' +import { DefaultProvidersService } from './default' + +export class TauriProvidersService extends DefaultProvidersService { + fetch(): typeof fetch { + // Tauri implementation uses Tauri's fetch to avoid CORS issues + return fetchTauri as typeof fetch + } + + async getProviders(): Promise { + try { + const builtinProviders = predefinedProviders.map((provider) => { + let models = provider.models as Model[] + if (Object.keys(providerModels).includes(provider.provider)) { + const builtInModels = providerModels[ + provider.provider as unknown as keyof typeof providerModels + ].models as unknown as string[] + + if (Array.isArray(builtInModels)) + models = builtInModels.map((model) => { + const modelManifest = models.find((e) => e.id === model) + // TODO: Check chat_template for tool call support + const capabilities = [ + ModelCapabilities.COMPLETION, + ( + providerModels[ + provider.provider as unknown as keyof typeof providerModels + ].supportsToolCalls as unknown as string[] + ).includes(model) + ? ModelCapabilities.TOOLS + : undefined, + ].filter(Boolean) as string[] + return { + ...(modelManifest ?? { id: model, name: model }), + capabilities, + } as Model + }) + } + + return { + ...provider, + models, + } + }) + + const runtimeProviders: ModelProvider[] = [] + for (const [providerName, value] of EngineManager.instance().engines) { + const models = (await value.list()) ?? [] + const provider: ModelProvider = { + active: false, + persist: true, + provider: providerName, + base_url: + 'inferenceUrl' in value + ? (value.inferenceUrl as string).replace('/chat/completions', '') + : '', + settings: (await value.getSettings()).map((setting) => { + return { + key: setting.key, + title: setting.title, + description: setting.description, + controller_type: setting.controllerType as unknown, + controller_props: setting.controllerProps as unknown, + } + }) as ProviderSetting[], + models: await Promise.all( + models.map( + async (model) => + ({ + id: model.id, + model: model.id, + name: model.name, + description: model.description, + capabilities: + 'capabilities' in model + ? (model.capabilities as string[]) + : (await value.isToolSupported(model.id)) + ? [ModelCapabilities.TOOLS] + : [], + provider: providerName, + settings: Object.values(modelSettings).reduce( + (acc, setting) => { + let value = setting.controller_props.value + if (setting.key === 'ctx_len') { + value = 8192 // Default context length for Llama.cpp models + } + acc[setting.key] = { + ...setting, + controller_props: { + ...setting.controller_props, + value: value, + }, + } + return acc + }, + {} as Record + ), + }) as Model + ) + ), + } + runtimeProviders.push(provider) + } + + return runtimeProviders.concat(builtinProviders as ModelProvider[]) + } catch (error) { + console.error('Error getting providers in Tauri:', error) + return [] + } + } + + async fetchModelsFromProvider(provider: ModelProvider): Promise { + if (!provider.base_url) { + throw new Error('Provider must have base_url configured') + } + + try { + const headers: Record = { + 'Content-Type': 'application/json', + } + + // Only add authentication headers if API key is provided + if (provider.api_key) { + headers['x-api-key'] = provider.api_key + headers['Authorization'] = `Bearer ${provider.api_key}` + } + + // Always use Tauri's fetch to avoid CORS issues + const response = await fetchTauri(`${provider.base_url}/models`, { + method: 'GET', + headers, + }) + + if (!response.ok) { + throw new Error( + `Failed to fetch models: ${response.status} ${response.statusText}` + ) + } + + const data = await response.json() + + // Handle different response formats that providers might use + if (data.data && Array.isArray(data.data)) { + // OpenAI format: { data: [{ id: "model-id" }, ...] } + return data.data.map((model: { id: string }) => model.id).filter(Boolean) + } else if (Array.isArray(data)) { + // Direct array format: ["model-id1", "model-id2", ...] + return data + .filter(Boolean) + .map((model) => + typeof model === 'object' && 'id' in model ? model.id : model + ) + } else if (data.models && Array.isArray(data.models)) { + // Alternative format: { models: [...] } + return data.models + .map((model: string | { id: string }) => + typeof model === 'string' ? model : model.id + ) + .filter(Boolean) + } else { + console.warn('Unexpected response format from provider API:', data) + return [] + } + } catch (error) { + console.error('Error fetching models from provider:', error) + + // Provide helpful error message + if (error instanceof Error && error.message.includes('fetch')) { + throw new Error( + `Cannot connect to ${provider.provider} at ${provider.base_url}. Please check that the service is running and accessible.` + ) + } + + throw error + } + } + + async updateSettings(providerName: string, settings: ProviderSetting[]): Promise { + try { + return ExtensionManager.getInstance() + .getEngine(providerName) + ?.updateSettings( + settings.map((setting) => ({ + ...setting, + controllerProps: { + ...setting.controller_props, + value: + setting.controller_props.value !== undefined + ? setting.controller_props.value + : '', + }, + controllerType: setting.controller_type, + })) as SettingComponentProps[] + ) + } catch (error) { + console.error('Error updating settings in Tauri:', error) + throw error + } + } +} \ No newline at end of file diff --git a/web-app/src/services/providers/types.ts b/web-app/src/services/providers/types.ts new file mode 100644 index 000000000..1c6d81d90 --- /dev/null +++ b/web-app/src/services/providers/types.ts @@ -0,0 +1,10 @@ +/** + * Providers Service Types + */ + +export interface ProvidersService { + getProviders(): Promise + fetchModelsFromProvider(provider: ModelProvider): Promise + updateSettings(providerName: string, settings: ProviderSetting[]): Promise + fetch(): typeof fetch +} \ No newline at end of file diff --git a/web-app/src/services/providers/web.ts b/web-app/src/services/providers/web.ts new file mode 100644 index 000000000..30fe71366 --- /dev/null +++ b/web-app/src/services/providers/web.ts @@ -0,0 +1,206 @@ +/** + * Web Providers Service - Web implementation + */ + +import { models as providerModels } from 'token.js' +import { predefinedProviders } from '@/consts/providers' +import { EngineManager, SettingComponentProps } from '@janhq/core' +import { ModelCapabilities } from '@/types/models' +import { modelSettings } from '@/lib/predefined' +import { ExtensionManager } from '@/lib/extension' +import type { ProvidersService } from './types' +import { PlatformFeatures } from '@/lib/platform/const' +import { PlatformFeature } from '@/lib/platform/types' + +export class WebProvidersService implements ProvidersService { + async getProviders(): Promise { + const runtimeProviders: ModelProvider[] = [] + for (const [providerName, value] of EngineManager.instance().engines) { + const models = (await value.list()) ?? [] + const provider: ModelProvider = { + active: false, + persist: true, + provider: providerName, + base_url: + 'inferenceUrl' in value + ? (value.inferenceUrl as string).replace('/chat/completions', '') + : '', + settings: (await value.getSettings()).map((setting) => { + return { + key: setting.key, + title: setting.title, + description: setting.description, + controller_type: setting.controllerType as unknown, + controller_props: setting.controllerProps as unknown, + } + }) as ProviderSetting[], + models: await Promise.all( + models.map( + async (model) => + ({ + id: model.id, + model: model.id, + name: model.name, + description: model.description, + capabilities: + 'capabilities' in model + ? (model.capabilities as string[]) + : (await value.isToolSupported(model.id)) + ? [ModelCapabilities.TOOLS] + : [], + provider: providerName, + settings: Object.values(modelSettings).reduce( + (acc, setting) => { + let value = setting.controller_props.value + if (setting.key === 'ctx_len') { + value = 8192 // Default context length for Llama.cpp models + } + acc[setting.key] = { + ...setting, + controller_props: { + ...setting.controller_props, + value: value, + }, + } + return acc + }, + {} as Record + ), + }) as Model + ) + ), + } + runtimeProviders.push(provider) + } + + if (!PlatformFeatures[PlatformFeature.DEFAULT_PROVIDERS]) { + return runtimeProviders + } + + const builtinProviders = predefinedProviders.map((provider) => { + let models = provider.models as Model[] + if (Object.keys(providerModels).includes(provider.provider)) { + const builtInModels = providerModels[ + provider.provider as unknown as keyof typeof providerModels + ].models as unknown as string[] + + if (Array.isArray(builtInModels)) { + models = builtInModels.map((model) => { + const modelManifest = models.find((e) => e.id === model) + // TODO: Check chat_template for tool call support + const capabilities = [ + ModelCapabilities.COMPLETION, + ( + providerModels[ + provider.provider as unknown as keyof typeof providerModels + ].supportsToolCalls as unknown as string[] + ).includes(model) + ? ModelCapabilities.TOOLS + : undefined, + ].filter(Boolean) as string[] + return { + ...(modelManifest ?? { id: model, name: model }), + capabilities, + } as Model + }) + } + } + + return { + ...provider, + models, + } + }) + + return runtimeProviders.concat(builtinProviders as ModelProvider[]) + } + + async fetchModelsFromProvider(provider: ModelProvider): Promise { + if (!provider.base_url) { + throw new Error('Provider must have base_url configured') + } + + try { + const headers: Record = { + 'Content-Type': 'application/json', + } + + // Only add authentication headers if API key is provided + if (provider.api_key) { + headers['x-api-key'] = provider.api_key + headers['Authorization'] = `Bearer ${provider.api_key}` + } + + // Use browser's native fetch for web environment + const response = await fetch(`${provider.base_url}/models`, { + method: 'GET', + headers, + }) + + if (!response.ok) { + throw new Error( + `Cannot connect to ${provider.provider} at ${provider.base_url}. Please check that the service is running and accessible.` + ) + } + + const data = await response.json() + + // Handle different response formats that providers might use + if (data.data && Array.isArray(data.data)) { + // OpenAI format: { data: [{ id: "model-id" }, ...] } + return data.data.map((model: { id: string }) => model.id).filter(Boolean) + } else if (Array.isArray(data)) { + // Direct array format: ["model-id1", "model-id2", ...] + return data + .filter(Boolean) + .map((model) => + typeof model === 'object' && 'id' in model ? model.id : model + ) + } else if (data.models && Array.isArray(data.models)) { + // Alternative format: { models: [...] } + return data.models + .map((model: string | { id: string }) => + typeof model === 'string' ? model : model.id + ) + .filter(Boolean) + } else { + console.warn('Unexpected response format from provider API:', data) + return [] + } + } catch (error) { + console.error('Error fetching models from provider:', error) + + // Provide helpful error message for any connection errors + if (error instanceof Error && error.message.includes('Cannot connect')) { + throw error + } + + throw new Error( + `Cannot connect to ${provider.provider} at ${provider.base_url}. Please check that the service is running and accessible.` + ) + } + } + + async updateSettings(providerName: string, settings: ProviderSetting[]): Promise { + await ExtensionManager.getInstance() + .getEngine(providerName) + ?.updateSettings( + settings.map((setting) => ({ + ...setting, + controllerProps: { + ...setting.controller_props, + value: + setting.controller_props.value !== undefined + ? setting.controller_props.value + : '', + }, + controllerType: setting.controller_type, + })) as SettingComponentProps[] + ) + } + + fetch(): typeof fetch { + // Web implementation uses regular fetch + return fetch + } +} \ No newline at end of file diff --git a/web-app/src/services/theme/default.ts b/web-app/src/services/theme/default.ts new file mode 100644 index 000000000..421cc102e --- /dev/null +++ b/web-app/src/services/theme/default.ts @@ -0,0 +1,21 @@ +/** + * Default Theme Service - Generic implementation with minimal returns + */ + +import type { ThemeService, ThemeMode } from './types' + +export class DefaultThemeService implements ThemeService { + async setTheme(theme: ThemeMode): Promise { + console.log('setTheme called with theme:', theme) + // No-op - not implemented in default service + } + + getCurrentWindow() { + return { + setTheme: (theme: ThemeMode): Promise => { + console.log('window.setTheme called with theme:', theme) + return Promise.resolve() + } + } + } +} \ No newline at end of file diff --git a/web-app/src/services/theme/tauri.ts b/web-app/src/services/theme/tauri.ts new file mode 100644 index 000000000..0f2f1f64d --- /dev/null +++ b/web-app/src/services/theme/tauri.ts @@ -0,0 +1,27 @@ +/** + * Tauri Theme Service - Desktop implementation + */ + +import { getCurrentWindow, Theme } from '@tauri-apps/api/window' +import type { ThemeMode } from './types' +import { DefaultThemeService } from './default' + +export class TauriThemeService extends DefaultThemeService { + async setTheme(theme: ThemeMode): Promise { + try { + const tauriTheme = theme as Theme | null + await getCurrentWindow().setTheme(tauriTheme) + } catch (error) { + console.error('Error setting theme in Tauri:', error) + throw error + } + } + + getCurrentWindow() { + return { + setTheme: (theme: ThemeMode): Promise => { + return this.setTheme(theme) + } + } + } +} \ No newline at end of file diff --git a/web-app/src/services/theme/types.ts b/web-app/src/services/theme/types.ts new file mode 100644 index 000000000..abcf8fc44 --- /dev/null +++ b/web-app/src/services/theme/types.ts @@ -0,0 +1,10 @@ +/** + * Theme Service Types + */ + +export type ThemeMode = 'light' | 'dark' | null + +export interface ThemeService { + setTheme(theme: ThemeMode): Promise + getCurrentWindow(): { setTheme: (theme: ThemeMode) => Promise } +} \ No newline at end of file diff --git a/web-app/src/services/theme/web.ts b/web-app/src/services/theme/web.ts new file mode 100644 index 000000000..39b1ff903 --- /dev/null +++ b/web-app/src/services/theme/web.ts @@ -0,0 +1,25 @@ +/** + * Web Theme Service - Web implementation + */ + +import type { ThemeService, ThemeMode } from './types' + +export class WebThemeService implements ThemeService { + async setTheme(theme: ThemeMode): Promise { + console.log('Setting theme in web mode:', theme) + // In web mode, we can apply theme by setting CSS classes or data attributes + if (theme) { + document.documentElement.setAttribute('data-theme', theme) + } else { + document.documentElement.removeAttribute('data-theme') + } + } + + getCurrentWindow() { + return { + setTheme: (theme: ThemeMode): Promise => { + return this.setTheme(theme) + } + } + } +} \ No newline at end of file diff --git a/web-app/src/services/threads.ts b/web-app/src/services/threads.ts deleted file mode 100644 index 2e2fc693f..000000000 --- a/web-app/src/services/threads.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { defaultAssistant } from '@/hooks/useAssistant' -import { ExtensionManager } from '@/lib/extension' -import { ConversationalExtension, ExtensionTypeEnum } from '@janhq/core' - -/** - * Fetches all threads from the conversational extension. - * @returns {Promise} A promise that resolves to an array of threads. - */ -export const fetchThreads = async (): Promise => { - return ( - ExtensionManager.getInstance() - .get(ExtensionTypeEnum.Conversational) - ?.listThreads() - .then((threads) => { - if (!Array.isArray(threads)) return [] - - return threads.map((e) => { - return { - ...e, - updated: - typeof e.updated === 'number' && e.updated > 1e12 - ? Math.floor(e.updated / 1000) - : (e.updated ?? 0), - order: e.metadata?.order, - isFavorite: e.metadata?.is_favorite, - model: { - id: e.assistants?.[0]?.model?.id, - provider: e.assistants?.[0]?.model?.engine, - }, - assistants: e.assistants ?? [defaultAssistant], - } as Thread - }) - }) - ?.catch((e) => { - console.error('Error fetching threads:', e) - return [] - }) ?? [] - ) -} - -/** - * Creates a new thread using the conversational extension. - * @param thread - The thread object to create. - * @returns {Promise} A promise that resolves to the created thread. - */ -export const createThread = async (thread: Thread): Promise => { - return ( - ExtensionManager.getInstance() - .get(ExtensionTypeEnum.Conversational) - ?.createThread({ - ...thread, - assistants: [ - { - ...(thread.assistants?.[0] ?? defaultAssistant), - model: { - id: thread.model?.id ?? '*', - engine: thread.model?.provider ?? 'llamacpp', - }, - }, - ], - metadata: { - order: thread.order, - }, - }) - .then((e) => { - return { - ...e, - updated: e.updated, - model: { - id: e.assistants?.[0]?.model?.id, - provider: e.assistants?.[0]?.model?.engine, - }, - order: e.metadata?.order ?? thread.order, - assistants: e.assistants ?? [defaultAssistant], - } as Thread - }) - .catch(() => thread) ?? thread - ) -} - -/** - * Updates an existing thread using the conversational extension. - * @param thread - The thread object to update. - */ -export const updateThread = (thread: Thread) => { - return ExtensionManager.getInstance() - .get(ExtensionTypeEnum.Conversational) - ?.modifyThread({ - ...thread, - assistants: thread.assistants?.map((e) => { - return { - model: { - id: thread.model?.id ?? '*', - engine: thread.model?.provider ?? 'llamacpp', - }, - id: e.id, - name: e.name, - instructions: e.instructions, - } - }) ?? [ - { - model: { - id: thread.model?.id ?? '*', - engine: thread.model?.provider ?? 'llamacpp', - }, - id: 'jan', - name: 'Jan', - }, - ], - metadata: { - is_favorite: thread.isFavorite, - order: thread.order, - }, - object: 'thread', - created: Date.now() / 1000, - updated: Date.now() / 1000, - }) -} - -/** - * Deletes a thread using the conversational extension. - * @param threadId - The ID of the thread to delete. - * @returns - */ -export const deleteThread = (threadId: string) => { - return ExtensionManager.getInstance() - .get(ExtensionTypeEnum.Conversational) - ?.deleteThread(threadId) -} diff --git a/web-app/src/services/threads/default.ts b/web-app/src/services/threads/default.ts new file mode 100644 index 000000000..af5f213d5 --- /dev/null +++ b/web-app/src/services/threads/default.ts @@ -0,0 +1,118 @@ +/** + * Default Threads Service - Web implementation + */ + +import { defaultAssistant } from '@/hooks/useAssistant' +import { ExtensionManager } from '@/lib/extension' +import { ConversationalExtension, ExtensionTypeEnum } from '@janhq/core' +import type { ThreadsService } from './types' + +export class DefaultThreadsService implements ThreadsService { + async fetchThreads(): Promise { + return ( + ExtensionManager.getInstance() + .get(ExtensionTypeEnum.Conversational) + ?.listThreads() + .then((threads) => { + if (!Array.isArray(threads)) return [] + + return threads.map((e) => { + return { + ...e, + updated: + typeof e.updated === 'number' && e.updated > 1e12 + ? Math.floor(e.updated / 1000) + : (e.updated ?? 0), + order: e.metadata?.order, + isFavorite: e.metadata?.is_favorite, + model: { + id: e.assistants?.[0]?.model?.id, + provider: e.assistants?.[0]?.model?.engine, + }, + assistants: e.assistants ?? [defaultAssistant], + } as Thread + }) + }) + ?.catch((e) => { + console.error('Error fetching threads:', e) + return [] + }) ?? [] + ) + } + + async createThread(thread: Thread): Promise { + return ( + ExtensionManager.getInstance() + .get(ExtensionTypeEnum.Conversational) + ?.createThread({ + ...thread, + assistants: [ + { + ...(thread.assistants?.[0] ?? defaultAssistant), + model: { + id: thread.model?.id ?? '*', + engine: thread.model?.provider ?? 'llamacpp', + }, + }, + ], + metadata: { + order: thread.order, + }, + }) + .then((e) => { + return { + ...e, + updated: e.updated, + model: { + id: e.assistants?.[0]?.model?.id, + provider: e.assistants?.[0]?.model?.engine, + }, + order: e.metadata?.order ?? thread.order, + assistants: e.assistants ?? [defaultAssistant], + } as Thread + }) + .catch(() => thread) ?? thread + ) + } + + async updateThread(thread: Thread): Promise { + await ExtensionManager.getInstance() + .get(ExtensionTypeEnum.Conversational) + ?.modifyThread({ + ...thread, + assistants: thread.assistants?.map((e) => { + return { + model: { + id: thread.model?.id ?? '*', + engine: thread.model?.provider ?? 'llamacpp', + }, + id: e.id, + name: e.name, + instructions: e.instructions, + } + }) ?? [ + { + model: { + id: thread.model?.id ?? '*', + engine: thread.model?.provider ?? 'llamacpp', + }, + id: 'jan', + name: 'Jan', + }, + ], + metadata: { + is_favorite: thread.isFavorite, + order: thread.order, + }, + object: 'thread', + created: Date.now() / 1000, + updated: Date.now() / 1000, + }) + } + + async deleteThread(threadId: string): Promise { + await ExtensionManager.getInstance() + .get(ExtensionTypeEnum.Conversational) + ?.deleteThread(threadId) + } +} \ No newline at end of file diff --git a/web-app/src/services/threads/types.ts b/web-app/src/services/threads/types.ts new file mode 100644 index 000000000..d0ce195cc --- /dev/null +++ b/web-app/src/services/threads/types.ts @@ -0,0 +1,10 @@ +/** + * Threads Service Types + */ + +export interface ThreadsService { + fetchThreads(): Promise + createThread(thread: Thread): Promise + updateThread(thread: Thread): Promise + deleteThread(threadId: string): Promise +} \ No newline at end of file diff --git a/web-app/src/services/updater/default.ts b/web-app/src/services/updater/default.ts new file mode 100644 index 000000000..b648c5622 --- /dev/null +++ b/web-app/src/services/updater/default.ts @@ -0,0 +1,22 @@ +/** + * Default Updater Service - Generic implementation with minimal returns + */ + +import type { UpdaterService, UpdateInfo, UpdateProgressEvent } from './types' + +export class DefaultUpdaterService implements UpdaterService { + async check(): Promise { + return null + } + + async installAndRestart(): Promise { + // No-op + } + + async downloadAndInstallWithProgress( + progressCallback: (event: UpdateProgressEvent) => void + ): Promise { + console.log('downloadAndInstallWithProgress called with callback:', typeof progressCallback) + // No-op for non-Tauri platforms + } +} \ No newline at end of file diff --git a/web-app/src/services/updater/tauri.ts b/web-app/src/services/updater/tauri.ts new file mode 100644 index 000000000..1db1ad294 --- /dev/null +++ b/web-app/src/services/updater/tauri.ts @@ -0,0 +1,63 @@ +/** + * Tauri Updater Service - Desktop implementation + */ + +import { check, Update } from '@tauri-apps/plugin-updater' +import type { UpdateInfo, UpdateProgressEvent } from './types' +import { DefaultUpdaterService } from './default' + +export class TauriUpdaterService extends DefaultUpdaterService { + async check(): Promise { + try { + const update: Update | null = await check() + + if (!update) return null + + return { + version: update.version, + date: update.date, + body: update.body, + } + } catch (error) { + console.error('Error checking for updates in Tauri:', error) + return null + } + } + + async installAndRestart(): Promise { + try { + const update = await check() + if (update) { + await update.downloadAndInstall() + // Note: Auto-restart happens after installation + } + } catch (error) { + console.error('Error installing update in Tauri:', error) + throw error + } + } + + async downloadAndInstallWithProgress( + progressCallback: (event: UpdateProgressEvent) => void + ): Promise { + try { + const update = await check() + if (!update) { + throw new Error('No update available') + } + + // Use Tauri's downloadAndInstall with progress callback + await update.downloadAndInstall((event) => { + try { + // Forward the event to the callback + progressCallback(event as UpdateProgressEvent) + } catch (callbackError) { + console.warn('Error in download progress callback:', callbackError) + } + }) + } catch (error) { + console.error('Error downloading update with progress in Tauri:', error) + throw error + } + } +} \ No newline at end of file diff --git a/web-app/src/services/updater/types.ts b/web-app/src/services/updater/types.ts new file mode 100644 index 000000000..c61642666 --- /dev/null +++ b/web-app/src/services/updater/types.ts @@ -0,0 +1,27 @@ +/** + * Updater Service Types + * Types for application update operations + */ + +export interface UpdateInfo { + version: string + date?: string + body?: string + signature?: string +} + +export interface UpdateProgressEvent { + event: 'Started' | 'Progress' | 'Finished' + data?: { + contentLength?: number + chunkLength?: number + } +} + +export interface UpdaterService { + check(): Promise + installAndRestart(): Promise + downloadAndInstallWithProgress( + progressCallback: (event: UpdateProgressEvent) => void + ): Promise +} \ No newline at end of file diff --git a/web-app/src/services/window/default.ts b/web-app/src/services/window/default.ts new file mode 100644 index 000000000..08483743c --- /dev/null +++ b/web-app/src/services/window/default.ts @@ -0,0 +1,43 @@ +/** + * Default Window Service - Generic implementation with minimal returns + */ + +import type { WindowService, WindowConfig, WebviewWindowInstance } from './types' + +export class DefaultWindowService implements WindowService { + async createWebviewWindow(config: WindowConfig): Promise { + return { + label: config.label, + async close() { /* No-op */ }, + async show() { /* No-op */ }, + async hide() { /* No-op */ }, + async focus() { /* No-op */ }, + async setTitle(title: string) { + console.log('window.setTitle called with title:', title) + /* No-op */ + } + } + } + + async getWebviewWindowByLabel(label: string): Promise { + console.log('getWebviewWindowByLabel called with label:', label) + return null + } + + async openWindow(config: WindowConfig): Promise { + console.log('openWindow called with config:', config) + // No-op - not implemented in default service + } + + async openLogsWindow(): Promise { + // No-op + } + + async openSystemMonitorWindow(): Promise { + // No-op + } + + async openLocalApiServerLogsWindow(): Promise { + // No-op + } +} \ No newline at end of file diff --git a/web-app/src/services/window/tauri.ts b/web-app/src/services/window/tauri.ts new file mode 100644 index 000000000..56c038425 --- /dev/null +++ b/web-app/src/services/window/tauri.ts @@ -0,0 +1,142 @@ +/** + * Tauri Window Service - Desktop implementation + */ + +import { WebviewWindow } from '@tauri-apps/api/webviewWindow' +import type { WindowConfig, WebviewWindowInstance } from './types' +import { DefaultWindowService } from './default' + +export class TauriWindowService extends DefaultWindowService { + async createWebviewWindow(config: WindowConfig): Promise { + try { + const webviewWindow = new WebviewWindow(config.label, { + url: config.url, + title: config.title, + width: config.width, + height: config.height, + center: config.center, + resizable: config.resizable, + minimizable: config.minimizable, + maximizable: config.maximizable, + closable: config.closable, + fullscreen: config.fullscreen, + }) + + return { + label: config.label, + async close() { + await webviewWindow.close() + }, + async show() { + await webviewWindow.show() + }, + async hide() { + await webviewWindow.hide() + }, + async focus() { + await webviewWindow.setFocus() + }, + async setTitle(title: string) { + await webviewWindow.setTitle(title) + } + } + } catch (error) { + console.error('Error creating Tauri window:', error) + throw error + } + } + + async getWebviewWindowByLabel(label: string): Promise { + try { + const existingWindow = await WebviewWindow.getByLabel(label) + + if (existingWindow) { + return { + label: label, + async close() { + await existingWindow.close() + }, + async show() { + await existingWindow.show() + }, + async hide() { + await existingWindow.hide() + }, + async focus() { + await existingWindow.setFocus() + }, + async setTitle(title: string) { + await existingWindow.setTitle(title) + } + } + } + + return null + } catch (error) { + console.error('Error getting Tauri window by label:', error) + return null + } + } + + async openWindow(config: WindowConfig): Promise { + // Check if window already exists first + const existing = await this.getWebviewWindowByLabel(config.label) + if (existing) { + await existing.show() + await existing.focus() + } else { + await this.createWebviewWindow(config) + } + } + + async openLogsWindow(): Promise { + try { + await this.openWindow({ + url: '/logs', + label: 'logs-app-window', + title: 'App Logs - Jan', + width: 800, + height: 600, + resizable: true, + center: true, + }) + } catch (error) { + console.error('Error opening logs window in Tauri:', error) + throw error + } + } + + async openSystemMonitorWindow(): Promise { + try { + await this.openWindow({ + url: '/system-monitor', + label: 'system-monitor-window', + title: 'System Monitor - Jan', + width: 1000, + height: 700, + resizable: true, + center: true, + }) + } catch (error) { + console.error('Error opening system monitor window in Tauri:', error) + throw error + } + } + + async openLocalApiServerLogsWindow(): Promise { + try { + await this.openWindow({ + url: '/local-api-server/logs', + label: 'logs-window-local-api-server', + title: 'Local API Server Logs - Jan', + width: 800, + height: 600, + resizable: true, + center: true, + }) + } catch (error) { + console.error('Error opening local API server logs window in Tauri:', error) + throw error + } + } +} \ No newline at end of file diff --git a/web-app/src/services/window/types.ts b/web-app/src/services/window/types.ts new file mode 100644 index 000000000..029f008aa --- /dev/null +++ b/web-app/src/services/window/types.ts @@ -0,0 +1,35 @@ +/** + * Window Service Types + */ + +export interface WindowConfig { + url: string + label: string + title?: string + width?: number + height?: number + center?: boolean + resizable?: boolean + minimizable?: boolean + maximizable?: boolean + closable?: boolean + fullscreen?: boolean +} + +export interface WebviewWindowInstance { + label: string + close(): Promise + show(): Promise + hide(): Promise + focus(): Promise + setTitle(title: string): Promise +} + +export interface WindowService { + createWebviewWindow(config: WindowConfig): Promise + getWebviewWindowByLabel(label: string): Promise + openWindow(config: WindowConfig): Promise + openLogsWindow(): Promise + openSystemMonitorWindow(): Promise + openLocalApiServerLogsWindow(): Promise +} \ No newline at end of file diff --git a/web-app/src/services/window/web.ts b/web-app/src/services/window/web.ts new file mode 100644 index 000000000..8cc01b8cb --- /dev/null +++ b/web-app/src/services/window/web.ts @@ -0,0 +1,64 @@ +/** + * Web Window Service - Web implementation + */ + +import type { WindowService, WindowConfig, WebviewWindowInstance } from './types' + +export class WebWindowService implements WindowService { + async createWebviewWindow(config: WindowConfig): Promise { + console.log('Creating window in web mode:', config) + + // Web implementation - open in new tab/window + const newWindow = window.open(config.url, config.label, + `width=${config.width || 800},height=${config.height || 600},resizable=${config.resizable !== false ? 'yes' : 'no'}` + ) + + if (!newWindow) { + throw new Error('Failed to create window - popup blocked?') + } + + return { + label: config.label, + async close() { + newWindow.close() + }, + async show() { + newWindow.focus() + }, + async hide() { + // Can't really hide a window in web, just minimize focus + console.log('Hide not supported in web mode') + }, + async focus() { + newWindow.focus() + }, + async setTitle(title: string) { + if (newWindow.document) { + newWindow.document.title = title + } + } + } + } + + async getWebviewWindowByLabel(label: string): Promise { + console.log('Getting window by label in web mode:', label) + // Web implementation can't track windows across sessions + return null + } + + async openWindow(config: WindowConfig): Promise { + await this.createWebviewWindow(config) + } + + async openLogsWindow(): Promise { + console.warn('Cannot open logs window in web environment') + } + + async openSystemMonitorWindow(): Promise { + console.warn('Cannot open system monitor window in web environment') + } + + async openLocalApiServerLogsWindow(): Promise { + console.warn('Cannot open local API server logs window in web environment') + } +} \ No newline at end of file diff --git a/web-app/src/test/mocks/extensions-web.ts b/web-app/src/test/mocks/extensions-web.ts new file mode 100644 index 000000000..908f56c90 --- /dev/null +++ b/web-app/src/test/mocks/extensions-web.ts @@ -0,0 +1,21 @@ +/** + * Mock for @jan/extensions-web package when it's not available (desktop CICD builds) + */ + +// Mock empty extensions registry +export const WEB_EXTENSIONS = {} + +// Mock extension classes for completeness +export class AssistantExtensionWeb { + constructor() {} +} + +export class ConversationalExtensionWeb { + constructor() {} +} + +// Default export +export default {} + +// Export registry type for TypeScript compatibility +export type WebExtensionRegistry = Record \ No newline at end of file diff --git a/web-app/src/test/setup.ts b/web-app/src/test/setup.ts index 1d36edc5c..a542ffec9 100644 --- a/web-app/src/test/setup.ts +++ b/web-app/src/test/setup.ts @@ -5,6 +5,165 @@ import * as matchers from '@testing-library/jest-dom/matchers' // extends Vitest's expect method with methods from react-testing-library expect.extend(matchers) +// Global mock for platform features to enable all features in tests +// This ensures consistent behavior across all tests and enables testing of +// platform-specific features like Hub, Hardware monitoring, etc. +vi.mock('@/lib/platform/const', () => ({ + PlatformFeatures: { + hardwareMonitoring: true, + extensionManagement: true, + localInference: true, + mcpServers: true, + localApiServer: true, + modelHub: true, + systemIntegrations: true, + httpsProxy: true, + defaultProviders: true, + analytics: true, + webAutoModelSelection: true, + modelProviderSettings: true, + } +})) + +// Create a mock ServiceHub +const mockServiceHub = { + theme: () => ({ + getTheme: vi.fn().mockReturnValue('light'), + setTheme: vi.fn(), + toggleTheme: vi.fn(), + }), + window: vi.fn().mockReturnValue({ + minimize: vi.fn(), + maximize: vi.fn(), + close: vi.fn(), + isMaximized: vi.fn().mockResolvedValue(false), + openLogsWindow: vi.fn().mockResolvedValue(undefined), + }), + events: () => ({ + emit: vi.fn().mockResolvedValue(undefined), + listen: vi.fn().mockResolvedValue(() => {}), + }), + hardware: () => ({ + getHardwareInfo: vi.fn().mockResolvedValue(null), + getSystemUsage: vi.fn().mockResolvedValue(null), + getLlamacppDevices: vi.fn().mockResolvedValue([]), // cspell: disable-line + setActiveGpus: vi.fn().mockResolvedValue(undefined), + // Legacy methods for backward compatibility + getGpuInfo: vi.fn().mockResolvedValue([]), + getCpuInfo: vi.fn().mockResolvedValue({}), + getMemoryInfo: vi.fn().mockResolvedValue({}), + }), + app: () => ({ + getAppSettings: vi.fn().mockResolvedValue({}), + updateAppSettings: vi.fn().mockResolvedValue(undefined), + getSystemInfo: vi.fn().mockResolvedValue({}), + relocateJanDataFolder: vi.fn().mockResolvedValue(undefined), + getJanDataFolder: vi.fn().mockResolvedValue('/mock/jan/data'), + }), + analytic: () => ({ + track: vi.fn(), + identify: vi.fn(), + page: vi.fn(), + }), + messages: () => ({ + createMessage: vi.fn().mockResolvedValue({ id: 'test-message' }), + deleteMessage: vi.fn().mockResolvedValue(undefined), + updateMessage: vi.fn().mockResolvedValue(undefined), + getMessages: vi.fn().mockResolvedValue([]), + getMessage: vi.fn().mockResolvedValue(null), + fetchMessages: vi.fn().mockResolvedValue([]), + }), + mcp: () => ({ + updateMCPConfig: vi.fn().mockResolvedValue(undefined), + restartMCPServers: vi.fn().mockResolvedValue(undefined), + getMCPConfig: vi.fn().mockResolvedValue({}), + getTools: vi.fn().mockResolvedValue([]), + getConnectedServers: vi.fn().mockResolvedValue([]), + callTool: vi.fn().mockResolvedValue({ error: '', content: [] }), + callToolWithCancellation: vi.fn().mockReturnValue({ + promise: Promise.resolve({ error: '', content: [] }), + cancel: vi.fn().mockResolvedValue(undefined), + token: 'test-token' + }), + cancelToolCall: vi.fn().mockResolvedValue(undefined), + activateMCPServer: vi.fn().mockResolvedValue(undefined), + deactivateMCPServer: vi.fn().mockResolvedValue(undefined), + }), + threads: () => ({ + createThread: vi.fn().mockResolvedValue({ id: 'test-thread', messages: [] }), + deleteThread: vi.fn().mockResolvedValue(undefined), + updateThread: vi.fn().mockResolvedValue(undefined), + getThreads: vi.fn().mockResolvedValue([]), + getThread: vi.fn().mockResolvedValue(null), + fetchThreads: vi.fn().mockResolvedValue([]), + }), + providers: () => ({ + getProviders: vi.fn().mockResolvedValue([]), + createProvider: vi.fn().mockResolvedValue({ id: 'test-provider' }), + deleteProvider: vi.fn().mockResolvedValue(undefined), + updateProvider: vi.fn().mockResolvedValue(undefined), + getProvider: vi.fn().mockResolvedValue(null), + }), + models: () => ({ + getModels: vi.fn().mockResolvedValue([]), + getModel: vi.fn().mockResolvedValue(null), + createModel: vi.fn().mockResolvedValue({ id: 'test-model' }), + deleteModel: vi.fn().mockResolvedValue(undefined), + updateModel: vi.fn().mockResolvedValue(undefined), + startModel: vi.fn().mockResolvedValue(undefined), + isModelSupported: vi.fn().mockResolvedValue('GREEN'), + checkMmprojExists: vi.fn().mockResolvedValue(true), // cspell: disable-line + stopAllModels: vi.fn().mockResolvedValue(undefined), + }), + assistants: () => ({ + getAssistants: vi.fn().mockResolvedValue([]), + getAssistant: vi.fn().mockResolvedValue(null), + createAssistant: vi.fn().mockResolvedValue({ id: 'test-assistant' }), + deleteAssistant: vi.fn().mockResolvedValue(undefined), + updateAssistant: vi.fn().mockResolvedValue(undefined), + }), + dialog: () => ({ + open: vi.fn().mockResolvedValue({ confirmed: true }), + save: vi.fn().mockResolvedValue('/path/to/file'), + message: vi.fn().mockResolvedValue(undefined), + }), + opener: vi.fn().mockReturnValue({ + open: vi.fn().mockResolvedValue(undefined), + revealItemInDir: vi.fn().mockResolvedValue(undefined), + }), + updater: () => ({ + checkForUpdates: vi.fn().mockResolvedValue(null), + installUpdate: vi.fn().mockResolvedValue(undefined), + downloadAndInstallWithProgress: vi.fn().mockResolvedValue(undefined), + }), + path: vi.fn().mockReturnValue({ + sep: () => '/', + join: vi.fn((...args) => args.join('/')), + resolve: vi.fn((path) => path), + dirname: vi.fn((path) => path.split('/').slice(0, -1).join('/')), + basename: vi.fn((path) => path.split('/').pop()), + }), + core: () => ({ + startCore: vi.fn().mockResolvedValue(undefined), + stopCore: vi.fn().mockResolvedValue(undefined), + getCoreStatus: vi.fn().mockResolvedValue('stopped'), + }), + deeplink: () => ({ // cspell: disable-line + register: vi.fn().mockResolvedValue(undefined), + handle: vi.fn().mockResolvedValue(undefined), + getCurrent: vi.fn().mockResolvedValue(null), + onOpenUrl: vi.fn().mockResolvedValue(undefined), + }), +} + +// Mock the useServiceHub module +vi.mock('@/hooks/useServiceHub', () => ({ + useServiceHub: () => mockServiceHub, + getServiceHub: () => mockServiceHub, + initializeServiceHubStore: vi.fn(), + isServiceHubInitialized: () => true, +})) + // Mock window.matchMedia for useMediaQuery tests Object.defineProperty(window, 'matchMedia', { writable: true, @@ -20,6 +179,27 @@ Object.defineProperty(window, 'matchMedia', { })), }) +// Mock globalThis.core.api for @janhq/core functions // cspell: disable-line +;(globalThis as Record).core = { + api: { + getJanDataFolderPath: vi.fn().mockResolvedValue('/mock/jan/data'), + openFileExplorer: vi.fn().mockResolvedValue(undefined), + joinPath: vi.fn((...paths: string[]) => paths.join('/')), + } +} + +// Mock globalThis.fs for @janhq/core fs functions // cspell: disable-line +;(globalThis as Record).fs = { + existsSync: vi.fn().mockResolvedValue(false), + readFile: vi.fn().mockResolvedValue(''), + writeFile: vi.fn().mockResolvedValue(undefined), + readdir: vi.fn().mockResolvedValue([]), + mkdir: vi.fn().mockResolvedValue(undefined), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), +} + + // runs a cleanup after each test case (e.g. clearing jsdom) afterEach(() => { cleanup() diff --git a/web-app/src/types/global.d.ts b/web-app/src/types/global.d.ts index b104314b0..3497eabcf 100644 --- a/web-app/src/types/global.d.ts +++ b/web-app/src/types/global.d.ts @@ -9,6 +9,7 @@ type AppCore = { declare global { declare const IS_TAURI: boolean + declare const IS_WEB_APP: boolean declare const IS_MACOS: boolean declare const IS_WINDOWS: boolean declare const IS_LINUX: boolean diff --git a/web-app/src/utils/formatDate.ts b/web-app/src/utils/formatDate.ts index c77f20097..3ad6a9128 100644 --- a/web-app/src/utils/formatDate.ts +++ b/web-app/src/utils/formatDate.ts @@ -22,7 +22,6 @@ export const formatDate = ( hour: 'numeric', minute: 'numeric', hour12: true, - timeZone: 'UTC', }) } diff --git a/web-app/tsconfig.web.json b/web-app/tsconfig.web.json new file mode 100644 index 000000000..c6515c8a6 --- /dev/null +++ b/web-app/tsconfig.web.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + // Relax some strict rules for web version to handle platform-specific code + "noUnusedParameters": false, + "noUnusedLocals": false, + "skipLibCheck": true + } +} \ No newline at end of file diff --git a/web-app/vite.config.ts b/web-app/vite.config.ts index 4c1b2ab40..352f9baa2 100644 --- a/web-app/vite.config.ts +++ b/web-app/vite.config.ts @@ -32,6 +32,7 @@ export default defineConfig(({ mode }) => { }, define: { IS_TAURI: JSON.stringify(process.env.IS_TAURI), + IS_WEB_APP: JSON.stringify(false), IS_MACOS: JSON.stringify( process.env.TAURI_ENV_PLATFORM?.includes('darwin') ?? false ), diff --git a/web-app/vite.config.web.ts b/web-app/vite.config.web.ts new file mode 100644 index 000000000..6f4e271be --- /dev/null +++ b/web-app/vite.config.web.ts @@ -0,0 +1,69 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' +import path from 'path' +import { TanStackRouterVite } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + TanStackRouterVite({ + target: 'react', + autoCodeSplitting: true, + routeFileIgnorePattern: '.((test).ts)|test-page', + }), + react(), + tailwindcss(), + ], + build: { + outDir: './dist-web', + emptyOutDir: true, + rollupOptions: { + external: [ + // Exclude Tauri packages from web bundle + '@tauri-apps/api', + '@tauri-apps/plugin-http', + '@tauri-apps/plugin-fs', + '@tauri-apps/plugin-shell', + '@tauri-apps/plugin-clipboard-manager', + '@tauri-apps/plugin-dialog', + '@tauri-apps/plugin-os', + '@tauri-apps/plugin-process', + '@tauri-apps/plugin-updater', + '@tauri-apps/plugin-deep-link', + '@tauri-apps/api/event', + '@tauri-apps/api/path', + '@tauri-apps/api/window', + '@tauri-apps/api/webviewWindow', + ], + }, + target: 'esnext', + }, + resolve: { + alias: { + '@': path.resolve(__dirname, './src'), + }, + }, + define: { + IS_TAURI: JSON.stringify(process.env.IS_TAURI), + // Platform detection constants for web version + IS_WEB_APP: JSON.stringify(true), + // Disable auto-updater on web (not applicable) + AUTO_UPDATER_DISABLED: JSON.stringify(true), + IS_MACOS: JSON.stringify(false), + IS_WINDOWS: JSON.stringify(false), + IS_LINUX: JSON.stringify(false), + IS_IOS: JSON.stringify(false), + IS_ANDROID: JSON.stringify(false), + PLATFORM: JSON.stringify('web'), + VERSION: JSON.stringify(process.env.npm_package_version || '1.0.0'), + POSTHOG_KEY: JSON.stringify(process.env.POSTHOG_KEY || ''), + POSTHOG_HOST: JSON.stringify(process.env.POSTHOG_HOST || ''), + MODEL_CATALOG_URL: JSON.stringify(process.env.MODEL_CATALOG_URL || ''), + }, + server: { + port: 3001, + strictPort: true, + }, + // Enable SPA mode - fallback to index.html for all routes + appType: 'spa', +}) diff --git a/web-app/vitest.config.ts b/web-app/vitest.config.ts index c2289f337..f3bea3c7a 100644 --- a/web-app/vitest.config.ts +++ b/web-app/vitest.config.ts @@ -25,10 +25,22 @@ export default defineConfig({ resolve: { alias: { '@': path.resolve(__dirname, './src'), + // Provide a fallback for @jan/extensions-web when it doesn't exist (CICD desktop builds) + '@jan/extensions-web': (() => { + try { + // Try to resolve the actual package first + require.resolve('@jan/extensions-web') + return '@jan/extensions-web' + } catch { + // If package doesn't exist, use a mock + return path.resolve(__dirname, './src/test/mocks/extensions-web.ts') + } + })(), }, }, define: { IS_TAURI: JSON.stringify('false'), + IS_WEB_APP: JSON.stringify('false'), IS_MACOS: JSON.stringify('false'), IS_WINDOWS: JSON.stringify('false'), IS_LINUX: JSON.stringify('false'), diff --git a/website/API_SPEC_SYNC.md b/website/API_SPEC_SYNC.md new file mode 100644 index 000000000..7c2fb0e78 --- /dev/null +++ b/website/API_SPEC_SYNC.md @@ -0,0 +1,183 @@ +# API Specification Synchronization + +This document explains how the Jan Server API specification is kept in sync with the documentation. + +## Overview + +The Jan documentation automatically synchronizes with the Jan Server API specification to ensure the API reference is always up to date. This is managed through GitHub Actions workflows that can be triggered in multiple ways. + +## Synchronization Methods + +### 1. Automatic Daily Sync +- **Schedule**: Runs daily at 2 AM UTC +- **Branch**: `dev` +- **Behavior**: Fetches the latest spec and commits changes if any +- **Workflow**: `.github/workflows/update-cloud-api-spec.yml` + +### 2. Manual Trigger via GitHub UI +Navigate to Actions → "Update Cloud API Spec" → Run workflow + +Options: +- **Commit changes**: Whether to commit changes directly (default: true) +- **Custom spec URL**: Override the default API spec URL +- **Create PR**: Create a pull request instead of direct commit (default: false) + +### 3. Webhook Trigger (For Jan Server Team) + +Send a repository dispatch event to trigger an update: + +```bash +curl -X POST \ + -H "Accept: application/vnd.github.v3+json" \ + -H "Authorization: token YOUR_GITHUB_TOKEN" \ + https://api.github.com/repos/janhq/jan/dispatches \ + -d '{ + "event_type": "update-api-spec", + "client_payload": { + "spec_url": "https://api.jan.ai/api/swagger/doc.json" + } + }' +``` + +### 4. Local Development + +For local development, the spec is updated conditionally: + +```bash +# Force update the cloud spec +bun run generate:cloud-spec-force + +# Normal update (checks if update is needed) +bun run generate:cloud-spec + +# Update both local and cloud specs +bun run generate:specs +``` + +## Configuration + +### Environment Variables + +The following environment variables can be configured in GitHub Secrets: + +| Variable | Description | Default | +|----------|-------------|---------| +| `JAN_SERVER_SPEC_URL` | URL to fetch the OpenAPI spec | `https://api.jan.ai/api/swagger/doc.json` | +| `JAN_SERVER_PROD_URL` | Production API base URL | `https://api.jan.ai/v1` | +| `JAN_SERVER_STAGING_URL` | Staging API base URL | `https://staging-api.jan.ai/v1` | + +### Build Behavior + +| Context | Behavior | +|---------|----------| +| Pull Request | Uses existing spec (no update) | +| Push to dev | Uses existing spec (no update) | +| Scheduled run | Updates spec and commits changes | +| Manual trigger | Updates based on input options | +| Webhook | Updates and creates PR | +| Local dev | Updates if spec is >24hrs old or missing | + +## Workflow Integration + +### For Jan Server Team + +When deploying a new API version: + +1. **Option A: Automatic PR** + - Deploy your API changes + - Trigger the webhook (see above) + - Review and merge the created PR + +2. **Option B: Manual Update** + - Go to [Actions](https://github.com/janhq/jan/actions/workflows/update-cloud-api-spec.yml) + - Click "Run workflow" + - Select options: + - Set "Create PR" to `true` for review + - Or leave as `false` for direct commit + +3. **Option C: Wait for Daily Sync** + - Changes will be picked up automatically at 2 AM UTC + +### For Documentation Team + +The API spec updates are handled automatically. However, you can: + +1. **Force an update**: Run the "Update Cloud API Spec" workflow manually +2. **Test locally**: Use `bun run generate:cloud-spec-force` +3. **Review changes**: Check PRs labeled with `api` and `automated` + +## Fallback Mechanism + +If the Jan Server API is unavailable: + +1. The workflow will use the last known good spec +2. Local builds will fall back to the local OpenAPI spec +3. The build will continue without failing + +## Monitoring + +### Check Update Status + +1. Go to [Actions](https://github.com/janhq/jan/actions/workflows/update-cloud-api-spec.yml) +2. Check the latest run status +3. Review the workflow summary for details + +### Notifications + +To add Slack/Discord notifications: + +1. Add webhook URL to GitHub Secrets +2. Uncomment notification section in workflow +3. Configure message format as needed + +## Troubleshooting + +### Spec Update Fails + +1. Check if the API endpoint is accessible +2. Verify the spec URL is correct +3. Check GitHub Actions logs for errors +4. Ensure proper permissions for the workflow + +### Changes Not Appearing + +1. Verify the workflow completed successfully +2. Check if changes were committed to the correct branch +3. Ensure the build is using the updated spec +4. Clear CDN cache if using Cloudflare + +### Manual Recovery + +If automated updates fail: + +```bash +# Clone the repository +git clone https://github.com/janhq/jan.git +cd jan/website + +# Install dependencies +bun install + +# Force update the spec +FORCE_UPDATE=true bun run generate:cloud-spec + +# Commit and push +git add public/openapi/cloud-openapi.json +git commit -m "chore: manual update of API spec" +git push +``` + +## Best Practices + +1. **Version Control**: Always review significant API changes before merging +2. **Testing**: Test the updated spec locally before deploying +3. **Communication**: Notify the docs team of breaking API changes +4. **Monitoring**: Set up alerts for failed spec updates +5. **Documentation**: Update this guide when changing the sync process + +## Support + +For issues or questions: +- Open an issue in the [Jan repository](https://github.com/janhq/jan/issues) +- Contact the documentation team on Discord +- Check the [workflow runs](https://github.com/janhq/jan/actions) for debugging \ No newline at end of file diff --git a/website/README.md b/website/README.md index cec200784..659e09ccc 100644 --- a/website/README.md +++ b/website/README.md @@ -26,3 +26,23 @@ All commands are run from the root of the project, from a terminal: | `bun preview` | Preview your build locally, before deploying | | `bun astro ...` | Run CLI commands like `astro add`, `astro check` | | `bun astro -- --help` | Get help using the Astro CLI | + +## 📖 API Reference Commands + +The website includes interactive API documentation. These commands help manage the OpenAPI specifications: + +| Command | Action | +| :------------------------------- | :-------------------------------------------------------- | +| `bun run api:dev` | Start dev server with API reference at `/api` | +| `bun run api:local` | Start dev server with local API docs at `/api-reference/local` | +| `bun run api:cloud` | Start dev server with cloud API docs at `/api-reference/cloud` | +| `bun run generate:local-spec` | Generate/fix the local OpenAPI specification | +| `bun run generate:cloud-spec` | Generate the cloud OpenAPI specification from Jan Server | +| `bun run generate:cloud-spec-force` | Force update cloud spec (ignores cache/conditions) | + +**API Reference Pages:** +- `/api` - Landing page with Local and Server API options +- `/api-reference/local` - Local API (llama.cpp) documentation +- `/api-reference/cloud` - Jan Server API (vLLM) documentation + +The cloud specification is automatically synced via GitHub Actions on a daily schedule and can be manually triggered by the Jan Server team. diff --git a/website/astro.config.mjs b/website/astro.config.mjs index 5395b8e9f..922f1a860 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -1,9 +1,11 @@ // @ts-check import { defineConfig } from 'astro/config' import starlight from '@astrojs/starlight' -import starlightThemeNext from 'starlight-theme-next' -// import starlightThemeRapide from 'starlight-theme-rapide' +import starlightThemeRapide from 'starlight-theme-rapide' import starlightSidebarTopics from 'starlight-sidebar-topics' +import starlightUtils from '@lorenzo_lewis/starlight-utils' +import react from '@astrojs/react' + import mermaid from 'astro-mermaid' import { fileURLToPath } from 'url' import path, { dirname } from 'path' @@ -14,155 +16,273 @@ const __dirname = dirname(__filename) // https://astro.build/config export default defineConfig({ // Deploy to the new v2 subdomain - site: 'https://v2.jan.ai', + site: 'https://docs.jan.ai', integrations: [ + react(), mermaid({ theme: 'default', autoTheme: true, }), starlight({ title: '👋 Jan', + favicon: 'favicon.ico', + customCss: ['./src/styles/global.css'], + head: [ + { + tag: 'script', + attrs: { src: '/scripts/inject-navigation.js', defer: true }, + }, + { + tag: 'link', + attrs: { rel: 'stylesheet', href: '/styles/navigation.css' }, + }, + ], - favicon: 'jan2.png', plugins: [ - // starlightThemeRapide(), - starlightThemeNext(), - starlightSidebarTopics([ + starlightThemeRapide(), + starlightSidebarTopics( + [ + { + label: 'Jan', + link: '/', + icon: 'rocket', + items: [{ label: 'Ecosystem', slug: 'index' }], + }, + { + label: 'Jan Desktop', + link: '/jan/quickstart', + icon: 'rocket', + items: [ + { + label: '🚀 QUICK START', + items: [ + { label: 'Getting Started', slug: 'jan/quickstart' }, + { + label: 'Install Jan', + collapsed: false, + autogenerate: { directory: 'jan/installation' }, + }, + { label: 'AI Assistants', slug: 'jan/assistants' }, + ], + }, + { + label: '🤖 MODELS', + items: [ + { label: 'Overview', slug: 'jan/manage-models' }, + { + label: 'Jan Models', + collapsed: false, + items: [ + { + label: 'Jan v1', + slug: 'jan/jan-models/jan-v1', + }, + { + label: 'Research Models', + collapsed: true, + items: [ + { + label: 'Jan Nano 32k', + slug: 'jan/jan-models/jan-nano-32', + }, + { + label: 'Jan Nano 128k', + slug: 'jan/jan-models/jan-nano-128', + }, + { + label: 'Lucy', + slug: 'jan/jan-models/lucy', + }, + ], + }, + ], + }, + { + label: 'Cloud Providers', + collapsed: true, + items: [ + { label: 'OpenAI', slug: 'jan/remote-models/openai' }, + { + label: 'Anthropic', + slug: 'jan/remote-models/anthropic', + }, + { label: 'Gemini', slug: 'jan/remote-models/google' }, + { label: 'Groq', slug: 'jan/remote-models/groq' }, + { + label: 'Mistral', + slug: 'jan/remote-models/mistralai', + }, + { label: 'Cohere', slug: 'jan/remote-models/cohere' }, + { + label: 'OpenRouter', + slug: 'jan/remote-models/openrouter', + }, + { + label: 'HuggingFace 🤗', + slug: 'jan/remote-models/huggingface', + }, + ], + }, + { + label: 'Custom Providers', + slug: 'jan/custom-provider', + }, + { + label: 'Multi-Modal Models', + slug: 'jan/multi-modal', + }, + ], + }, + { + label: '🔧 TOOLS & INTEGRATIONS', + items: [ + { label: 'What is MCP?', slug: 'jan/mcp' }, + { + label: 'Examples & Tutorials', + collapsed: true, + items: [ + { + label: 'Web & Search', + collapsed: true, + items: [ + { + label: 'Browser Control', + slug: 'jan/mcp-examples/browser/browserbase', + }, + { + label: 'Serper Search', + slug: 'jan/mcp-examples/search/serper', + }, + { + label: 'Exa Search', + slug: 'jan/mcp-examples/search/exa', + }, + ], + }, + { + label: 'Data & Analysis', + collapsed: true, + items: [ + { + label: 'Jupyter Notebooks', + slug: 'jan/mcp-examples/data-analysis/jupyter', + }, + { + label: 'Code Sandbox (E2B)', + slug: 'jan/mcp-examples/data-analysis/e2b', + }, + { + label: 'Deep Financial Research', + slug: 'jan/mcp-examples/deepresearch/octagon', + }, + ], + }, + { + label: 'Productivity', + collapsed: true, + items: [ + { + label: 'Linear', + slug: 'jan/mcp-examples/productivity/linear', + }, + { + label: 'Todoist', + slug: 'jan/mcp-examples/productivity/todoist', + }, + ], + }, + { + label: 'Creative', + collapsed: true, + items: [ + { + label: 'Design with Canva', + slug: 'jan/mcp-examples/design/canva', + }, + ], + }, + ], + }, + ], + }, + { + label: '⚙️ DEVELOPER', + items: [ + { + label: 'Local API Server', + collapsed: true, + items: [ + { label: 'Overview', slug: 'local-server' }, + { + label: 'API Configuration', + slug: 'local-server/api-server', + }, + { + label: 'Engine Settings', + slug: 'local-server/llama-cpp', + }, + { + label: 'Server Settings', + slug: 'local-server/settings', + }, + { + label: 'Integrations', + collapsed: true, + autogenerate: { + directory: 'local-server/integrations', + }, + }, + ], + }, + { + label: 'Technical Details', + collapsed: true, + items: [ + { + label: 'Model Parameters', + slug: 'jan/explanation/model-parameters', + }, + ], + }, + ], + }, + { + label: '📚 REFERENCE', + items: [ + { label: 'Settings', slug: 'jan/settings' }, + { label: 'Data Folder', slug: 'jan/data-folder' }, + { label: 'Troubleshooting', slug: 'jan/troubleshooting' }, + { label: 'Privacy Policy', slug: 'jan/privacy' }, + ], + }, + ], + }, + { + label: 'Browser Extension', + link: '/browser/', + badge: { text: 'Alpha', variant: 'tip' }, + icon: 'puzzle', + items: [{ label: 'Overview', slug: 'browser' }], + }, + { + label: 'Jan Mobile', + link: '/mobile/', + badge: { text: 'Soon', variant: 'caution' }, + icon: 'phone', + items: [{ label: 'Overview', slug: 'mobile' }], + }, + { + label: 'Jan Server', + link: '/server/', + badge: { text: 'Soon', variant: 'caution' }, + icon: 'forward-slash', + items: [{ label: 'Overview', slug: 'server' }], + }, + ], { - label: 'Jan Desktop', - link: '/', - icon: 'rocket', - items: [ - { - label: 'GETTING STARTED', - items: [ - { - label: 'Install 👋 Jan', - collapsed: false, - autogenerate: { directory: 'jan/installation' }, - }, - { label: 'QuickStart', slug: 'jan/quickstart' }, - { - label: 'Models', - collapsed: true, - autogenerate: { directory: 'jan/jan-models' }, - }, - { label: 'Assistants', slug: 'jan/assistants' }, - { - label: 'Cloud Providers', - collapsed: true, - items: [ - { - label: 'Anthropic', - slug: 'jan/remote-models/anthropic', - }, - { label: 'OpenAI', slug: 'jan/remote-models/openai' }, - { label: 'Gemini', slug: 'jan/remote-models/google' }, - { - label: 'OpenRouter', - slug: 'jan/remote-models/openrouter', - }, - { label: 'Cohere', slug: 'jan/remote-models/cohere' }, - { - label: 'Mistral', - slug: 'jan/remote-models/mistralai', - }, - { label: 'Groq', slug: 'jan/remote-models/groq' }, - ], - }, - ], - }, - { - label: 'TUTORIALS', - items: [ - { - label: 'MCP Examples', - collapsed: true, - items: [ - { - label: 'Browser Control (Browserbase)', - slug: 'jan/mcp-examples/browser/browserbase', - }, - { - label: 'Code Sandbox (E2B)', - slug: 'jan/mcp-examples/data-analysis/e2b', - }, - { - label: 'Design Creation (Canva)', - slug: 'jan/mcp-examples/design/canva', - }, - { - label: 'Deep Research (Octagon)', - slug: 'jan/mcp-examples/deepresearch/octagon', - }, - { - label: 'Serper Search', - slug: 'jan/mcp-examples/search/serper', - }, - { - label: 'Web Search (Exa)', - slug: 'jan/mcp-examples/search/exa', - }, - ], - }, - ], - }, - { - label: 'EXPLANATION', - items: [ - { - label: 'Local AI Engine', - slug: 'jan/explanation/llama-cpp', - }, - { - label: 'Model Parameters', - slug: 'jan/explanation/model-parameters', - }, - ], - }, - { - label: 'ADVANCED', - items: [ - { label: 'Manage Models', slug: 'jan/manage-models' }, - { label: 'Model Context Protocol', slug: 'jan/mcp' }, - ], - }, - { - label: 'Local Server', - items: [ - { - label: 'All', - collapsed: true, - autogenerate: { directory: 'local-server' }, - }, - ], - }, - { - label: 'REFERENCE', - items: [ - { label: 'Settings', slug: 'jan/settings' }, - { label: 'Jan Data Folder', slug: 'jan/data-folder' }, - { label: 'Troubleshooting', slug: 'jan/troubleshooting' }, - { label: 'Privacy Policy', slug: 'jan/privacy' }, - ], - }, - ], - }, - { - label: 'Jan Mobile', - link: '/mobile/', - badge: { text: 'Soon', variant: 'caution' }, - icon: 'phone', - items: [{ label: 'Overview', slug: 'mobile' }], - }, - { - label: 'Jan Server', - link: '/server/', - badge: { text: 'Soon', variant: 'caution' }, - icon: 'forward-slash', - items: [{ label: 'Overview', slug: 'server' }], - }, - ]), + exclude: ['/api-reference', '/api-reference/**/*'], + } + ), ], social: [ { diff --git a/website/bun.lock b/website/bun.lock index 24b037fea..91dde2b17 100644 --- a/website/bun.lock +++ b/website/bun.lock @@ -4,32 +4,33 @@ "": { "name": "website", "dependencies": { + "@astrojs/react": "^4.3.0", "@astrojs/starlight": "^0.35.1", "@lorenzo_lewis/starlight-utils": "^0.3.2", + "@scalar/api-reference-react": "^0.7.42", + "@types/react": "^19.1.12", "astro": "^5.6.1", "astro-mermaid": "^1.0.4", - "gsap": "^3.13.0", "mermaid": "^11.9.0", - "phosphor-astro": "^2.1.0", + "react": "^19.1.1", + "react-dom": "^19.1.1", "sharp": "^0.34.3", "starlight-openapi": "^0.19.1", "starlight-sidebar-topics": "^0.6.0", - "starlight-theme-next": "^0.3.2", "starlight-theme-rapide": "^0.5.1", - "starlight-videos": "^0.3.0", "unist-util-visit": "^5.0.0", }, }, }, "packages": { + "@ampproject/remapping": ["@ampproject/remapping@2.3.0", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw=="], + "@antfu/install-pkg": ["@antfu/install-pkg@1.1.0", "", { "dependencies": { "package-manager-detector": "^1.3.0", "tinyexec": "^1.0.1" } }, "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ=="], "@antfu/utils": ["@antfu/utils@8.1.1", "", {}, "sha512-Mex9nXf9vR6AhcXmMrlz/HVgYYZpVGJ6YlPgwl7UnaFpnshXs6EK/oa5Gpf3CzENMjkvEx2tQtntGnb7UtSTOQ=="], "@apidevtools/swagger-methods": ["@apidevtools/swagger-methods@3.0.2", "", {}, "sha512-QAkD5kK2b1WfjDS/UQn/qQkbwF31uqRjPTrsCs5ZG9BQGAkjwvqGFjjPqAuzac/IYzpPtRzjCP1WrTuAIjMrXg=="], - "@astro-community/astro-embed-youtube": ["@astro-community/astro-embed-youtube@0.5.6", "", { "dependencies": { "lite-youtube-embed": "^0.3.3" }, "peerDependencies": { "astro": "^2.0.0 || ^3.0.0-beta || ^4.0.0-beta || ^5.0.0-beta" } }, "sha512-/mRfCl/eTBUz0kmjD1psOy0qoDDBorVp0QumUacjFcIkBullYtbeFQ2ZGZ+3N/tA6cR/OIyzr2QA4dQXlY6USg=="], - "@astrojs/compiler": ["@astrojs/compiler@2.12.2", "", {}, "sha512-w2zfvhjNCkNMmMMOn5b0J8+OmUaBL1o40ipMvqcG6NRpdC+lKxmTi48DT8Xw0SzJ3AfmeFLB45zXZXtmbsjcgw=="], "@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="], @@ -40,6 +41,8 @@ "@astrojs/prism": ["@astrojs/prism@3.3.0", "", { "dependencies": { "prismjs": "^1.30.0" } }, "sha512-q8VwfU/fDZNoDOf+r7jUnMC2//H2l0TuQ6FkGJL8vD8nw/q5KiL3DS1KKBI3QhI9UQhpJ5dc7AtqfbXWuOgLCQ=="], + "@astrojs/react": ["@astrojs/react@4.3.0", "", { "dependencies": { "@vitejs/plugin-react": "^4.4.1", "ultrahtml": "^1.6.0", "vite": "^6.3.5" }, "peerDependencies": { "@types/react": "^17.0.50 || ^18.0.21 || ^19.0.0", "@types/react-dom": "^17.0.17 || ^18.0.6 || ^19.0.0", "react": "^17.0.2 || ^18.0.0 || ^19.0.0", "react-dom": "^17.0.2 || ^18.0.0 || ^19.0.0" } }, "sha512-N02aj52Iezn69qHyx5+XvPqgsPMEnel9mI5JMbGiRMTzzLMuNaxRVoQTaq2024Dpr7BLsxCjqMkNvelqMDhaHA=="], + "@astrojs/sitemap": ["@astrojs/sitemap@3.4.1", "", { "dependencies": { "sitemap": "^8.0.0", "stream-replace-string": "^2.0.0", "zod": "^3.24.2" } }, "sha512-VjZvr1e4FH6NHyyHXOiQgLiw94LnCVY4v06wN/D0gZKchTMkg71GrAHJz81/huafcmavtLkIv26HnpfDq6/h/Q=="], "@astrojs/starlight": ["@astrojs/starlight@0.35.1", "", { "dependencies": { "@astrojs/markdown-remark": "^6.3.1", "@astrojs/mdx": "^4.2.3", "@astrojs/sitemap": "^3.3.0", "@pagefind/default-ui": "^1.3.0", "@types/hast": "^3.0.4", "@types/js-yaml": "^4.0.9", "@types/mdast": "^4.0.4", "astro-expressive-code": "^0.41.1", "bcp-47": "^2.1.0", "hast-util-from-html": "^2.0.1", "hast-util-select": "^6.0.2", "hast-util-to-string": "^3.0.0", "hastscript": "^9.0.0", "i18next": "^23.11.5", "js-yaml": "^4.1.0", "klona": "^2.0.6", "mdast-util-directive": "^3.0.0", "mdast-util-to-markdown": "^2.1.0", "mdast-util-to-string": "^4.0.0", "pagefind": "^1.3.0", "rehype": "^13.0.1", "rehype-format": "^5.0.0", "remark-directive": "^3.0.0", "ultrahtml": "^1.6.0", "unified": "^11.0.5", "unist-util-visit": "^5.0.0", "vfile": "^6.0.2" }, "peerDependencies": { "astro": "^5.5.0" } }, "sha512-/hshlAayMd3B+E+h8wY6JWT1lNmX/K1+ugiZPirW5XFo5QUcNMk/Bsa4oHgg+TFoU6kbxPtijo0VppATfD9XuA=="], @@ -48,14 +51,42 @@ "@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="], + "@babel/compat-data": ["@babel/compat-data@7.28.0", "", {}, "sha512-60X7qkglvrap8mn1lh2ebxXdZYtUcpd7gsmy9kLaBJ4i/WdY8PqTSdxyA8qraikqKQK5C1KRBKXqznrVapyNaw=="], + + "@babel/core": ["@babel/core@7.28.3", "", { "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.3", "@babel/helper-compilation-targets": "^7.27.2", "@babel/helper-module-transforms": "^7.28.3", "@babel/helpers": "^7.28.3", "@babel/parser": "^7.28.3", "@babel/template": "^7.27.2", "@babel/traverse": "^7.28.3", "@babel/types": "^7.28.2", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-yDBHV9kQNcr2/sUr9jghVyz9C3Y5G2zUM2H2lo+9mKv4sFgbA8s8Z9t8D1jiTkGoO/NoIfKMyKWr4s6CN23ZwQ=="], + + "@babel/generator": ["@babel/generator@7.28.3", "", { "dependencies": { "@babel/parser": "^7.28.3", "@babel/types": "^7.28.2", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-3lSpxGgvnmZznmBkCRnVREPUFJv2wrv9iAoFDvADJc0ypmdOxdUtcLeBgBJ6zE0PMeTKnxeQzyk0xTBq4Ep7zw=="], + + "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.27.2", "", { "dependencies": { "@babel/compat-data": "^7.27.2", "@babel/helper-validator-option": "^7.27.1", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ=="], + + "@babel/helper-globals": ["@babel/helper-globals@7.28.0", "", {}, "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw=="], + + "@babel/helper-module-imports": ["@babel/helper-module-imports@7.27.1", "", { "dependencies": { "@babel/traverse": "^7.27.1", "@babel/types": "^7.27.1" } }, "sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w=="], + + "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.28.3", "", { "dependencies": { "@babel/helper-module-imports": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1", "@babel/traverse": "^7.28.3" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-gytXUbs8k2sXS9PnQptz5o0QnpLL51SwASIORY6XaBKF88nsOT0Zw9szLqlSGQDP/4TljBAD5y98p2U1fqkdsw=="], + + "@babel/helper-plugin-utils": ["@babel/helper-plugin-utils@7.27.1", "", {}, "sha512-1gn1Up5YXka3YYAHGKpbideQ5Yjf1tDa9qYcgysz+cNCXukyLl6DjPXhD3VRwSb8c0J9tA4b2+rHEZtc6R0tlw=="], + "@babel/helper-string-parser": ["@babel/helper-string-parser@7.27.1", "", {}, "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA=="], "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.27.1", "", {}, "sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow=="], + "@babel/helper-validator-option": ["@babel/helper-validator-option@7.27.1", "", {}, "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg=="], + + "@babel/helpers": ["@babel/helpers@7.28.3", "", { "dependencies": { "@babel/template": "^7.27.2", "@babel/types": "^7.28.2" } }, "sha512-PTNtvUQihsAsDHMOP5pfobP8C6CM4JWXmP8DrEIt46c3r2bf87Ua1zoqevsMo9g+tWDwgWrFP5EIxuBx5RudAw=="], + "@babel/parser": ["@babel/parser@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.0" }, "bin": "./bin/babel-parser.js" }, "sha512-jVZGvOxOuNSsuQuLRTh13nU0AogFlw32w/MT+LV6D3sP5WdbW61E77RnkbaO2dUvmPAYrBDJXGn5gGS6tH4j8g=="], + "@babel/plugin-transform-react-jsx-self": ["@babel/plugin-transform-react-jsx-self@7.27.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw=="], + + "@babel/plugin-transform-react-jsx-source": ["@babel/plugin-transform-react-jsx-source@7.27.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw=="], + "@babel/runtime": ["@babel/runtime@7.27.6", "", {}, "sha512-vbavdySgbTTrmFE+EsiqUTzlOr5bzlnJtUv9PynGCAKvfQqjIXbvFdumPM/GxMDfyuGMJaJAU6TO4zc1Jf1i8Q=="], + "@babel/template": ["@babel/template@7.27.2", "", { "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/parser": "^7.27.2", "@babel/types": "^7.27.1" } }, "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw=="], + + "@babel/traverse": ["@babel/traverse@7.28.3", "", { "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.3", "@babel/helper-globals": "^7.28.0", "@babel/parser": "^7.28.3", "@babel/template": "^7.27.2", "@babel/types": "^7.28.2", "debug": "^4.3.1" } }, "sha512-7w4kZYHneL3A6NP2nxzHvT3HCZ7puDZZjFMqDpBPECub79sTtSO5CGXDkKrTQq8ksAwfD/XI2MRFX23njdDaIQ=="], + "@babel/types": ["@babel/types@7.28.1", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-x0LvFTekgSX+83TI28Y9wYPUfzrnl2aT5+5QLnO6v7mSJYtEEevuDRN0F0uSHRk1G1IWZC43o00Y0xDDrpBGPQ=="], "@braintree/sanitize-url": ["@braintree/sanitize-url@7.1.1", "", {}, "sha512-i1L7noDNxtFyL5DmZafWy1wRVhGehQmzZaz1HiN5e7iylJMSZR7ekOV7NsIqa5qBldlLrsKv4HbgFUVlQrz8Mw=="], @@ -72,6 +103,32 @@ "@chevrotain/utils": ["@chevrotain/utils@11.0.3", "", {}, "sha512-YslZMgtJUyuMbZ+aKvfF3x1f5liK4mWNxghFRv7jqRR9C3R3fAOGTTKvxXDa2Y1s9zSbcpuO0cAxDYsc9SrXoQ=="], + "@codemirror/autocomplete": ["@codemirror/autocomplete@6.18.7", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0" } }, "sha512-8EzdeIoWPJDsMBwz3zdzwXnUpCzMiCyz5/A3FIPpriaclFCGDkAzK13sMcnsu5rowqiyeQN2Vs2TsOcoDPZirQ=="], + + "@codemirror/commands": ["@codemirror/commands@6.8.1", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.4.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-KlGVYufHMQzxbdQONiLyGQDUW0itrLZwq3CcY7xpv9ZLRHqzkBSoteocBHtMCoY7/Ci4xhzSrToIeLg7FxHuaw=="], + + "@codemirror/lang-css": ["@codemirror/lang-css@6.3.1", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.2", "@lezer/css": "^1.1.7" } }, "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg=="], + + "@codemirror/lang-html": ["@codemirror/lang-html@6.4.9", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/css": "^1.1.0", "@lezer/html": "^1.3.0" } }, "sha512-aQv37pIMSlueybId/2PVSP6NPnmurFDVmZwzc7jszd2KAF8qd4VBbvNYPXWQq90WIARjsdVkPbw29pszmHws3Q=="], + + "@codemirror/lang-javascript": ["@codemirror/lang-javascript@6.2.4", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/lint": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/javascript": "^1.0.0" } }, "sha512-0WVmhp1QOqZ4Rt6GlVGwKJN3KW7Xh4H2q8ZZNGZaP6lRdxXJzmjm4FqvmOojVj6khWJHIb9sp7U/72W7xQgqAA=="], + + "@codemirror/lang-json": ["@codemirror/lang-json@6.0.2", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/json": "^1.0.0" } }, "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ=="], + + "@codemirror/lang-xml": ["@codemirror/lang-xml@6.1.0", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/xml": "^1.0.0" } }, "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg=="], + + "@codemirror/lang-yaml": ["@codemirror/lang-yaml@6.1.2", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.0.0", "@lezer/yaml": "^1.0.0" } }, "sha512-dxrfG8w5Ce/QbT7YID7mWZFKhdhsaTNOYjOkSIMt1qmC4VQnXSDSYVHHHn8k6kJUfIhtLo8t1JJgltlxWdsITw=="], + + "@codemirror/language": ["@codemirror/language@6.11.3", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", "@lezer/common": "^1.1.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0", "style-mod": "^4.0.0" } }, "sha512-9HBM2XnwDj7fnu0551HkGdrUrrqmYq/WC5iv6nbY2WdicXdGbhR/gfbZOH73Aqj4351alY1+aoG9rCNfiwS1RA=="], + + "@codemirror/lint": ["@codemirror/lint@6.8.5", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.35.0", "crelt": "^1.0.5" } }, "sha512-s3n3KisH7dx3vsoeGMxsbRAgKe4O1vbrnKBClm99PU0fWxmxsx5rR2PfqQgIt+2MMJBHbiJ5rfIdLYfB9NNvsA=="], + + "@codemirror/search": ["@codemirror/search@6.5.11", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "crelt": "^1.0.5" } }, "sha512-KmWepDE6jUdL6n8cAAqIpRmLPBZ5ZKnicE8oGU/s3QrAVID+0VhLFrzUucVKHG5035/BSykhExDL/Xm7dHthiA=="], + + "@codemirror/state": ["@codemirror/state@6.5.2", "", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-FVqsPqtPWKVVL3dPSxy8wEF/ymIEuVzF1PK3VbUgrxXpJUSHQWWZz4JMToquRxnkw+36LTamCZG2iua2Ptq0fA=="], + + "@codemirror/view": ["@codemirror/view@6.38.2", "", { "dependencies": { "@codemirror/state": "^6.5.0", "crelt": "^1.0.6", "style-mod": "^4.1.0", "w3c-keyname": "^2.2.4" } }, "sha512-bTWAJxL6EOFLPzTx+O5P5xAO3gTqpatQ2b/ARQ8itfU/v2LlpS3pH2fkL0A3E/Fx8Y2St2KES7ZEV0sHTsSW/A=="], + "@ctrl/tinycolor": ["@ctrl/tinycolor@4.1.0", "", {}, "sha512-WyOx8cJQ+FQus4Mm4uPIZA64gbk3Wxh0so5Lcii0aJifqwoVOlfFtorjLE0Hen4OYyHZMXDWqMmaQemBhgxFRQ=="], "@emnapi/runtime": ["@emnapi/runtime@1.4.5", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-++LApOtY0pEEz1zrd9vy1/zXVaVJJ/EbAF3u0fXIzPJEDtnITsBGbbK0EkM72amhl/R5b+5xx0Y/QhcVOpuulg=="], @@ -136,8 +193,30 @@ "@expressive-code/plugin-text-markers": ["@expressive-code/plugin-text-markers@0.41.3", "", { "dependencies": { "@expressive-code/core": "^0.41.3" } }, "sha512-SN8tkIzDpA0HLAscEYD2IVrfLiid6qEdE9QLlGVSxO1KEw7qYvjpbNBQjUjMr5/jvTJ7ys6zysU2vLPHE0sb2g=="], + "@floating-ui/core": ["@floating-ui/core@1.7.3", "", { "dependencies": { "@floating-ui/utils": "^0.2.10" } }, "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w=="], + + "@floating-ui/dom": ["@floating-ui/dom@1.7.4", "", { "dependencies": { "@floating-ui/core": "^1.7.3", "@floating-ui/utils": "^0.2.10" } }, "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA=="], + + "@floating-ui/utils": ["@floating-ui/utils@0.2.10", "", {}, "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ=="], + + "@floating-ui/vue": ["@floating-ui/vue@1.1.9", "", { "dependencies": { "@floating-ui/dom": "^1.7.4", "@floating-ui/utils": "^0.2.10", "vue-demi": ">=0.13.0" } }, "sha512-BfNqNW6KA83Nexspgb9DZuz578R7HT8MZw1CfK9I6Ah4QReNWEJsXWHN+SdmOVLNGmTPDi+fDT535Df5PzMLbQ=="], + + "@headlessui/tailwindcss": ["@headlessui/tailwindcss@0.2.2", "", { "peerDependencies": { "tailwindcss": "^3.0 || ^4.0" } }, "sha512-xNe42KjdyA4kfUKLLPGzME9zkH7Q3rOZ5huFihWNWOQFxnItxPB3/67yBI8/qBfY8nwBRx5GHn4VprsoluVMGw=="], + + "@headlessui/vue": ["@headlessui/vue@1.7.23", "", { "dependencies": { "@tanstack/vue-virtual": "^3.0.0-beta.60" }, "peerDependencies": { "vue": "^3.2.0" } }, "sha512-JzdCNqurrtuu0YW6QaDtR2PIYCKPUWq28csDyMvN4zmGccmE7lz40Is6hc3LA4HFeCI7sekZ/PQMTNmn9I/4Wg=="], + "@humanwhocodes/momoa": ["@humanwhocodes/momoa@2.0.4", "", {}, "sha512-RE815I4arJFtt+FVeU1Tgp9/Xvecacji8w/V6XtXsWWH/wz/eNkNbhb+ny/+PlVZjV0rxQpRSQKNKE3lcktHEA=="], + "@hyperjump/browser": ["@hyperjump/browser@1.3.1", "", { "dependencies": { "@hyperjump/json-pointer": "^1.1.0", "@hyperjump/uri": "^1.2.0", "content-type": "^1.0.5", "just-curry-it": "^5.3.0" } }, "sha512-Le5XZUjnVqVjkgLYv6yyWgALat/0HpB1XaCPuCZ+GCFki9NvXloSZITIJ0H+wRW7mb9At1SxvohKBbNQbrr/cw=="], + + "@hyperjump/json-pointer": ["@hyperjump/json-pointer@1.1.1", "", {}, "sha512-M0T3s7TC2JepoWPMZQn1W6eYhFh06OXwpMqL+8c5wMVpvnCKNsPgpu9u7WyCI03xVQti8JAeAy4RzUa6SYlJLA=="], + + "@hyperjump/json-schema": ["@hyperjump/json-schema@1.16.2", "", { "dependencies": { "@hyperjump/json-pointer": "^1.1.0", "@hyperjump/pact": "^1.2.0", "@hyperjump/uri": "^1.2.0", "content-type": "^1.0.4", "json-stringify-deterministic": "^1.0.12", "just-curry-it": "^5.3.0", "uuid": "^9.0.0" }, "peerDependencies": { "@hyperjump/browser": "^1.1.0" } }, "sha512-MJNvaEFc79+h5rvBPgAJK4OHEUr0RqsKcLC5rc3V9FEsJyQAjnP910deRFoZCE068kX/NrAPPhunMgUMwonPtg=="], + + "@hyperjump/pact": ["@hyperjump/pact@1.4.0", "", {}, "sha512-01Q7VY6BcAkp9W31Fv+ciiZycxZHGlR2N6ba9BifgyclHYHdbaZgITo0U6QMhYRlem4k8pf8J31/tApxvqAz8A=="], + + "@hyperjump/uri": ["@hyperjump/uri@1.3.1", "", {}, "sha512-2ecKymxf6prQMgrNpAvlx4RhsuM5+PFT6oh6uUTZdv5qmBv0RZvxv8LJ7oR30ZxGhdPdZAl4We/1NFc0nqHeAw=="], + "@iconify/types": ["@iconify/types@2.0.0", "", {}, "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg=="], "@iconify/utils": ["@iconify/utils@2.3.0", "", { "dependencies": { "@antfu/install-pkg": "^1.0.0", "@antfu/utils": "^8.1.0", "@iconify/types": "^2.0.0", "debug": "^4.4.0", "globals": "^15.14.0", "kolorist": "^1.8.0", "local-pkg": "^1.0.0", "mlly": "^1.7.4" } }, "sha512-GmQ78prtwYW6EtzXRU1rY+KwOKfz32PD7iJh6Iyqw68GiKuoZ2A6pRtzWONz5VQJbp50mEjXh/7NkumtrAgRKA=="], @@ -186,12 +265,42 @@ "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.34.3", "", { "os": "win32", "cpu": "x64" }, "sha512-OWwz05d++TxzLEv4VnsTz5CmZ6mI6S05sfQGEMrNrQcOEERbX46332IvE7pO/EUiw7jUrrS40z/M7kPyjfl04g=="], + "@internationalized/date": ["@internationalized/date@3.9.0", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-yaN3brAnHRD+4KyyOsJyk49XUvj2wtbNACSqg0bz3u8t2VuzhC8Q5dfRnrSxjnnbDb+ienBnkn1TzQfE154vyg=="], + + "@internationalized/number": ["@internationalized/number@3.6.5", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-6hY4Kl4HPBvtfS62asS/R22JzNNy8vi/Ssev7x6EobfCp+9QIB2hKvI2EtbdJ0VSQacxVNtqhE/NmF/NZ0gm6g=="], + + "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], + + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.4", "", {}, "sha512-VT2+G1VQs/9oz078bLrYbecdZKs912zQlkelYpuf+SXF+QvZDYJlbx/LSx+meSAwdDFnF8FVXW92AVjjkVmgFw=="], + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.30", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-GQ7Nw5G2lTu/BtHTKfXhKHok2WGetd4XYcVKGx00SjAk8GMwgJM3zr6zORiPGuOE+/vkc90KtTosSSvaCjKb2Q=="], + "@jsdevtools/ono": ["@jsdevtools/ono@7.1.3", "", {}, "sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg=="], + "@lezer/common": ["@lezer/common@1.2.3", "", {}, "sha512-w7ojc8ejBqr2REPsWxJjrMFsA/ysDCFICn8zEOR9mrqzOu2amhITYuLD8ag6XZf0CFXDrhKqw7+tW8cX66NaDA=="], + + "@lezer/css": ["@lezer/css@1.3.0", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-pBL7hup88KbI7hXnZV3PQsn43DHy6TWyzuyk2AO9UyoXcDltvIdqWKE1dLL/45JVZ+YZkHe1WVHqO6wugZZWcw=="], + + "@lezer/highlight": ["@lezer/highlight@1.2.1", "", { "dependencies": { "@lezer/common": "^1.0.0" } }, "sha512-Z5duk4RN/3zuVO7Jq0pGLJ3qynpxUVsh7IbUbGj88+uV2ApSAn6kWg2au3iJb+0Zi7kKtqffIESgNcRXWZWmSA=="], + + "@lezer/html": ["@lezer/html@1.3.10", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-dqpT8nISx/p9Do3AchvYGV3qYc4/rKr3IBZxlHmpIKam56P47RSHkSF5f13Vu9hebS1jM0HmtJIwLbWz1VIY6w=="], + + "@lezer/javascript": ["@lezer/javascript@1.5.1", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.1.3", "@lezer/lr": "^1.3.0" } }, "sha512-ATOImjeVJuvgm3JQ/bpo2Tmv55HSScE2MTPnKRMRIPx2cLhHGyX2VnqpHhtIV1tVzIjZDbcWQm+NCTF40ggZVw=="], + + "@lezer/json": ["@lezer/json@1.0.3", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ=="], + + "@lezer/lr": ["@lezer/lr@1.4.2", "", { "dependencies": { "@lezer/common": "^1.0.0" } }, "sha512-pu0K1jCIdnQ12aWNaAVU5bzi7Bd1w54J3ECgANPmYLtQKP0HBj2cE/5coBD66MT10xbtIuUr7tg0Shbsvk0mDA=="], + + "@lezer/xml": ["@lezer/xml@1.0.6", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww=="], + + "@lezer/yaml": ["@lezer/yaml@1.0.3", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.4.0" } }, "sha512-GuBLekbw9jDBDhGur82nuwkxKQ+a3W5H0GfaAthDXcAu+XdpS43VlnxA9E9hllkpSP5ellRDKjLLj7Lu9Wr6xA=="], + "@lorenzo_lewis/starlight-utils": ["@lorenzo_lewis/starlight-utils@0.3.2", "", { "dependencies": { "astro-integration-kit": "^0.18.0" }, "peerDependencies": { "@astrojs/starlight": ">=0.32.0", "astro": ">=5" } }, "sha512-9GCZLyfIUTkXuE39jHjcCSwnOzm6hSGnC8DrHlo2imegiZmZSdG0eBMA/sTb/shLkvCzE2SGCaKM+EwIeO6oDw=="], + "@marijn/find-cluster-break": ["@marijn/find-cluster-break@1.0.2", "", {}, "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g=="], + "@mdx-js/mdx": ["@mdx-js/mdx@3.1.0", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdx": "^2.0.0", "collapse-white-space": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "estree-util-scope": "^1.0.0", "estree-walker": "^3.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "markdown-extensions": "^2.0.0", "recma-build-jsx": "^1.0.0", "recma-jsx": "^1.0.0", "recma-stringify": "^1.0.0", "rehype-recma": "^1.0.0", "remark-mdx": "^3.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "source-map": "^0.7.0", "unified": "^11.0.0", "unist-util-position-from-estree": "^2.0.0", "unist-util-stringify-position": "^4.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-/QxEhPAvGwbQmy1Px8F899L5Uc2KZ6JtXwlCgJmjSTBedwOZkByYcBG4GceIGPXRDsmfxhHazuS+hlOShRLeDw=="], "@mermaid-js/parser": ["@mermaid-js/parser@0.6.2", "", { "dependencies": { "langium": "3.3.1" } }, "sha512-+PO02uGF6L6Cs0Bw8RpGhikVvMWEysfAyl27qTlroUB8jSWr1lL0Sf6zi78ZxlSnmgSY2AMMKVgghnN9jTtwkQ=="], @@ -210,6 +319,8 @@ "@pagefind/windows-x64": ["@pagefind/windows-x64@1.3.0", "", { "os": "win32", "cpu": "x64" }, "sha512-BR1bIRWOMqkf8IoU576YDhij1Wd/Zf2kX/kCI0b2qzCKC8wcc2GQJaaRMCpzvCCrmliO4vtJ6RITp/AnoYUUmQ=="], + "@phosphor-icons/core": ["@phosphor-icons/core@2.1.1", "", {}, "sha512-v4ARvrip4qBCImOE5rmPUylOEK4iiED9ZyKjcvzuezqMaiRASCHKcRIuvvxL/twvLpkfnEODCOJp5dM4eZilxQ=="], + "@readme/better-ajv-errors": ["@readme/better-ajv-errors@2.3.2", "", { "dependencies": { "@babel/code-frame": "^7.22.5", "@babel/runtime": "^7.22.5", "@humanwhocodes/momoa": "^2.0.3", "jsonpointer": "^5.0.0", "leven": "^3.1.0", "picocolors": "^1.1.1" }, "peerDependencies": { "ajv": "4.11.8 - 8" } }, "sha512-T4GGnRAlY3C339NhoUpgJJFsMYko9vIgFAlhgV+/vEGFw66qEY4a4TRJIAZBcX/qT1pq5DvXSme+SQODHOoBrw=="], "@readme/json-schema-ref-parser": ["@readme/json-schema-ref-parser@1.2.0", "", { "dependencies": { "@jsdevtools/ono": "^7.1.3", "@types/json-schema": "^7.0.6", "call-me-maybe": "^1.0.1", "js-yaml": "^4.1.0" } }, "sha512-Bt3QVovFSua4QmHa65EHUmh2xS0XJ3rgTEUPH998f4OW4VVJke3BuS16f+kM0ZLOGdvIrzrPRqwihuv5BAjtrA=="], @@ -218,6 +329,10 @@ "@readme/openapi-schemas": ["@readme/openapi-schemas@3.1.0", "", {}, "sha512-9FC/6ho8uFa8fV50+FPy/ngWN53jaUu4GRXlAjcxIRrzhltJnpKkBG2Tp0IDraFJeWrOpk84RJ9EMEEYzaI1Bw=="], + "@replit/codemirror-css-color-picker": ["@replit/codemirror-css-color-picker@6.3.0", "", { "peerDependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0" } }, "sha512-19biDANghUm7Fz7L1SNMIhK48tagaWuCOHj4oPPxc7hxPGkTVY2lU/jVZ8tsbTKQPVG7BO2CBDzs7CBwb20t4A=="], + + "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-beta.27", "", {}, "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA=="], + "@rollup/pluginutils": ["@rollup/pluginutils@5.2.0", "", { "dependencies": { "@types/estree": "^1.0.0", "estree-walker": "^2.0.2", "picomatch": "^4.0.2" }, "peerDependencies": { "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "optionalPeers": ["rollup"] }, "sha512-qWJ2ZTbmumwiLFomfzTyt5Kng4hwPi9rwCYN4SHb6eaRU1KNO4ccxINHr/VhH4GgPlt1XfSTLX2LBTme8ne4Zw=="], "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.45.1", "", { "os": "android", "cpu": "arm" }, "sha512-NEySIFvMY0ZQO+utJkgoMiCAjMrGvnbDLHvcmlA33UXJpYBCvlBEbMMtV837uCkS+plG2umfhn0T5mMAxGrlRA=="], @@ -260,6 +375,50 @@ "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.45.1", "", { "os": "win32", "cpu": "x64" }, "sha512-M/fKi4sasCdM8i0aWJjCSFm2qEnYRR8AMLG2kxp6wD13+tMGA4Z1tVAuHkNRjud5SW2EM3naLuK35w9twvf6aA=="], + "@scalar/api-client": ["@scalar/api-client@2.5.26", "", { "dependencies": { "@headlessui/tailwindcss": "^0.2.2", "@headlessui/vue": "^1.7.23", "@scalar/components": "0.14.27", "@scalar/draggable": "0.2.0", "@scalar/helpers": "0.0.8", "@scalar/icons": "0.4.7", "@scalar/import": "0.4.19", "@scalar/oas-utils": "0.4.22", "@scalar/object-utils": "1.2.4", "@scalar/openapi-parser": "0.20.1", "@scalar/openapi-types": "0.3.7", "@scalar/postman-to-openapi": "0.3.25", "@scalar/snippetz": "0.4.7", "@scalar/themes": "0.13.14", "@scalar/types": "0.2.13", "@scalar/use-codemirror": "0.12.28", "@scalar/use-hooks": "0.2.4", "@scalar/use-toasts": "0.8.0", "@types/har-format": "^1.2.15", "@vueuse/core": "^11.2.0", "@vueuse/integrations": "^11.2.0", "focus-trap": "^7", "fuse.js": "^7.1.0", "microdiff": "^1.5.0", "nanoid": "5.1.5", "pretty-bytes": "^6.1.1", "pretty-ms": "^8.0.0", "shell-quote": "^1.8.1", "type-fest": "4.41.0", "vue": "^3.5.17", "vue-router": "^4.3.0", "whatwg-mimetype": "^4.0.0", "yaml": "2.8.0", "zod": "3.24.1" } }, "sha512-f5NWAr8aRBpANLAWVhIXlO3ehe/lY47nufoltnpR4QLu0xSNwAa8MdL9hQuU9Cka6cGp/h9NE60ad1qM1m/eFA=="], + + "@scalar/api-reference": ["@scalar/api-reference@1.34.6", "", { "dependencies": { "@floating-ui/vue": "^1.1.7", "@headlessui/vue": "^1.7.23", "@scalar/api-client": "2.5.26", "@scalar/code-highlight": "0.1.9", "@scalar/components": "0.14.27", "@scalar/helpers": "0.0.8", "@scalar/icons": "0.4.7", "@scalar/json-magic": "0.3.1", "@scalar/oas-utils": "0.4.22", "@scalar/object-utils": "1.2.4", "@scalar/openapi-parser": "0.20.1", "@scalar/openapi-types": "0.3.7", "@scalar/snippetz": "0.4.7", "@scalar/themes": "0.13.14", "@scalar/types": "0.2.13", "@scalar/use-hooks": "0.2.4", "@scalar/use-toasts": "0.8.0", "@scalar/workspace-store": "0.14.2", "@unhead/vue": "^1.11.20", "@vueuse/core": "^11.2.0", "flatted": "^3.3.3", "fuse.js": "^7.1.0", "github-slugger": "^2.0.0", "microdiff": "^1.5.0", "nanoid": "5.1.5", "vue": "^3.5.17", "zod": "3.24.1" } }, "sha512-QOLca2cM9yrbLs+Wy/OGIakit2JJXG4yPJDzUcCxXdVXaKJGb2dax3anUITPl9PObW9UBEKCy27ClJFDJSlXkw=="], + + "@scalar/api-reference-react": ["@scalar/api-reference-react@0.7.42", "", { "dependencies": { "@scalar/api-reference": "1.34.6", "@scalar/types": "0.2.13" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0" } }, "sha512-hqy8i7D4DijNbv4MF5ooXP/XkexghBWrtkFf5S9qRUG2VX3JAvhFksyWIqdkpWrOjZ40OPlcashbWKO0s/Hcww=="], + + "@scalar/code-highlight": ["@scalar/code-highlight@0.1.9", "", { "dependencies": { "hast-util-to-text": "^4.0.2", "highlight.js": "^11.9.0", "highlightjs-curl": "^1.3.0", "highlightjs-vue": "^1.0.0", "lowlight": "^3.1.0", "rehype-external-links": "^3.0.0", "rehype-format": "^5.0.0", "rehype-parse": "^9.0.0", "rehype-raw": "^7.0.0", "rehype-sanitize": "^6.0.0", "rehype-stringify": "^10.0.0", "remark-gfm": "^4.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.0", "remark-stringify": "^11.0.0", "unified": "^11.0.4", "unist-util-visit": "^5.0.0" } }, "sha512-WUUVDd1Wk7QJVKWXl/Zdn/VINc2pc1NlWW8VJFYZRm3/hKJwBhi0on7+HjVQNKgUaRy7+zluru5Ckl1gcTHHEg=="], + + "@scalar/components": ["@scalar/components@0.14.27", "", { "dependencies": { "@floating-ui/utils": "^0.2.2", "@floating-ui/vue": "^1.1.7", "@headlessui/vue": "^1.7.23", "@scalar/code-highlight": "0.1.9", "@scalar/helpers": "0.0.8", "@scalar/icons": "0.4.7", "@scalar/oas-utils": "0.4.22", "@scalar/themes": "0.13.14", "@scalar/use-hooks": "0.2.4", "@scalar/use-toasts": "0.8.0", "@vueuse/core": "^11.2.0", "cva": "1.0.0-beta.2", "nanoid": "5.1.5", "pretty-bytes": "^6.1.1", "radix-vue": "^1.9.3", "vue": "^3.5.17", "vue-component-type-helpers": "^3.0.4" } }, "sha512-XMm3oaGy9oBKO7XAoI3mLnr5wKGacefj358XYPNjYGGN9qx60burOdGuFPzCGPnhS++th+O0h7drCXy1mznPfQ=="], + + "@scalar/draggable": ["@scalar/draggable@0.2.0", "", { "dependencies": { "vue": "^3.5.12" } }, "sha512-UetHRB5Bqo5egVYlS21roWBcICmyk8CKh2htsidO+bFGAjl2e7Te+rY0borhNrMclr0xezHlPuLpEs1dvgLS2g=="], + + "@scalar/helpers": ["@scalar/helpers@0.0.8", "", {}, "sha512-9A1CxL3jV7Kl9wGu86/cR/wiJN6J+3tK4WuW3252s2gF+upXsgQRx9WLhFF3xifOP1irIGusitZBiojiKmUSVg=="], + + "@scalar/icons": ["@scalar/icons@0.4.7", "", { "dependencies": { "@phosphor-icons/core": "^2.1.1", "@types/node": "^22.9.0", "chalk": "^5.4.1", "vue": "^3.5.17" } }, "sha512-0qXPGRdZ180TMfejWCPYy7ILszBrAraq4KBhPtcM12ghc5qkncFWWpTm5yXI/vrbm10t7wvtTK08CLZ36CnXlQ=="], + + "@scalar/import": ["@scalar/import@0.4.19", "", { "dependencies": { "@scalar/helpers": "0.0.8", "@scalar/openapi-parser": "0.20.1", "yaml": "2.8.0" } }, "sha512-Y8BB0/msE/y9U1aiU4ioH/sDIVcvxmcEPDfTr2PGcTNamMmwOnAYN7AcEYQarlDo1CVjyzsIdiaEdrgQyZ4y9A=="], + + "@scalar/json-magic": ["@scalar/json-magic@0.3.1", "", { "dependencies": { "@scalar/helpers": "0.0.8", "vue": "^3.5.17", "yaml": "2.8.0" } }, "sha512-vQvl4TckiMT8Txo6S82ETJ4OI+K6iSxLZsjPaq4cEqY+9zVfmIMALFGPj/X5BB8tU3FdluV2yEa8LswsMQ68IA=="], + + "@scalar/oas-utils": ["@scalar/oas-utils@0.4.22", "", { "dependencies": { "@hyperjump/browser": "^1.1.0", "@hyperjump/json-schema": "^1.9.6", "@scalar/helpers": "0.0.8", "@scalar/json-magic": "0.3.1", "@scalar/object-utils": "1.2.4", "@scalar/openapi-types": "0.3.7", "@scalar/themes": "0.13.14", "@scalar/types": "0.2.13", "@scalar/workspace-store": "0.14.2", "@types/har-format": "^1.2.15", "flatted": "^3.3.3", "microdiff": "^1.5.0", "nanoid": "5.1.5", "type-fest": "4.41.0", "yaml": "2.8.0", "zod": "3.24.1" } }, "sha512-a8qvtU9GnHBKPvfflU2UF4mYi61Fc0V626bEgclCicwomrss7ic2MRyrwODmKR72F50Q2jWw0HeKE0DfqOjSPg=="], + + "@scalar/object-utils": ["@scalar/object-utils@1.2.4", "", { "dependencies": { "@scalar/helpers": "0.0.8", "flatted": "^3.3.3", "just-clone": "^6.2.0", "ts-deepmerge": "^7.0.1", "type-fest": "4.41.0" } }, "sha512-lX/+9Sp6euZvbsikGRZiHwmfbLd0oTLTttKbJF9v2EkahSrQUT0WF835Ct2N0R8xSkyQauDhT2xCfuA0QNqDeA=="], + + "@scalar/openapi-parser": ["@scalar/openapi-parser@0.20.1", "", { "dependencies": { "@scalar/json-magic": "0.3.1", "@scalar/openapi-types": "0.3.7", "ajv": "^8.17.1", "ajv-draft-04": "^1.0.0", "ajv-formats": "^3.0.1", "jsonpointer": "^5.0.1", "leven": "^4.0.0", "yaml": "2.8.0" } }, "sha512-rxtuBQ90YsUEDefWU3GAEmvjYr1CvGO6nkDVzbjmWv2aPB3mtK80bCRBgQGTdIdW5XQEWAAmflSKEhcj2Xo5QA=="], + + "@scalar/openapi-types": ["@scalar/openapi-types@0.3.7", "", { "dependencies": { "zod": "3.24.1" } }, "sha512-QHSvHBVDze3+dUwAhIGq6l1iOev4jdoqdBK7QpfeN1Q4h+6qpVEw3EEqBiH0AXUSh/iWwObBv4uMgfIx0aNZ5g=="], + + "@scalar/postman-to-openapi": ["@scalar/postman-to-openapi@0.3.25", "", { "dependencies": { "@scalar/helpers": "0.0.8", "@scalar/oas-utils": "0.4.22", "@scalar/openapi-types": "0.3.7" } }, "sha512-sMf85+uCjmzgyZ8pS7MbVm5FOVj/9SGOT/RX4xDG8LklpE77SQdYXO1G50kj8XEHMwLpsMh5Ufbt5Wft54DqlQ=="], + + "@scalar/snippetz": ["@scalar/snippetz@0.4.7", "", { "dependencies": { "@scalar/types": "0.2.13", "stringify-object": "^5.0.0" } }, "sha512-SvjpZ8qVaGAxoypqsJLAlM95XEjccDXXEvd3ljlCoOYzG06tbMX+g8+Vfsv/FjMXQ0LB3/ZfpYjTrKO8h7ZU4Q=="], + + "@scalar/themes": ["@scalar/themes@0.13.14", "", { "dependencies": { "@scalar/types": "0.2.13", "nanoid": "5.1.5" } }, "sha512-uYqWtzQuLaVAEcxRaLzIINRuocds2I+rj8dCHcg3RMdmvSn9oJ8ysEhOZGqzNE7nL5aD7sh2tFa2E4+iScWSyA=="], + + "@scalar/types": ["@scalar/types@0.2.13", "", { "dependencies": { "@scalar/openapi-types": "0.3.7", "nanoid": "5.1.5", "zod": "3.24.1" } }, "sha512-rO6KGMJqOsBnN/2R4fErMFLpRSPVJElni+HABDpf+ZlLJp2lvxuPn0IXLumK5ytfplUH9iqKgSXjndnZfxSYLQ=="], + + "@scalar/use-codemirror": ["@scalar/use-codemirror@0.12.28", "", { "dependencies": { "@codemirror/autocomplete": "^6.18.3", "@codemirror/commands": "^6.7.1", "@codemirror/lang-css": "^6.3.1", "@codemirror/lang-html": "^6.4.8", "@codemirror/lang-json": "^6.0.0", "@codemirror/lang-xml": "^6.0.0", "@codemirror/lang-yaml": "^6.1.2", "@codemirror/language": "^6.10.7", "@codemirror/lint": "^6.8.4", "@codemirror/state": "^6.5.0", "@codemirror/view": "^6.35.3", "@lezer/common": "^1.2.3", "@lezer/highlight": "^1.2.1", "@replit/codemirror-css-color-picker": "^6.3.0", "@scalar/components": "0.14.27", "codemirror": "^6.0.0", "vue": "^3.5.17" } }, "sha512-4hxuSI1lKmOpEMI5Xvv88wWKj6e3KV6RJUsi46Sb5fOsO3aRgYMDopWvo96nk/4wXD+g2QJIITsSL2Ic7NVnxA=="], + + "@scalar/use-hooks": ["@scalar/use-hooks@0.2.4", "", { "dependencies": { "@scalar/use-toasts": "0.8.0", "@vueuse/core": "^10.10.0", "cva": "1.0.0-beta.2", "tailwind-merge": "^2.5.5", "vue": "^3.5.12", "zod": "3.24.1" } }, "sha512-TXviVV9Cfmei6g24QadnfuFj2r1YkZY56ufsSnwHgLNbtDRd9U9jXGIswXAuA+k7whaEVEgcoZ3Zmq2v5ZLF8w=="], + + "@scalar/use-toasts": ["@scalar/use-toasts@0.8.0", "", { "dependencies": { "nanoid": "^5.1.5", "vue": "^3.5.12", "vue-sonner": "^1.0.3" } }, "sha512-u+o77cdTNZ5ePqHPu8ZcFw1BLlISv+cthN0bR1zJHXmqBjvanFTy2kL+Gmv3eW9HxZiHdqycKVETlYd0mWiqJQ=="], + + "@scalar/workspace-store": ["@scalar/workspace-store@0.14.2", "", { "dependencies": { "@scalar/code-highlight": "0.1.9", "@scalar/helpers": "0.0.8", "@scalar/json-magic": "0.3.1", "@scalar/openapi-parser": "0.20.1", "@scalar/types": "0.2.13", "@sinclair/typebox": "https://raw.githubusercontent.com/DemonHa/typebox/refs/heads/amrit/build-2/target/sinclair-typebox-0.34.40.tgz", "github-slugger": "^2.0.0", "type-fest": "4.41.0", "vue": "^3.5.17", "yaml": "2.8.0" } }, "sha512-FLI//S2kxS4NxdKZ+SaMTUoMI7n2hZID/JznAid02+WU35QVA+Y3ioose7VzPRpDmPxeF3lhXgcPpcZ811yIjA=="], + "@shikijs/core": ["@shikijs/core@3.8.1", "", { "dependencies": { "@shikijs/types": "3.8.1", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-uTSXzUBQ/IgFcUa6gmGShCHr4tMdR3pxUiiWKDm8pd42UKJdYhkAYsAmHX5mTwybQ5VyGDgTjW4qKSsRvGSang=="], "@shikijs/engine-javascript": ["@shikijs/engine-javascript@3.8.1", "", { "dependencies": { "@shikijs/types": "3.8.1", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.3" } }, "sha512-rZRp3BM1llrHkuBPAdYAzjlF7OqlM0rm/7EWASeCcY7cRYZIrOnGIHE9qsLz5TCjGefxBFnwgIECzBs2vmOyKA=="], @@ -274,8 +433,22 @@ "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.0.2", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="], + "@sinclair/typebox": ["@sinclair/typebox@https://raw.githubusercontent.com/DemonHa/typebox/refs/heads/amrit/build-2/target/sinclair-typebox-0.34.40.tgz", {}], + "@swc/helpers": ["@swc/helpers@0.5.17", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5IKx/Y13RsYd+sauPb2x+U/xZikHjolzfuDgTAl/Tdf3Q8rslRvC19NKDLgAJQ6wsqADk10ntlv08nPFw/gO/A=="], + "@tanstack/virtual-core": ["@tanstack/virtual-core@3.13.12", "", {}, "sha512-1YBOJfRHV4sXUmWsFSf5rQor4Ss82G8dQWLRbnk3GA4jeP8hQt1hxXh0tmflpC0dz3VgEv/1+qwPyLeWkQuPFA=="], + + "@tanstack/vue-virtual": ["@tanstack/vue-virtual@3.13.12", "", { "dependencies": { "@tanstack/virtual-core": "3.13.12" }, "peerDependencies": { "vue": "^2.7.0 || ^3.0.0" } }, "sha512-vhF7kEU9EXWXh+HdAwKJ2m3xaOnTTmgcdXcF2pim8g4GvI7eRrk2YRuV5nUlZnd/NbCIX4/Ja2OZu5EjJL06Ww=="], + + "@types/babel__core": ["@types/babel__core@7.20.5", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="], + + "@types/babel__generator": ["@types/babel__generator@7.27.0", "", { "dependencies": { "@babel/types": "^7.0.0" } }, "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg=="], + + "@types/babel__template": ["@types/babel__template@7.4.4", "", { "dependencies": { "@babel/parser": "^7.1.0", "@babel/types": "^7.0.0" } }, "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A=="], + + "@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="], + "@types/d3": ["@types/d3@7.4.3", "", { "dependencies": { "@types/d3-array": "*", "@types/d3-axis": "*", "@types/d3-brush": "*", "@types/d3-chord": "*", "@types/d3-color": "*", "@types/d3-contour": "*", "@types/d3-delaunay": "*", "@types/d3-dispatch": "*", "@types/d3-drag": "*", "@types/d3-dsv": "*", "@types/d3-ease": "*", "@types/d3-fetch": "*", "@types/d3-force": "*", "@types/d3-format": "*", "@types/d3-geo": "*", "@types/d3-hierarchy": "*", "@types/d3-interpolate": "*", "@types/d3-path": "*", "@types/d3-polygon": "*", "@types/d3-quadtree": "*", "@types/d3-random": "*", "@types/d3-scale": "*", "@types/d3-scale-chromatic": "*", "@types/d3-selection": "*", "@types/d3-shape": "*", "@types/d3-time": "*", "@types/d3-time-format": "*", "@types/d3-timer": "*", "@types/d3-transition": "*", "@types/d3-zoom": "*" } }, "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww=="], "@types/d3-array": ["@types/d3-array@3.2.1", "", {}, "sha512-Y2Jn2idRrLzUfAKV2LyRImR+y4oa2AntrgID95SHJxuMUrkNXmanDSed71sRNZysveJVt1hLLemQZIady0FpEg=="], @@ -348,6 +521,8 @@ "@types/geojson": ["@types/geojson@7946.0.16", "", {}, "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg=="], + "@types/har-format": ["@types/har-format@1.2.16", "", {}, "sha512-fluxdy7ryD3MV6h8pTfTYpy/xQzCFC7m89nOH9y94cNqJ1mDIDPut7MnRHI3F6qRmh/cT2fUjG1MLdCNb4hE9A=="], + "@types/hast": ["@types/hast@3.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ=="], "@types/js-yaml": ["@types/js-yaml@4.0.9", "", {}, "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg=="], @@ -364,14 +539,58 @@ "@types/node": ["@types/node@17.0.45", "", {}, "sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw=="], + "@types/react": ["@types/react@19.1.12", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-cMoR+FoAf/Jyq6+Df2/Z41jISvGZZ2eTlnsaJRptmZ76Caldwy1odD4xTr/gNV9VLj0AWgg/nmkevIyUfIIq5w=="], + + "@types/react-dom": ["@types/react-dom@19.1.9", "", { "peerDependencies": { "@types/react": "^19.0.0" } }, "sha512-qXRuZaOsAdXKFyOhRBg6Lqqc0yay13vN7KrIg4L7N4aaHN68ma9OK3NE1BoDFgFOTfM7zg+3/8+2n8rLUH3OKQ=="], + "@types/sax": ["@types/sax@1.2.7", "", { "dependencies": { "@types/node": "*" } }, "sha512-rO73L89PJxeYM3s3pPPjiPgVVcymqU490g0YO5n5By0k2Erzj6tay/4lr1CHAAU4JyOWd1rpQ8bCf6cZfHU96A=="], "@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="], "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="], + "@types/web-bluetooth": ["@types/web-bluetooth@0.0.20", "", {}, "sha512-g9gZnnXVq7gM7v3tJCWV/qw7w+KeOlSHAhgF9RytFyifW6AF61hdT2ucrYhPq9hLs5JIryeupHV3qGk95dH9ow=="], + "@ungap/structured-clone": ["@ungap/structured-clone@1.3.0", "", {}, "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g=="], + "@unhead/dom": ["@unhead/dom@1.11.20", "", { "dependencies": { "@unhead/schema": "1.11.20", "@unhead/shared": "1.11.20" } }, "sha512-jgfGYdOH+xHJF/j8gudjsYu3oIjFyXhCWcgKaw3vQnT616gSqyqnGQGOItL+BQtQZACKNISwIfx5PuOtztMKLA=="], + + "@unhead/schema": ["@unhead/schema@1.11.20", "", { "dependencies": { "hookable": "^5.5.3", "zhead": "^2.2.4" } }, "sha512-0zWykKAaJdm+/Y7yi/Yds20PrUK7XabLe9c3IRcjnwYmSWY6z0Cr19VIs3ozCj8P+GhR+/TI2mwtGlueCEYouA=="], + + "@unhead/shared": ["@unhead/shared@1.11.20", "", { "dependencies": { "@unhead/schema": "1.11.20", "packrup": "^0.1.2" } }, "sha512-1MOrBkGgkUXS+sOKz/DBh4U20DNoITlJwpmvSInxEUNhghSNb56S0RnaHRq0iHkhrO/cDgz2zvfdlRpoPLGI3w=="], + + "@unhead/vue": ["@unhead/vue@1.11.20", "", { "dependencies": { "@unhead/schema": "1.11.20", "@unhead/shared": "1.11.20", "hookable": "^5.5.3", "unhead": "1.11.20" }, "peerDependencies": { "vue": ">=2.7 || >=3" } }, "sha512-sqQaLbwqY9TvLEGeq8Fd7+F2TIuV3nZ5ihVISHjWpAM3y7DwNWRU7NmT9+yYT+2/jw1Vjwdkv5/HvDnvCLrgmg=="], + + "@vitejs/plugin-react": ["@vitejs/plugin-react@4.7.0", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-beta.27", "@types/babel__core": "^7.20.5", "react-refresh": "^0.17.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA=="], + + "@vue/compiler-core": ["@vue/compiler-core@3.5.21", "", { "dependencies": { "@babel/parser": "^7.28.3", "@vue/shared": "3.5.21", "entities": "^4.5.0", "estree-walker": "^2.0.2", "source-map-js": "^1.2.1" } }, "sha512-8i+LZ0vf6ZgII5Z9XmUvrCyEzocvWT+TeR2VBUVlzIH6Tyv57E20mPZ1bCS+tbejgUgmjrEh7q/0F0bibskAmw=="], + + "@vue/compiler-dom": ["@vue/compiler-dom@3.5.21", "", { "dependencies": { "@vue/compiler-core": "3.5.21", "@vue/shared": "3.5.21" } }, "sha512-jNtbu/u97wiyEBJlJ9kmdw7tAr5Vy0Aj5CgQmo+6pxWNQhXZDPsRr1UWPN4v3Zf82s2H3kF51IbzZ4jMWAgPlQ=="], + + "@vue/compiler-sfc": ["@vue/compiler-sfc@3.5.21", "", { "dependencies": { "@babel/parser": "^7.28.3", "@vue/compiler-core": "3.5.21", "@vue/compiler-dom": "3.5.21", "@vue/compiler-ssr": "3.5.21", "@vue/shared": "3.5.21", "estree-walker": "^2.0.2", "magic-string": "^0.30.18", "postcss": "^8.5.6", "source-map-js": "^1.2.1" } }, "sha512-SXlyk6I5eUGBd2v8Ie7tF6ADHE9kCR6mBEuPyH1nUZ0h6Xx6nZI29i12sJKQmzbDyr2tUHMhhTt51Z6blbkTTQ=="], + + "@vue/compiler-ssr": ["@vue/compiler-ssr@3.5.21", "", { "dependencies": { "@vue/compiler-dom": "3.5.21", "@vue/shared": "3.5.21" } }, "sha512-vKQ5olH5edFZdf5ZrlEgSO1j1DMA4u23TVK5XR1uMhvwnYvVdDF0nHXJUblL/GvzlShQbjhZZ2uvYmDlAbgo9w=="], + + "@vue/devtools-api": ["@vue/devtools-api@6.6.4", "", {}, "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g=="], + + "@vue/reactivity": ["@vue/reactivity@3.5.21", "", { "dependencies": { "@vue/shared": "3.5.21" } }, "sha512-3ah7sa+Cwr9iiYEERt9JfZKPw4A2UlbY8RbbnH2mGCE8NwHkhmlZt2VsH0oDA3P08X3jJd29ohBDtX+TbD9AsA=="], + + "@vue/runtime-core": ["@vue/runtime-core@3.5.21", "", { "dependencies": { "@vue/reactivity": "3.5.21", "@vue/shared": "3.5.21" } }, "sha512-+DplQlRS4MXfIf9gfD1BOJpk5RSyGgGXD/R+cumhe8jdjUcq/qlxDawQlSI8hCKupBlvM+3eS1se5xW+SuNAwA=="], + + "@vue/runtime-dom": ["@vue/runtime-dom@3.5.21", "", { "dependencies": { "@vue/reactivity": "3.5.21", "@vue/runtime-core": "3.5.21", "@vue/shared": "3.5.21", "csstype": "^3.1.3" } }, "sha512-3M2DZsOFwM5qI15wrMmNF5RJe1+ARijt2HM3TbzBbPSuBHOQpoidE+Pa+XEaVN+czbHf81ETRoG1ltztP2em8w=="], + + "@vue/server-renderer": ["@vue/server-renderer@3.5.21", "", { "dependencies": { "@vue/compiler-ssr": "3.5.21", "@vue/shared": "3.5.21" }, "peerDependencies": { "vue": "3.5.21" } }, "sha512-qr8AqgD3DJPJcGvLcJKQo2tAc8OnXRcfxhOJCPF+fcfn5bBGz7VCcO7t+qETOPxpWK1mgysXvVT/j+xWaHeMWA=="], + + "@vue/shared": ["@vue/shared@3.5.21", "", {}, "sha512-+2k1EQpnYuVuu3N7atWyG3/xoFWIVJZq4Mz8XNOdScFI0etES75fbny/oU4lKWk/577P1zmg0ioYvpGEDZ3DLw=="], + + "@vueuse/core": ["@vueuse/core@11.3.0", "", { "dependencies": { "@types/web-bluetooth": "^0.0.20", "@vueuse/metadata": "11.3.0", "@vueuse/shared": "11.3.0", "vue-demi": ">=0.14.10" } }, "sha512-7OC4Rl1f9G8IT6rUfi9JrKiXy4bfmHhZ5x2Ceojy0jnd3mHNEvV4JaRygH362ror6/NZ+Nl+n13LPzGiPN8cKA=="], + + "@vueuse/integrations": ["@vueuse/integrations@11.3.0", "", { "dependencies": { "@vueuse/core": "11.3.0", "@vueuse/shared": "11.3.0", "vue-demi": ">=0.14.10" }, "peerDependencies": { "async-validator": "^4", "axios": "^1", "change-case": "^5", "drauu": "^0.4", "focus-trap": "^7", "fuse.js": "^7", "idb-keyval": "^6", "jwt-decode": "^4", "nprogress": "^0.2", "qrcode": "^1.5", "sortablejs": "^1", "universal-cookie": "^7" }, "optionalPeers": ["async-validator", "axios", "change-case", "drauu", "focus-trap", "fuse.js", "idb-keyval", "jwt-decode", "nprogress", "qrcode", "sortablejs", "universal-cookie"] }, "sha512-5fzRl0apQWrDezmobchoiGTkGw238VWESxZHazfhP3RM7pDSiyXy18QbfYkILoYNTd23HPAfQTJpkUc5QbkwTw=="], + + "@vueuse/metadata": ["@vueuse/metadata@11.3.0", "", {}, "sha512-pwDnDspTqtTo2HwfLw4Rp6yywuuBdYnPYDq+mO38ZYKGebCUQC/nVj/PXSiK9HX5otxLz8Fn7ECPbjiRz2CC3g=="], + + "@vueuse/shared": ["@vueuse/shared@11.3.0", "", { "dependencies": { "vue-demi": ">=0.14.10" } }, "sha512-P8gSSWQeucH5821ek2mn/ciCk+MS/zoRKqdQIM3bHq6p7GXDAJLmnRRKmF5F65sAVJIfzQlwR3aDzwCn10s8hA=="], + "acorn": ["acorn@8.15.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg=="], "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], @@ -380,6 +599,8 @@ "ajv-draft-04": ["ajv-draft-04@1.0.0", "", { "peerDependencies": { "ajv": "^8.5.0" }, "optionalPeers": ["ajv"] }, "sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw=="], + "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], + "ansi-align": ["ansi-align@3.0.1", "", { "dependencies": { "string-width": "^4.1.0" } }, "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w=="], "ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="], @@ -392,6 +613,8 @@ "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], + "aria-hidden": ["aria-hidden@1.2.6", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="], + "aria-query": ["aria-query@5.3.2", "", {}, "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw=="], "array-iterate": ["array-iterate@2.0.1", "", {}, "sha512-I1jXZMjAgCMmxT4qxXfPXa6SthSoE8h6gkSI9BGGNv8mP8G/v0blc+qFnZu6K42vTOiuME596QaLO0TP3Lk0xg=="], @@ -428,10 +651,14 @@ "brotli": ["brotli@1.3.3", "", { "dependencies": { "base64-js": "^1.1.2" } }, "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg=="], + "browserslist": ["browserslist@4.25.4", "", { "dependencies": { "caniuse-lite": "^1.0.30001737", "electron-to-chromium": "^1.5.211", "node-releases": "^2.0.19", "update-browserslist-db": "^1.1.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-4jYpcjabC606xJ3kw2QwGEZKX0Aw7sgQdZCvIK9dhVSPh76BKo+C+btT1RRofH7B+8iNpEbgGNVWiLki5q93yg=="], + "call-me-maybe": ["call-me-maybe@1.0.2", "", {}, "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ=="], "camelcase": ["camelcase@8.0.0", "", {}, "sha512-8WB3Jcas3swSvjIeA2yvCJ+Miyz5l1ZmB6HFb9R1317dt9LCQoswg/BGrmAmkWVEszSrrg4RwmO46qIm2OEnSA=="], + "caniuse-lite": ["caniuse-lite@1.0.30001739", "", {}, "sha512-y+j60d6ulelrNSwpPyrHdl+9mJnQzHBr08xm48Qno0nSk4h3Qojh+ziv2qE6rXf4k3tadF4o1J/1tAbVm1NtnA=="], + "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], "chalk": ["chalk@5.4.1", "", {}, "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w=="], @@ -458,6 +685,8 @@ "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], + "codemirror": ["codemirror@6.0.2", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/commands": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/lint": "^6.0.0", "@codemirror/search": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0" } }, "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw=="], + "collapse-white-space": ["collapse-white-space@2.1.0", "", {}, "sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw=="], "color": ["color@4.2.3", "", { "dependencies": { "color-convert": "^2.0.1", "color-string": "^1.9.0" } }, "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A=="], @@ -476,12 +705,18 @@ "confbox": ["confbox@0.2.2", "", {}, "sha512-1NB+BKqhtNipMsov4xI/NnhCKp9XG9NamYp5PVm9klAT0fsrNPjaFICsCFhNhwZJKNh7zB/3q8qXz0E9oaMNtQ=="], + "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], + + "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], + "cookie": ["cookie@1.0.2", "", {}, "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA=="], "cookie-es": ["cookie-es@1.2.2", "", {}, "sha512-+W7VmiVINB+ywl1HGXJXmrqkOhpKrIiVZV6tQuV54ZyQC7MMuBt81Vc336GMLoHBq5hV/F9eXgt5Mnx0Rha5Fg=="], "cose-base": ["cose-base@1.0.3", "", { "dependencies": { "layout-base": "^1.0.0" } }, "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg=="], + "crelt": ["crelt@1.0.6", "", {}, "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g=="], + "cross-fetch": ["cross-fetch@3.2.0", "", { "dependencies": { "node-fetch": "^2.7.0" } }, "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q=="], "crossws": ["crossws@0.3.5", "", { "dependencies": { "uncrypto": "^0.1.3" } }, "sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA=="], @@ -492,6 +727,10 @@ "cssesc": ["cssesc@3.0.0", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="], + "csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="], + + "cva": ["cva@1.0.0-beta.2", "", { "dependencies": { "clsx": "^2.1.1" }, "peerDependencies": { "typescript": ">= 4.5.5 < 6" }, "optionalPeers": ["typescript"] }, "sha512-dqcOFe247I5pKxfuzqfq3seLL5iMYsTgo40Uw7+pKZAntPgFtR7Tmy59P5IVIq/XgB0NQWoIvYDt9TwHkuK8Cg=="], + "cytoscape": ["cytoscape@3.32.1", "", {}, "sha512-dbeqFTLYEwlFg7UGtcZhCCG/2WayX72zK3Sq323CEX29CY81tYfVhw1MIdduCtpstB0cTOhJswWlM/OEB3Xp+Q=="], "cytoscape-cose-bilkent": ["cytoscape-cose-bilkent@4.1.0", "", { "dependencies": { "cose-base": "^1.0.0" }, "peerDependencies": { "cytoscape": "^3.2.0" } }, "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ=="], @@ -598,6 +837,8 @@ "dset": ["dset@3.1.4", "", {}, "sha512-2QF/g9/zTaPDc3BjNcVTGoBbXBgYfMTTceLaYcFJ/W9kggFUkhxD/hMEeuLKbugyef9SqAx8cpgwlIP/jinUTA=="], + "electron-to-chromium": ["electron-to-chromium@1.5.212", "", {}, "sha512-gE7ErIzSW+d8jALWMcOIgf+IB6lpfsg6NwOhPVwKzDtN2qcBix47vlin4yzSregYDxTCXOUqAZjVY/Z3naS7ww=="], + "emoji-regex": ["emoji-regex@10.4.0", "", {}, "sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw=="], "entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="], @@ -610,6 +851,8 @@ "esbuild": ["esbuild@0.25.8", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.8", "@esbuild/android-arm": "0.25.8", "@esbuild/android-arm64": "0.25.8", "@esbuild/android-x64": "0.25.8", "@esbuild/darwin-arm64": "0.25.8", "@esbuild/darwin-x64": "0.25.8", "@esbuild/freebsd-arm64": "0.25.8", "@esbuild/freebsd-x64": "0.25.8", "@esbuild/linux-arm": "0.25.8", "@esbuild/linux-arm64": "0.25.8", "@esbuild/linux-ia32": "0.25.8", "@esbuild/linux-loong64": "0.25.8", "@esbuild/linux-mips64el": "0.25.8", "@esbuild/linux-ppc64": "0.25.8", "@esbuild/linux-riscv64": "0.25.8", "@esbuild/linux-s390x": "0.25.8", "@esbuild/linux-x64": "0.25.8", "@esbuild/netbsd-arm64": "0.25.8", "@esbuild/netbsd-x64": "0.25.8", "@esbuild/openbsd-arm64": "0.25.8", "@esbuild/openbsd-x64": "0.25.8", "@esbuild/openharmony-arm64": "0.25.8", "@esbuild/sunos-x64": "0.25.8", "@esbuild/win32-arm64": "0.25.8", "@esbuild/win32-ia32": "0.25.8", "@esbuild/win32-x64": "0.25.8" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-vVC0USHGtMi8+R4Kz8rt6JhEWLxsv9Rnu/lGYbPR8u47B+DCBksq9JarW0zOO7bs37hyOK1l2/oqtbciutL5+Q=="], + "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], + "escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="], "esprima": ["esprima@4.0.1", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="], @@ -642,22 +885,30 @@ "fdir": ["fdir@6.4.6", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w=="], + "flatted": ["flatted@3.3.3", "", {}, "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg=="], + "flattie": ["flattie@1.1.1", "", {}, "sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ=="], + "focus-trap": ["focus-trap@7.6.5", "", { "dependencies": { "tabbable": "^6.2.0" } }, "sha512-7Ke1jyybbbPZyZXFxEftUtxFGLMpE2n6A+z//m4CRDlj0hW+o3iYSmh8nFlYMurOiJVDmJRilUQtJr08KfIxlg=="], + "fontace": ["fontace@0.3.0", "", { "dependencies": { "@types/fontkit": "^2.0.8", "fontkit": "^2.0.4" } }, "sha512-czoqATrcnxgWb/nAkfyIrRp6Q8biYj7nGnL6zfhTcX+JKKpWHFBnb8uNMw/kZr7u++3Y3wYSYoZgHkCcsuBpBg=="], "fontkit": ["fontkit@2.0.4", "", { "dependencies": { "@swc/helpers": "^0.5.12", "brotli": "^1.3.2", "clone": "^2.1.2", "dfa": "^1.2.0", "fast-deep-equal": "^3.1.3", "restructure": "^3.0.0", "tiny-inflate": "^1.0.3", "unicode-properties": "^1.4.0", "unicode-trie": "^2.0.0" } }, "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + "fuse.js": ["fuse.js@7.1.0", "", {}, "sha512-trLf4SzuuUxfusZADLINj+dE8clK1frKdmqiJNb1Es75fmI5oY6X2mxLVUciLLjxqw/xr72Dhy+lER6dGd02FQ=="], + + "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], + "get-east-asian-width": ["get-east-asian-width@1.3.0", "", {}, "sha512-vpeMIQKxczTD/0s2CdEWHcb0eeJe6TFjxb+J5xgX7hScxqrGuyjmv4c1D4A/gelKfyox0gJJwIHF+fLjeaM8kQ=="], + "get-own-enumerable-keys": ["get-own-enumerable-keys@1.0.0", "", {}, "sha512-PKsK2FSrQCyxcGHsGrLDcK0lx+0Ke+6e8KFFozA9/fIQLhQzPaRvJFdcz7+Axg3jUH/Mq+NI4xa5u/UT2tQskA=="], + "github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="], "globals": ["globals@15.15.0", "", {}, "sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg=="], - "gsap": ["gsap@3.13.0", "", {}, "sha512-QL7MJ2WMjm1PHWsoFrAQH/J8wUeqZvMtHO58qdekHpCfhvhSL4gSiz6vJf5EeMP0LOn3ZCprL2ki/gjED8ghVw=="], - "h3": ["h3@1.15.3", "", { "dependencies": { "cookie-es": "^1.2.2", "crossws": "^0.3.4", "defu": "^6.1.4", "destr": "^2.0.5", "iron-webcrypto": "^1.2.1", "node-mock-http": "^1.0.0", "radix3": "^1.1.2", "ufo": "^1.6.1", "uncrypto": "^0.1.3" } }, "sha512-z6GknHqyX0h9aQaTx22VZDf6QyZn+0Nh+Ym8O/u0SGSkyF5cuTJYKlc8MkzW3Nzf9LE1ivcpmYC3FUGpywhuUQ=="], "hachure-fill": ["hachure-fill@0.5.2", "", {}, "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg=="], @@ -684,6 +935,8 @@ "hast-util-raw": ["hast-util-raw@9.1.0", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "hast-util-from-parse5": "^8.0.0", "hast-util-to-parse5": "^8.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "parse5": "^7.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw=="], + "hast-util-sanitize": ["hast-util-sanitize@5.0.2", "", { "dependencies": { "@types/hast": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "unist-util-position": "^5.0.0" } }, "sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg=="], + "hast-util-select": ["hast-util-select@6.0.4", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "bcp-47-match": "^2.0.0", "comma-separated-tokens": "^2.0.0", "css-selector-parser": "^3.0.0", "devlop": "^1.0.0", "direction": "^2.0.0", "hast-util-has-property": "^3.0.0", "hast-util-to-string": "^3.0.0", "hast-util-whitespace": "^3.0.0", "nth-check": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-RqGS1ZgI0MwxLaKLDxjprynNzINEkRHY2i8ln4DDjgv9ZhcYVIHN9rlpiYsqtFwrgpYU361SyWDQcGNIBVu3lw=="], "hast-util-to-estree": ["hast-util-to-estree@3.1.3", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-attach-comments": "^3.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-48+B/rJWAp0jamNbAAf9M7Uf//UVqAoMmgXhBdxTDJLGKY+LRnZ99qcG+Qjl5HfMpYNzS5v4EAwVEF34LeAj7w=="], @@ -702,6 +955,14 @@ "hastscript": ["hastscript@9.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-parse-selector": "^4.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0" } }, "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w=="], + "highlight.js": ["highlight.js@11.11.1", "", {}, "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w=="], + + "highlightjs-curl": ["highlightjs-curl@1.3.0", "", {}, "sha512-50UEfZq1KR0Lfk2Tr6xb/MUIZH3h10oNC0OTy9g7WELcs5Fgy/mKN1vEhuKTkKbdo8vr5F9GXstu2eLhApfQ3A=="], + + "highlightjs-vue": ["highlightjs-vue@1.0.0", "", {}, "sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA=="], + + "hookable": ["hookable@5.5.3", "", {}, "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ=="], + "html-escaper": ["html-escaper@3.0.3", "", {}, "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ=="], "html-void-elements": ["html-void-elements@3.0.0", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="], @@ -722,6 +983,8 @@ "iron-webcrypto": ["iron-webcrypto@1.2.1", "", {}, "sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg=="], + "is-absolute-url": ["is-absolute-url@4.0.1", "", {}, "sha512-/51/TKE88Lmm7Gc4/8btclNXWS+g50wXhYJq8HWIBAGUBnoAdRu1aXeh364t/O7wXDAcTJDP8PNuNKWUDWie+A=="], + "is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="], "is-alphanumerical": ["is-alphanumerical@2.0.1", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="], @@ -738,20 +1001,32 @@ "is-inside-container": ["is-inside-container@1.0.0", "", { "dependencies": { "is-docker": "^3.0.0" }, "bin": { "is-inside-container": "cli.js" } }, "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA=="], + "is-obj": ["is-obj@3.0.0", "", {}, "sha512-IlsXEHOjtKhpN8r/tRFj2nDyTmHvcfNeu/nrRIcXE17ROeatXchkojffa1SpdqW4cr/Fj6QkEf/Gn4zf6KKvEQ=="], + "is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="], - "is-wsl": ["is-wsl@3.1.0", "", { "dependencies": { "is-inside-container": "^1.0.0" } }, "sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw=="], + "is-regexp": ["is-regexp@3.1.0", "", {}, "sha512-rbku49cWloU5bSMI+zaRaXdQHXnthP6DZ/vLnfdSKyL4zUzuWnomtOEiZZOd+ioQ+avFo/qau3KPTc7Fjy1uPA=="], - "iso8601-duration": ["iso8601-duration@2.1.2", "", {}, "sha512-yXteYUiKv6x8seaDzyBwnZtPpmx766KfvQuaVNyPifYOjmPdOo3ajd4phDNa7Y5mTQGnXsNEcXFtVun1FjYXxQ=="], + "is-wsl": ["is-wsl@3.1.0", "", { "dependencies": { "is-inside-container": "^1.0.0" } }, "sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw=="], "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], "js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="], + "jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="], + "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + "json-stringify-deterministic": ["json-stringify-deterministic@1.0.12", "", {}, "sha512-q3PN0lbUdv0pmurkBNdJH3pfFvOTL/Zp0lquqpvcjfKzt6Y0j49EPHAmVHCAS4Ceq/Y+PejWTzyiVpoY71+D6g=="], + + "json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="], + "jsonpointer": ["jsonpointer@5.0.1", "", {}, "sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ=="], + "just-clone": ["just-clone@6.2.0", "", {}, "sha512-1IynUYEc/HAwxhi3WDpIpxJbZpMCvvrrmZVqvj9EhpvbH8lls7HhdhiByjL7DkAaWlLIzpC0Xc/VPvy/UxLNjA=="], + + "just-curry-it": ["just-curry-it@5.3.0", "", {}, "sha512-silMIRiFjUWlfaDhkgSzpuAyQ6EX/o09Eu8ZBfmFwQMbax7+LQzeIU2CBrICT6Ne4l86ITCGvUCBpCubWYy0Yw=="], + "katex": ["katex@0.16.22", "", { "dependencies": { "commander": "^8.3.0" }, "bin": { "katex": "cli.js" } }, "sha512-XCHRdUw4lf3SKBaJe4EvgqIuWwkPSo9XoeO8GjQW94Bp7TWv9hNhzZjZ+OH9yf1UmLygb7DIT5GSFQiyt16zYg=="], "khroma": ["khroma@2.1.0", "", {}, "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw=="], @@ -766,9 +1041,7 @@ "layout-base": ["layout-base@1.0.2", "", {}, "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg=="], - "leven": ["leven@3.1.0", "", {}, "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A=="], - - "lite-youtube-embed": ["lite-youtube-embed@0.3.3", "", {}, "sha512-gFfVVnj6NRjxVfJKo3qoLtpi0v5mn3AcR4eKD45wrxQuxzveFJUb+7Cr6uV6n+DjO8X3p0UzPPquhGt0H/y+NA=="], + "leven": ["leven@4.0.0", "", {}, "sha512-puehA3YKku3osqPlNuzGDUHq8WpwXupUg1V6NXdV38G+gr+gkBwFC8g1b/+YcIvp8gnqVIus+eJCH/eGsRmJNw=="], "local-pkg": ["local-pkg@1.1.1", "", { "dependencies": { "mlly": "^1.7.4", "pkg-types": "^2.0.1", "quansync": "^0.2.8" } }, "sha512-WunYko2W1NcdfAFpuLUoucsgULmgDBRkdxHxWQ7mK0cQqwPiy8E1enjuRBrhLtZkB5iScJ1XIPdhVEFK8aOLSg=="], @@ -776,6 +1049,8 @@ "longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="], + "lowlight": ["lowlight@3.3.0", "", { "dependencies": { "@types/hast": "^3.0.0", "devlop": "^1.0.0", "highlight.js": "~11.11.0" } }, "sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ=="], + "lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], "magic-string": ["magic-string@0.30.17", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0" } }, "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA=="], @@ -828,6 +1103,8 @@ "mermaid": ["mermaid@11.9.0", "", { "dependencies": { "@braintree/sanitize-url": "^7.0.4", "@iconify/utils": "^2.1.33", "@mermaid-js/parser": "^0.6.2", "@types/d3": "^7.4.3", "cytoscape": "^3.29.3", "cytoscape-cose-bilkent": "^4.1.0", "cytoscape-fcose": "^2.2.0", "d3": "^7.9.0", "d3-sankey": "^0.12.3", "dagre-d3-es": "7.0.11", "dayjs": "^1.11.13", "dompurify": "^3.2.5", "katex": "^0.16.22", "khroma": "^2.1.0", "lodash-es": "^4.17.21", "marked": "^16.0.0", "roughjs": "^4.6.6", "stylis": "^4.3.6", "ts-dedent": "^2.2.0", "uuid": "^11.1.0" } }, "sha512-YdPXn9slEwO0omQfQIsW6vS84weVQftIyyTGAZCwM//MGhPzL1+l6vO6bkf0wnP4tHigH1alZ5Ooy3HXI2gOag=="], + "microdiff": ["microdiff@1.5.0", "", {}, "sha512-Drq+/THMvDdzRYrK0oxJmOKiC24ayUV8ahrt8l3oRK51PWt6gdtrIGrlIH3pT/lFh1z93FbAcidtsHcWbnRz8Q=="], + "micromark": ["micromark@4.0.2", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA=="], "micromark-core-commonmark": ["micromark-core-commonmark@2.0.3", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg=="], @@ -906,7 +1183,7 @@ "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - "nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], + "nanoid": ["nanoid@5.1.5", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-Ir/+ZpE9fDsNH0hQ3C68uyThDXzYcim2EqcZ8zn8Chtt1iylPT9xXJB0kPCnqzgcEGikO9RxSrh63MsmVCU7Fw=="], "neotraverse": ["neotraverse@0.6.18", "", {}, "sha512-Z4SmBUweYa09+o6pG+eASabEpP6QkQ70yHj351pQoEXIs8uHbaU2DWVmzBANKgflPa47A50PtB2+NgRpQvr7vA=="], @@ -918,6 +1195,8 @@ "node-mock-http": ["node-mock-http@1.0.1", "", {}, "sha512-0gJJgENizp4ghds/Ywu2FCmcRsgBTmRQzYPZm61wy+Em2sBarSka0OhQS5huLBg6od1zkNpnWMCZloQDFVvOMQ=="], + "node-releases": ["node-releases@2.0.19", "", {}, "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw=="], + "normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="], "nth-check": ["nth-check@2.1.1", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="], @@ -940,6 +1219,8 @@ "package-manager-detector": ["package-manager-detector@1.3.0", "", {}, "sha512-ZsEbbZORsyHuO00lY1kV3/t72yp6Ysay6Pd17ZAlNGuGwmWDLCJxFpRs0IzfXfj1o4icJOkUEioexFHzyPurSQ=="], + "packrup": ["packrup@0.1.2", "", {}, "sha512-ZcKU7zrr5GlonoS9cxxrb5HVswGnyj6jQvwFBa6p5VFw7G71VAHcUKL5wyZSU/ECtPM/9gacWxy2KFQKt1gMNA=="], + "pagefind": ["pagefind@1.3.0", "", { "optionalDependencies": { "@pagefind/darwin-arm64": "1.3.0", "@pagefind/darwin-x64": "1.3.0", "@pagefind/linux-arm64": "1.3.0", "@pagefind/linux-x64": "1.3.0", "@pagefind/windows-x64": "1.3.0" }, "bin": { "pagefind": "lib/runner/bin.cjs" } }, "sha512-8KPLGT5g9s+olKMRTU9LFekLizkVIu9tes90O1/aigJ0T5LmyPqTzGJrETnSw3meSYg58YH7JTzhTTW/3z6VAw=="], "pako": ["pako@0.2.9", "", {}, "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA=="], @@ -948,14 +1229,14 @@ "parse-latin": ["parse-latin@7.0.0", "", { "dependencies": { "@types/nlcst": "^2.0.0", "@types/unist": "^3.0.0", "nlcst-to-string": "^4.0.0", "unist-util-modify-children": "^4.0.0", "unist-util-visit-children": "^3.0.0", "vfile": "^6.0.0" } }, "sha512-mhHgobPPua5kZ98EF4HWiH167JWBfl4pvAIXXdbaVohtK7a6YBOy56kvhCqduqyo/f3yrHFWmqmiMg/BkBkYYQ=="], + "parse-ms": ["parse-ms@3.0.0", "", {}, "sha512-Tpb8Z7r7XbbtBTrM9UhpkzzaMrqA2VXMT3YChzYltwV3P3pM6t8wl7TvpMnSTosz1aQAdVib7kdoys7vYOPerw=="], + "parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="], "path-data-parser": ["path-data-parser@0.1.0", "", {}, "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w=="], "pathe": ["pathe@1.1.2", "", {}, "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ=="], - "phosphor-astro": ["phosphor-astro@2.1.0", "", {}, "sha512-qyYUlxF8DbfHc+85DDGPL04ghNBwrVK75EsNsBfYOChiCeCRwAwfbHxj/qqPrrSFPMgh9cUyEvgKYjI/7bjCUA=="], - "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], "picomatch": ["picomatch@4.0.3", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="], @@ -972,6 +1253,10 @@ "postcss-selector-parser": ["postcss-selector-parser@6.1.2", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg=="], + "pretty-bytes": ["pretty-bytes@6.1.1", "", {}, "sha512-mQUvGU6aUFQ+rNvTIAcZuWGRT9a6f6Yrg9bHs4ImKF+HZCEK+plBvnAZYSIQztknZF2qnzNtr6F8s0+IuptdlQ=="], + + "pretty-ms": ["pretty-ms@8.0.0", "", { "dependencies": { "parse-ms": "^3.0.0" } }, "sha512-ASJqOugUF1bbzI35STMBUpZqdfYKlJugy6JBziGi2EE+AL5JPJGSzvpeVXojxrr0ViUYoToUjb5kjSEGf7Y83Q=="], + "prismjs": ["prismjs@1.30.0", "", {}, "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw=="], "prompts": ["prompts@2.4.2", "", { "dependencies": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q=="], @@ -980,8 +1265,16 @@ "quansync": ["quansync@0.2.10", "", {}, "sha512-t41VRkMYbkHyCYmOvx/6URnN80H7k4X0lLdBMGsz+maAwrJQYB1djpV6vHrQIBE0WBSGqhtEHrK9U3DWWH8v7A=="], + "radix-vue": ["radix-vue@1.9.17", "", { "dependencies": { "@floating-ui/dom": "^1.6.7", "@floating-ui/vue": "^1.1.0", "@internationalized/date": "^3.5.4", "@internationalized/number": "^3.5.3", "@tanstack/vue-virtual": "^3.8.1", "@vueuse/core": "^10.11.0", "@vueuse/shared": "^10.11.0", "aria-hidden": "^1.2.4", "defu": "^6.1.4", "fast-deep-equal": "^3.1.3", "nanoid": "^5.0.7" }, "peerDependencies": { "vue": ">= 3.2.0" } }, "sha512-mVCu7I2vXt1L2IUYHTt0sZMz7s1K2ZtqKeTIxG3yC5mMFfLBG4FtE1FDeRMpDd+Hhg/ybi9+iXmAP1ISREndoQ=="], + "radix3": ["radix3@1.1.2", "", {}, "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA=="], + "react": ["react@19.1.1", "", {}, "sha512-w8nqGImo45dmMIfljjMwOGtbmC/mk4CMYhWIicdSflH91J9TyCyczcPFXJzrZ/ZXcgGRFeP6BU0BEJTw6tZdfQ=="], + + "react-dom": ["react-dom@19.1.1", "", { "dependencies": { "scheduler": "^0.26.0" }, "peerDependencies": { "react": "^19.1.1" } }, "sha512-Dlq/5LAZgF0Gaz6yiqZCf6VCcZs1ghAJyrsu84Q/GT0gV+mCxbfmKNoGRKBYMJ8IEdGPqu49YWXD02GCknEDkw=="], + + "react-refresh": ["react-refresh@0.17.0", "", {}, "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ=="], + "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], "recast": ["recast@0.23.11", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA=="], @@ -1004,6 +1297,8 @@ "rehype-expressive-code": ["rehype-expressive-code@0.41.3", "", { "dependencies": { "expressive-code": "^0.41.3" } }, "sha512-8d9Py4c/V6I/Od2VIXFAdpiO2kc0SV2qTJsRAaqSIcM9aruW4ASLNe2kOEo1inXAAkIhpFzAHTc358HKbvpNUg=="], + "rehype-external-links": ["rehype-external-links@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "hast-util-is-element": "^3.0.0", "is-absolute-url": "^4.0.0", "space-separated-tokens": "^2.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-yp+e5N9V3C6bwBeAC4n796kc86M4gJCdlVhiMTxIrJG5UHDMh+PJANf9heqORJbt1nrCbDwIlAZKjANIaVBbvw=="], + "rehype-format": ["rehype-format@5.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-format": "^1.0.0" } }, "sha512-zvmVru9uB0josBVpr946OR8ui7nJEdzZobwLOOqHb/OOD88W0Vk2SqLwoVOj0fM6IPCCO6TaV9CvQvJMWwukFQ=="], "rehype-parse": ["rehype-parse@9.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-from-html": "^2.0.0", "unified": "^11.0.0" } }, "sha512-ksCzCD0Fgfh7trPDxr2rSylbwq9iYDkSn8TCDmEJ49ljEUBxDVCzCHv7QNzZOfODanX4+bWQ4WZqLCRWYLfhag=="], @@ -1012,6 +1307,8 @@ "rehype-recma": ["rehype-recma@1.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "hast-util-to-estree": "^3.0.0" } }, "sha512-lqA4rGUf1JmacCNWWZx0Wv1dHqMwxzsDWYMTowuplHF3xH0N/MmrZ/G3BDZnzAkRmxDadujCjaKM2hqYdCBOGw=="], + "rehype-sanitize": ["rehype-sanitize@6.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-sanitize": "^5.0.0" } }, "sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg=="], + "rehype-stringify": ["rehype-stringify@10.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-html": "^9.0.0", "unified": "^11.0.0" } }, "sha512-k9ecfXHmIPuFVI61B9DeLPN0qFHfawM6RsuX48hoqlaKSF61RskNjSm1lI8PhBEM0MRdLxVVm4WmTqJQccH9mA=="], "remark-directive": ["remark-directive@3.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-directive": "^3.0.0", "micromark-extension-directive": "^3.0.0", "unified": "^11.0.0" } }, "sha512-gwglrEQEZcZYgVyG1tQuA+h58EZfq5CSULw7J90AFuCTyib1thgHPoqQ+h9iFvU6R+vnZ5oNFQR5QKgGpk741A=="], @@ -1052,10 +1349,14 @@ "sax": ["sax@1.4.1", "", {}, "sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg=="], + "scheduler": ["scheduler@0.26.0", "", {}, "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA=="], + "semver": ["semver@7.7.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA=="], "sharp": ["sharp@0.34.3", "", { "dependencies": { "color": "^4.2.3", "detect-libc": "^2.0.4", "semver": "^7.7.2" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.34.3", "@img/sharp-darwin-x64": "0.34.3", "@img/sharp-libvips-darwin-arm64": "1.2.0", "@img/sharp-libvips-darwin-x64": "1.2.0", "@img/sharp-libvips-linux-arm": "1.2.0", "@img/sharp-libvips-linux-arm64": "1.2.0", "@img/sharp-libvips-linux-ppc64": "1.2.0", "@img/sharp-libvips-linux-s390x": "1.2.0", "@img/sharp-libvips-linux-x64": "1.2.0", "@img/sharp-libvips-linuxmusl-arm64": "1.2.0", "@img/sharp-libvips-linuxmusl-x64": "1.2.0", "@img/sharp-linux-arm": "0.34.3", "@img/sharp-linux-arm64": "0.34.3", "@img/sharp-linux-ppc64": "0.34.3", "@img/sharp-linux-s390x": "0.34.3", "@img/sharp-linux-x64": "0.34.3", "@img/sharp-linuxmusl-arm64": "0.34.3", "@img/sharp-linuxmusl-x64": "0.34.3", "@img/sharp-wasm32": "0.34.3", "@img/sharp-win32-arm64": "0.34.3", "@img/sharp-win32-ia32": "0.34.3", "@img/sharp-win32-x64": "0.34.3" } }, "sha512-eX2IQ6nFohW4DbvHIOLRB3MHFpYqaqvXd3Tp5e/T/dSH83fxaNJQRvDMhASmkNTsNTVF2/OOopzRCt7xokgPfg=="], + "shell-quote": ["shell-quote@1.8.3", "", {}, "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw=="], + "shiki": ["shiki@3.8.1", "", { "dependencies": { "@shikijs/core": "3.8.1", "@shikijs/engine-javascript": "3.8.1", "@shikijs/engine-oniguruma": "3.8.1", "@shikijs/langs": "3.8.1", "@shikijs/themes": "3.8.1", "@shikijs/types": "3.8.1", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-+MYIyjwGPCaegbpBeFN9+oOifI8CKiKG3awI/6h3JeT85c//H2wDW/xCJEGuQ5jPqtbboKNqNy+JyX9PYpGwNg=="], "simple-swizzle": ["simple-swizzle@0.2.2", "", { "dependencies": { "is-arrayish": "^0.3.1" } }, "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg=="], @@ -1072,32 +1373,36 @@ "space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="], - "srt-parser-2": ["srt-parser-2@1.2.3", "", { "bin": { "srt-parser-2": "bin/index.js" } }, "sha512-dANP1AyJTI503H0/kXwRza+7QxDB3BqeFvEKTF4MI9lQcBe8JbRUQTKVIGzGABJCwBovEYavZ2Qsdm/s8XKz8A=="], - "starlight-openapi": ["starlight-openapi@0.19.1", "", { "dependencies": { "@readme/openapi-parser": "^2.7.0", "github-slugger": "^2.0.0", "url-template": "^3.1.1" }, "peerDependencies": { "@astrojs/markdown-remark": ">=6.0.1", "@astrojs/starlight": ">=0.34.0", "astro": ">=5.5.0" } }, "sha512-hEwbLlxpWaEceJM6Cj66Amh/CCDH5mbZ/MO55byWSUmBGmitkmWMUMTPhbSj8Y7MD2SQ7uJ83tcnfaDpfwxk4Q=="], "starlight-sidebar-topics": ["starlight-sidebar-topics@0.6.0", "", { "dependencies": { "picomatch": "^4.0.2" }, "peerDependencies": { "@astrojs/starlight": ">=0.32.0" } }, "sha512-ysmOR7zaHYKtk18/mpW4MbEMDioR/ZBsisu9bdQrq0v9BlHWpW7gAdWlqFWO9zdv1P7l0Mo1WKd0wJ0UtqOVEQ=="], - "starlight-theme-next": ["starlight-theme-next@0.3.2", "", { "peerDependencies": { "@astrojs/starlight": ">=0.34" } }, "sha512-GQGhZ67nZ09pWVQoecl1N+H/1EUkUOvLVpjqOCHlkSotCblwrWrj4guEsdF9aKkNqiyTi6zzwZ5sxQospvdHOg=="], - "starlight-theme-rapide": ["starlight-theme-rapide@0.5.1", "", { "peerDependencies": { "@astrojs/starlight": ">=0.34.0" } }, "sha512-QRF6mzcYHLEX5UpUvOPXVVwISS298siIJLcKextoMLhXcnF12nX+IYJ0LNxFk9XaPbX9uDXIieSBJf5Pztkteg=="], - "starlight-videos": ["starlight-videos@0.3.0", "", { "dependencies": { "@astro-community/astro-embed-youtube": "^0.5.6", "hastscript": "^9.0.0", "iso8601-duration": "^2.1.2", "srt-parser-2": "^1.2.3", "unist-util-visit": "^5.0.0" }, "peerDependencies": { "@astrojs/starlight": ">=0.34.0" } }, "sha512-1yvFUEn3P+ZjuGr5COswQp14cZdIvsGjg9lqDIyW5clCrZaBiDMSNPLYngyQozaDbrublEp6/V9HbJR6sGnSOA=="], - "stream-replace-string": ["stream-replace-string@2.0.0", "", {}, "sha512-TlnjJ1C0QrmxRNrON00JvaFFlNh5TTG00APw23j74ET7gkQpTASi6/L2fuiav8pzK715HXtUeClpBTw2NPSn6w=="], "string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], "stringify-entities": ["stringify-entities@4.0.4", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="], + "stringify-object": ["stringify-object@5.0.0", "", { "dependencies": { "get-own-enumerable-keys": "^1.0.0", "is-obj": "^3.0.0", "is-regexp": "^3.1.0" } }, "sha512-zaJYxz2FtcMb4f+g60KsRNFOpVMUyuJgA51Zi5Z1DOTC3S59+OQiVOzE9GZt0x72uBGWKsQIuBKeF9iusmKFsg=="], + "strip-ansi": ["strip-ansi@7.1.0", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ=="], + "style-mod": ["style-mod@4.1.2", "", {}, "sha512-wnD1HyVqpJUI2+eKZ+eo1UwghftP6yuFheBqqe+bWCotBjC2K1YnteJILRMs3SM4V/0dLEW1SC27MWP5y+mwmw=="], + "style-to-js": ["style-to-js@1.1.17", "", { "dependencies": { "style-to-object": "1.0.9" } }, "sha512-xQcBGDxJb6jjFCTzvQtfiPn6YvvP2O8U1MDIPNfJQlWMYfktPy+iGsHE7cssjs7y84d9fQaK4UF3RIJaAHSoYA=="], "style-to-object": ["style-to-object@1.0.9", "", { "dependencies": { "inline-style-parser": "0.2.4" } }, "sha512-G4qppLgKu/k6FwRpHiGiKPaPTFcG3g4wNVX/Qsfu+RqQM30E7Tyu/TEgxcL9PNLF5pdRLwQdE3YKKf+KF2Dzlw=="], "stylis": ["stylis@4.3.6", "", {}, "sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ=="], + "tabbable": ["tabbable@6.2.0", "", {}, "sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew=="], + + "tailwind-merge": ["tailwind-merge@2.6.0", "", {}, "sha512-P+Vu1qXfzediirmHOC3xKGAYeZtPcV9g76X+xg2FD4tYgR71ewMA35Y3sCz3zhiN/dwefRpJX0yBcgwi1fXNQA=="], + + "tailwindcss": ["tailwindcss@4.1.12", "", {}, "sha512-DzFtxOi+7NsFf7DBtI3BJsynR+0Yp6etH+nRPTbpWnS2pZBaSksv/JGctNwSWzbFjp0vxSqknaUylseZqMDGrA=="], + "tiny-inflate": ["tiny-inflate@1.0.3", "", {}, "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw=="], "tiny-invariant": ["tiny-invariant@1.3.3", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="], @@ -1114,6 +1419,8 @@ "ts-dedent": ["ts-dedent@2.2.0", "", {}, "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ=="], + "ts-deepmerge": ["ts-deepmerge@7.0.3", "", {}, "sha512-Du/ZW2RfwV/D4cmA5rXafYjBQVuvu4qGiEEla4EmEHVHgRdx68Gftx7i66jn2bzHPwSVZY36Ae6OuDn9el4ZKA=="], + "tsconfck": ["tsconfck@3.1.6", "", { "peerDependencies": { "typescript": "^5.0.0" }, "optionalPeers": ["typescript"], "bin": { "tsconfck": "bin/tsconfck.js" } }, "sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w=="], "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], @@ -1128,6 +1435,10 @@ "uncrypto": ["uncrypto@0.1.3", "", {}, "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q=="], + "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], + + "unhead": ["unhead@1.11.20", "", { "dependencies": { "@unhead/dom": "1.11.20", "@unhead/schema": "1.11.20", "@unhead/shared": "1.11.20", "hookable": "^5.5.3" } }, "sha512-3AsNQC0pjwlLqEYHLjtichGWankK8yqmocReITecmpB1H0aOabeESueyy+8X1gyJx4ftZVwo9hqQ4O3fPWffCA=="], + "unicode-properties": ["unicode-properties@1.4.1", "", { "dependencies": { "base64-js": "^1.3.0", "unicode-trie": "^2.0.0" } }, "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg=="], "unicode-trie": ["unicode-trie@2.0.0", "", { "dependencies": { "pako": "^0.2.5", "tiny-inflate": "^1.0.0" } }, "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ=="], @@ -1158,6 +1469,8 @@ "unstorage": ["unstorage@1.16.1", "", { "dependencies": { "anymatch": "^3.1.3", "chokidar": "^4.0.3", "destr": "^2.0.5", "h3": "^1.15.3", "lru-cache": "^10.4.3", "node-fetch-native": "^1.6.6", "ofetch": "^1.4.1", "ufo": "^1.6.1" }, "peerDependencies": { "@azure/app-configuration": "^1.8.0", "@azure/cosmos": "^4.2.0", "@azure/data-tables": "^13.3.0", "@azure/identity": "^4.6.0", "@azure/keyvault-secrets": "^4.9.0", "@azure/storage-blob": "^12.26.0", "@capacitor/preferences": "^6.0.3 || ^7.0.0", "@deno/kv": ">=0.9.0", "@netlify/blobs": "^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0", "@planetscale/database": "^1.19.0", "@upstash/redis": "^1.34.3", "@vercel/blob": ">=0.27.1", "@vercel/kv": "^1.0.1", "aws4fetch": "^1.0.20", "db0": ">=0.2.1", "idb-keyval": "^6.2.1", "ioredis": "^5.4.2", "uploadthing": "^7.4.4" }, "optionalPeers": ["@azure/app-configuration", "@azure/cosmos", "@azure/data-tables", "@azure/identity", "@azure/keyvault-secrets", "@azure/storage-blob", "@capacitor/preferences", "@deno/kv", "@netlify/blobs", "@planetscale/database", "@upstash/redis", "@vercel/blob", "@vercel/kv", "aws4fetch", "db0", "idb-keyval", "ioredis", "uploadthing"] }, "sha512-gdpZ3guLDhz+zWIlYP1UwQ259tG5T5vYRzDaHMkQ1bBY1SQPutvZnrRjTFaWUUpseErJIgAZS51h6NOcZVZiqQ=="], + "update-browserslist-db": ["update-browserslist-db@1.1.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw=="], + "url-template": ["url-template@3.1.1", "", {}, "sha512-4oszoaEKE/mQOtAmdMWqIRHmkxWkUZMnXFnjQ5i01CuRSK3uluxcH1MRVVVWmhlnzT1SCDfKxxficm2G37qzCA=="], "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], @@ -1186,10 +1499,24 @@ "vscode-uri": ["vscode-uri@3.0.8", "", {}, "sha512-AyFQ0EVmsOZOlAnxoFOGOq1SQDWAB7C6aqMGS23svWAllfOaxbuFvcT8D1i8z3Gyn8fraVeZNNmN6e9bxxXkKw=="], + "vue": ["vue@3.5.21", "", { "dependencies": { "@vue/compiler-dom": "3.5.21", "@vue/compiler-sfc": "3.5.21", "@vue/runtime-dom": "3.5.21", "@vue/server-renderer": "3.5.21", "@vue/shared": "3.5.21" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-xxf9rum9KtOdwdRkiApWL+9hZEMWE90FHh8yS1+KJAiWYh+iGWV1FquPjoO9VUHQ+VIhsCXNNyZ5Sf4++RVZBA=="], + + "vue-component-type-helpers": ["vue-component-type-helpers@3.0.6", "", {}, "sha512-6CRM8X7EJqWCJOiKPvSLQG+hJPb/Oy2gyJx3pLjUEhY7PuaCthQu3e0zAGI1lqUBobrrk9IT0K8sG2GsCluxoQ=="], + + "vue-demi": ["vue-demi@0.14.10", "", { "peerDependencies": { "@vue/composition-api": "^1.0.0-rc.1", "vue": "^3.0.0-0 || ^2.6.0" }, "optionalPeers": ["@vue/composition-api"], "bin": { "vue-demi-fix": "bin/vue-demi-fix.js", "vue-demi-switch": "bin/vue-demi-switch.js" } }, "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg=="], + + "vue-router": ["vue-router@4.5.1", "", { "dependencies": { "@vue/devtools-api": "^6.6.4" }, "peerDependencies": { "vue": "^3.2.0" } }, "sha512-ogAF3P97NPm8fJsE4by9dwSYtDwXIY1nFY9T6DyQnGHd1E2Da94w9JIolpe42LJGIl0DwOHBi8TcRPlPGwbTtw=="], + + "vue-sonner": ["vue-sonner@1.3.2", "", {}, "sha512-UbZ48E9VIya3ToiRHAZUbodKute/z/M1iT8/3fU8zEbwBRE11AKuHikssv18LMk2gTTr6eMQT4qf6JoLHWuj/A=="], + + "w3c-keyname": ["w3c-keyname@2.2.8", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="], + "web-namespaces": ["web-namespaces@2.0.1", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="], "webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], + "whatwg-mimetype": ["whatwg-mimetype@4.0.0", "", {}, "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg=="], + "whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], "which-pm-runs": ["which-pm-runs@1.1.0", "", {}, "sha512-n1brCuqClxfFfq/Rb0ICg9giSZqCS+pLtccdag6C2HyufBrh3fBOiy9nb6ggRMvWOVH5GrdJskj5iGTZNxd7SA=="], @@ -1200,6 +1527,10 @@ "xxhash-wasm": ["xxhash-wasm@1.1.0", "", {}, "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA=="], + "yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], + + "yaml": ["yaml@2.8.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ=="], + "yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], "yocto-queue": ["yocto-queue@1.2.1", "", {}, "sha512-AyeEbWOu/TAXdxlV9wmGcR0+yh2j3vYPGOECcIj2S7MkrLyC7ne+oye2BKTItt0ii2PHk4cDy+95+LshzbXnGg=="], @@ -1208,6 +1539,8 @@ "yoctocolors": ["yoctocolors@2.1.1", "", {}, "sha512-GQHQqAopRhwU8Kt1DDM8NjibDXHC8eoh1erhGAJPEyveY9qqVeXvVikNKrDz69sHowPMorbPUrH/mx8c50eiBQ=="], + "zhead": ["zhead@2.2.4", "", {}, "sha512-8F0OI5dpWIA5IGG5NHUg9staDwz/ZPxZtvGVf01j7vHqSyZ0raHY+78atOVxRqb73AotX22uV1pXt3gYSstGag=="], + "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], "zod-to-json-schema": ["zod-to-json-schema@3.24.6", "", { "peerDependencies": { "zod": "^3.24.1" } }, "sha512-h/z3PKvcTcTetyjl1fkj79MHNEjm+HpD6NXheWjzOekY7kV+lwDYnHw+ivHkijnCSMz1yJaWBD9vu/Fcmk+vEg=="], @@ -1218,8 +1551,78 @@ "@antfu/install-pkg/tinyexec": ["tinyexec@1.0.1", "", {}, "sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw=="], + "@babel/core/@babel/parser": ["@babel/parser@7.28.3", "", { "dependencies": { "@babel/types": "^7.28.2" }, "bin": "./bin/babel-parser.js" }, "sha512-7+Ey1mAgYqFAx2h0RuoxcQT5+MlG3GTV0TQrgr7/ZliKsm/MNDxVVutlWaziMq7wJNAz8MTqz55XLpWvva6StA=="], + + "@babel/core/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + + "@babel/generator/@babel/parser": ["@babel/parser@7.28.3", "", { "dependencies": { "@babel/types": "^7.28.2" }, "bin": "./bin/babel-parser.js" }, "sha512-7+Ey1mAgYqFAx2h0RuoxcQT5+MlG3GTV0TQrgr7/ZliKsm/MNDxVVutlWaziMq7wJNAz8MTqz55XLpWvva6StA=="], + + "@babel/generator/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], + + "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + + "@babel/helper-module-imports/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@babel/helpers/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@babel/template/@babel/parser": ["@babel/parser@7.28.3", "", { "dependencies": { "@babel/types": "^7.28.2" }, "bin": "./bin/babel-parser.js" }, "sha512-7+Ey1mAgYqFAx2h0RuoxcQT5+MlG3GTV0TQrgr7/ZliKsm/MNDxVVutlWaziMq7wJNAz8MTqz55XLpWvva6StA=="], + + "@babel/template/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@babel/traverse/@babel/parser": ["@babel/parser@7.28.3", "", { "dependencies": { "@babel/types": "^7.28.2" }, "bin": "./bin/babel-parser.js" }, "sha512-7+Ey1mAgYqFAx2h0RuoxcQT5+MlG3GTV0TQrgr7/ZliKsm/MNDxVVutlWaziMq7wJNAz8MTqz55XLpWvva6StA=="], + + "@babel/traverse/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@hyperjump/json-schema/uuid": ["uuid@9.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="], + + "@readme/better-ajv-errors/leven": ["leven@3.1.0", "", {}, "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A=="], + "@rollup/pluginutils/estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], + "@scalar/api-client/zod": ["zod@3.24.1", "", {}, "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A=="], + + "@scalar/api-reference/zod": ["zod@3.24.1", "", {}, "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A=="], + + "@scalar/icons/@types/node": ["@types/node@22.18.0", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-m5ObIqwsUp6BZzyiy4RdZpzWGub9bqLJMvZDD0QMXhxjqMHMENlj+SqF5QxoUwaQNFe+8kz8XM8ZQhqkQPTgMQ=="], + + "@scalar/oas-utils/zod": ["zod@3.24.1", "", {}, "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A=="], + + "@scalar/openapi-types/zod": ["zod@3.24.1", "", {}, "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A=="], + + "@scalar/types/zod": ["zod@3.24.1", "", {}, "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A=="], + + "@scalar/use-hooks/@vueuse/core": ["@vueuse/core@10.11.1", "", { "dependencies": { "@types/web-bluetooth": "^0.0.20", "@vueuse/metadata": "10.11.1", "@vueuse/shared": "10.11.1", "vue-demi": ">=0.14.8" } }, "sha512-guoy26JQktXPcz+0n3GukWIy/JDNKti9v6VEMu6kV2sYBsWuGiTU8OWdg+ADfUbHg3/3DlqySDe7JmdHrktiww=="], + + "@scalar/use-hooks/zod": ["zod@3.24.1", "", {}, "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A=="], + + "@types/babel__core/@babel/parser": ["@babel/parser@7.28.3", "", { "dependencies": { "@babel/types": "^7.28.2" }, "bin": "./bin/babel-parser.js" }, "sha512-7+Ey1mAgYqFAx2h0RuoxcQT5+MlG3GTV0TQrgr7/ZliKsm/MNDxVVutlWaziMq7wJNAz8MTqz55XLpWvva6StA=="], + + "@types/babel__core/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@types/babel__generator/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@types/babel__template/@babel/parser": ["@babel/parser@7.28.3", "", { "dependencies": { "@babel/types": "^7.28.2" }, "bin": "./bin/babel-parser.js" }, "sha512-7+Ey1mAgYqFAx2h0RuoxcQT5+MlG3GTV0TQrgr7/ZliKsm/MNDxVVutlWaziMq7wJNAz8MTqz55XLpWvva6StA=="], + + "@types/babel__template/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@types/babel__traverse/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@vue/compiler-core/@babel/parser": ["@babel/parser@7.28.3", "", { "dependencies": { "@babel/types": "^7.28.2" }, "bin": "./bin/babel-parser.js" }, "sha512-7+Ey1mAgYqFAx2h0RuoxcQT5+MlG3GTV0TQrgr7/ZliKsm/MNDxVVutlWaziMq7wJNAz8MTqz55XLpWvva6StA=="], + + "@vue/compiler-core/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], + + "@vue/compiler-core/estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], + + "@vue/compiler-sfc/@babel/parser": ["@babel/parser@7.28.3", "", { "dependencies": { "@babel/types": "^7.28.2" }, "bin": "./bin/babel-parser.js" }, "sha512-7+Ey1mAgYqFAx2h0RuoxcQT5+MlG3GTV0TQrgr7/ZliKsm/MNDxVVutlWaziMq7wJNAz8MTqz55XLpWvva6StA=="], + + "@vue/compiler-sfc/estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], + + "@vue/compiler-sfc/magic-string": ["magic-string@0.30.18", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-yi8swmWbO17qHhwIBNeeZxTceJMeBvWJaId6dyvTSOwTipqeHhMhOrz6513r1sOKnpvQ7zkhlG8tPrpilwTxHQ=="], + "ansi-align/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], "anymatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], @@ -1244,10 +1647,26 @@ "pkg-types/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + "postcss/nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], + "prompts/kleur": ["kleur@3.0.3", "", {}, "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w=="], + "radix-vue/@vueuse/core": ["@vueuse/core@10.11.1", "", { "dependencies": { "@types/web-bluetooth": "^0.0.20", "@vueuse/metadata": "10.11.1", "@vueuse/shared": "10.11.1", "vue-demi": ">=0.14.8" } }, "sha512-guoy26JQktXPcz+0n3GukWIy/JDNKti9v6VEMu6kV2sYBsWuGiTU8OWdg+ADfUbHg3/3DlqySDe7JmdHrktiww=="], + + "radix-vue/@vueuse/shared": ["@vueuse/shared@10.11.1", "", { "dependencies": { "vue-demi": ">=0.14.8" } }, "sha512-LHpC8711VFZlDaYUXEBbFBCQ7GS3dVU9mjOhhMhXP6txTV4EhYQg/KGnQuvt/sPAtoUKq7VVUnL6mVtFoL42sA=="], + "recast/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], + "@scalar/use-hooks/@vueuse/core/@vueuse/metadata": ["@vueuse/metadata@10.11.1", "", {}, "sha512-IGa5FXd003Ug1qAZmyE8wF3sJ81xGLSqTqtQ6jaVfkeZ4i5kS2mwQF61yhVqojRnenVew5PldLyRgvdl4YYuSw=="], + + "@scalar/use-hooks/@vueuse/core/@vueuse/shared": ["@vueuse/shared@10.11.1", "", { "dependencies": { "vue-demi": ">=0.14.8" } }, "sha512-LHpC8711VFZlDaYUXEBbFBCQ7GS3dVU9mjOhhMhXP6txTV4EhYQg/KGnQuvt/sPAtoUKq7VVUnL6mVtFoL42sA=="], + + "@vue/compiler-core/@babel/parser/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@vue/compiler-sfc/@babel/parser/@babel/types": ["@babel/types@7.28.2", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ=="], + + "@vue/compiler-sfc/magic-string/@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], + "ansi-align/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], "ansi-align/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], @@ -1298,6 +1717,8 @@ "mlly/pkg-types/confbox": ["confbox@0.1.8", "", {}, "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w=="], + "radix-vue/@vueuse/core/@vueuse/metadata": ["@vueuse/metadata@10.11.1", "", {}, "sha512-IGa5FXd003Ug1qAZmyE8wF3sJ81xGLSqTqtQ6jaVfkeZ4i5kS2mwQF61yhVqojRnenVew5PldLyRgvdl4YYuSw=="], + "ansi-align/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], } } diff --git a/website/bun.lockb b/website/bun.lockb new file mode 100755 index 000000000..3be93289a Binary files /dev/null and b/website/bun.lockb differ diff --git a/website/package.json b/website/package.json index aa6f74799..d387af88b 100644 --- a/website/package.json +++ b/website/package.json @@ -7,23 +7,30 @@ "start": "astro dev", "build": "astro build", "preview": "astro preview", - "astro": "astro" + "astro": "astro", + "prebuild": "bun scripts/fix-local-spec-complete.js && bun scripts/conditional-cloud-spec.js", + "generate:local-spec": "bun scripts/fix-local-spec-complete.js", + "generate:cloud-spec": "bun scripts/generate-cloud-spec.js", + "generate:cloud-spec-force": "FORCE_UPDATE=true bun scripts/generate-cloud-spec.js", + "api:dev": "astro dev --open /api", + "api:local": "astro dev --open /api-reference/local", + "api:cloud": "astro dev --open /api-reference/cloud" }, "dependencies": { + "@astrojs/react": "^4.3.0", "@astrojs/starlight": "^0.35.1", "@lorenzo_lewis/starlight-utils": "^0.3.2", + "@scalar/api-reference-react": "^0.7.42", + "@types/react": "^19.1.12", "astro": "^5.6.1", "astro-mermaid": "^1.0.4", - "gsap": "^3.13.0", "mermaid": "^11.9.0", - "phosphor-astro": "^2.1.0", + "react": "^19.1.1", + "react-dom": "^19.1.1", "sharp": "^0.34.3", "starlight-openapi": "^0.19.1", "starlight-sidebar-topics": "^0.6.0", - "starlight-theme-next": "^0.3.2", "starlight-theme-rapide": "^0.5.1", - "starlight-videos": "^0.3.0", "unist-util-visit": "^5.0.0" - }, - "packageManager": "yarn@1.22.22" + } } diff --git a/website/public/assets/fonts/StudioFeixenSans-Bold.otf b/website/public/assets/fonts/StudioFeixenSans-Bold.otf new file mode 100644 index 000000000..481b7b413 Binary files /dev/null and b/website/public/assets/fonts/StudioFeixenSans-Bold.otf differ diff --git a/website/public/assets/fonts/StudioFeixenSans-Book.otf b/website/public/assets/fonts/StudioFeixenSans-Book.otf new file mode 100644 index 000000000..80f60011f Binary files /dev/null and b/website/public/assets/fonts/StudioFeixenSans-Book.otf differ diff --git a/website/public/assets/fonts/StudioFeixenSans-Light.otf b/website/public/assets/fonts/StudioFeixenSans-Light.otf new file mode 100644 index 000000000..c84da6092 Binary files /dev/null and b/website/public/assets/fonts/StudioFeixenSans-Light.otf differ diff --git a/website/public/assets/fonts/StudioFeixenSans-Medium.otf b/website/public/assets/fonts/StudioFeixenSans-Medium.otf new file mode 100644 index 000000000..5a7ca7912 Binary files /dev/null and b/website/public/assets/fonts/StudioFeixenSans-Medium.otf differ diff --git a/website/public/assets/fonts/StudioFeixenSans-Regular.otf b/website/public/assets/fonts/StudioFeixenSans-Regular.otf new file mode 100644 index 000000000..7b864f7dd Binary files /dev/null and b/website/public/assets/fonts/StudioFeixenSans-Regular.otf differ diff --git a/website/public/assets/fonts/StudioFeixenSans-Semibold.otf b/website/public/assets/fonts/StudioFeixenSans-Semibold.otf new file mode 100644 index 000000000..7eca0c0fc Binary files /dev/null and b/website/public/assets/fonts/StudioFeixenSans-Semibold.otf differ diff --git a/website/public/assets/fonts/StudioFeixenSans-Ultralight.otf b/website/public/assets/fonts/StudioFeixenSans-Ultralight.otf new file mode 100644 index 000000000..ffb5495d3 Binary files /dev/null and b/website/public/assets/fonts/StudioFeixenSans-Ultralight.otf differ diff --git a/website/public/favicon.ico b/website/public/favicon.ico new file mode 100644 index 000000000..3f7947fea Binary files /dev/null and b/website/public/favicon.ico differ diff --git a/website/public/favicon.svg b/website/public/favicon.svg deleted file mode 100644 index cba5ac140..000000000 --- a/website/public/favicon.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/website/public/gifs/extension.gif b/website/public/gifs/extension.gif new file mode 100644 index 000000000..26464e32f Binary files /dev/null and b/website/public/gifs/extension.gif differ diff --git a/website/public/jan.png b/website/public/jan.png deleted file mode 100644 index 21ec5b15f..000000000 Binary files a/website/public/jan.png and /dev/null differ diff --git a/website/public/jan2.png b/website/public/jan2.png deleted file mode 100644 index ef2abe4d4..000000000 Binary files a/website/public/jan2.png and /dev/null differ diff --git a/website/public/openapi/cloud-openapi.json b/website/public/openapi/cloud-openapi.json new file mode 100644 index 000000000..4d5b2c6b8 --- /dev/null +++ b/website/public/openapi/cloud-openapi.json @@ -0,0 +1,3978 @@ +{ + "schemes": [], + "swagger": "2.0", + "info": { + "description": "OpenAI-compatible API for Jan Server powered by vLLM. High-performance, scalable inference service with automatic batching and optimized memory management.", + "title": "👋Jan Server API", + "contact": { + "name": "Jan Server Support", + "url": "https://jan.ai/support", + "email": "support@jan.ai" + }, + "version": "1.0", + "x-logo": { + "url": "https://jan.ai/logo.png", + "altText": "👋Jan Server API" + }, + "license": { + "name": "Apache 2.0", + "url": "https://github.com/menloresearch/jan/blob/main/LICENSE" + } + }, + "host": "", + "basePath": "/", + "paths": { + "/jan/v1/auth/google/callback": { + "post": { + "description": "Handles the callback from the Google OAuth2 provider to exchange the authorization code for a token, verify the user, and issue access and refresh tokens.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Authentication" + ], + "summary": "Google OAuth2 Callback", + "parameters": [ + { + "description": "Request body containing the authorization code and state", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_auth_google.GoogleCallbackRequest" + } + } + ], + "responses": { + "200": { + "description": "Successfully authenticated and returned tokens", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_auth_google_GoogleCallbackResponse" + } + }, + "400": { + "description": "Bad request (e.g., invalid state, missing code, or invalid claims)", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized (e.g., a user claim is not found or is invalid in the context)", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/jan/v1/auth/google/login": { + "get": { + "description": "Redirects the user to the Google OAuth2 authorization page to initiate the login process.", + "tags": [ + "Jan", + "Jan-Authentication" + ], + "summary": "Google OAuth2 Login", + "responses": { + "307": { + "description": "Redirects to Google's login page" + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/jan/v1/auth/guest-login": { + "post": { + "description": "JWT-base Guest Login.", + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Authentication" + ], + "summary": "Guest Login", + "responses": { + "200": { + "description": "Successfully refreshed the access token", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_auth_RefreshTokenResponse" + } + }, + "400": { + "description": "Bad Request (e.g., invalid refresh token)", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized (e.g., expired or missing refresh token)", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/jan/v1/auth/me": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves the profile of the authenticated user based on the provided JWT.", + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Authentication" + ], + "summary": "Get user profile", + "responses": { + "200": { + "description": "Successfully retrieved user profile", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_auth_GetMeResponse" + } + }, + "401": { + "description": "Unauthorized (e.g., missing or invalid JWT)", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/jan/v1/auth/refresh-token": { + "get": { + "description": "Use a valid refresh token to obtain a new access token. The refresh token is typically sent in a cookie.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Authentication" + ], + "summary": "Refresh an access token", + "responses": { + "200": { + "description": "Successfully refreshed the access token", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_auth_RefreshTokenResponse" + } + }, + "400": { + "description": "Bad Request (e.g., invalid refresh token)", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized (e.g., expired or missing refresh token)", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/jan/v1/chat/completions": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Generates a model response for the given chat conversation.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Chat" + ], + "summary": "Create a chat completion", + "parameters": [ + { + "description": "Chat completion request payload", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/openai.ChatCompletionRequest" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_chat.ChatCompletionResponseSwagger" + } + }, + "400": { + "description": "Invalid request payload", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/jan/v1/conversations": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a new conversation for the authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Conversations" + ], + "summary": "Create a conversation", + "parameters": [ + { + "description": "Create conversation request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.CreateConversationRequest" + } + } + ], + "responses": { + "200": { + "description": "Created conversation", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationResponse" + } + }, + "400": { + "description": "Invalid request", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/jan/v1/conversations/{conversation_id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a conversation by its ID", + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Conversations" + ], + "summary": "Get a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Conversation details", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a conversation and all its items", + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Conversations" + ], + "summary": "Delete a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Deleted conversation", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.DeletedConversationResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "patch": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Updates conversation metadata", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Conversations" + ], + "summary": "Update a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + }, + { + "description": "Update conversation request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.UpdateConversationRequest" + } + } + ], + "responses": { + "200": { + "description": "Updated conversation", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationResponse" + } + }, + "400": { + "description": "Invalid request", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/jan/v1/conversations/{conversation_id}/items": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Lists all items in a conversation", + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Conversations" + ], + "summary": "List items in a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Number of items to return (1-100)", + "name": "limit", + "in": "query" + }, + { + "type": "string", + "description": "Cursor for pagination", + "name": "cursor", + "in": "query" + }, + { + "type": "string", + "description": "Order of items (asc/desc)", + "name": "order", + "in": "query" + } + ], + "responses": { + "200": { + "description": "List of items", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemListResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Adds multiple items to a conversation", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Conversations" + ], + "summary": "Create items in a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + }, + { + "description": "Create items request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.CreateItemsRequest" + } + } + ], + "responses": { + "200": { + "description": "Created items", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemListResponse" + } + }, + "400": { + "description": "Invalid request", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/jan/v1/conversations/{conversation_id}/items/{item_id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a specific item from a conversation", + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Conversations" + ], + "summary": "Get an item from a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Item ID", + "name": "item_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Item details", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a specific item from a conversation", + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Conversations" + ], + "summary": "Delete an item from a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Item ID", + "name": "item_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Updated conversation", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/jan/v1/organizations": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a list of organizations owned by the authenticated user.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Organizations" + ], + "summary": "List organizations", + "parameters": [ + { + "type": "integer", + "default": 10, + "description": "Number of organizations to return", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "default": 0, + "description": "Offset for pagination", + "name": "offset", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Successfully retrieved organizations.", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ListResponse-app_interfaces_http_routes_jan_v1_organization_OrganizationResponse" + } + }, + "400": { + "description": "Bad request, e.g., invalid pagination parameters.", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized, e.g., invalid or missing token.", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error.", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/jan/v1/organizations/{org_public_id}/api_keys": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a list of all API keys associated with an organization.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Organizations" + ], + "summary": "List API keys for a specific organization", + "parameters": [ + { + "type": "string", + "description": "Organization Public ID", + "name": "org_public_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "default": 0, + "description": "offset for pagination", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "default": 10, + "description": "Number of items per page", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "List of API keys retrieved successfully", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ListResponse-app_interfaces_http_routes_jan_v1_organization_api_keys_ApiKeyResponse" + } + }, + "400": { + "description": "Bad request, e.g., invalid pagination parameters", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized, e.g., invalid or missing token", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Not Found, e.g., organization not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a new API key with administrative permissions for a specific organization.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Organizations" + ], + "summary": "Create a new organization-level admin key", + "parameters": [ + { + "type": "string", + "description": "Organization Public ID", + "name": "org_public_id", + "in": "path", + "required": true + }, + { + "description": "Request body for creating an admin key", + "name": "requestBody", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_organization_api_keys.CreateAdminKeyRequest" + } + } + ], + "responses": { + "200": { + "description": "Admin API key created successfully", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_organization_api_keys_ApiKeyResponse" + } + }, + "400": { + "description": "Bad request, e.g., invalid payload or missing IDs", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized, e.g., invalid or missing token", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Not Found, e.g., organization not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/jan/v1/organizations/{org_public_id}/projects": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "List all projects within a given organization.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Organizations" + ], + "summary": "List projects", + "parameters": [ + { + "type": "string", + "description": "Organization Public ID", + "name": "org_public_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "default": 10, + "description": "Number of projects to return", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "default": 0, + "description": "Offset for pagination", + "name": "offset", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Successfully retrieved projects", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ListResponse-app_interfaces_http_routes_jan_v1_organization_projects_ProjectResponse" + } + }, + "400": { + "description": "Bad request, e.g., invalid pagination parameters or organization ID", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized, e.g., invalid or missing token", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Not Found, e.g., organization not found or no projects found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/jan/v1/organizations/{org_public_id}/projects/{project_public_id}/api_keys": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "List API keys for a specific project.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Organizations" + ], + "summary": "List new project API key", + "parameters": [ + { + "type": "string", + "description": "Organization Public ID", + "name": "org_public_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Project Public ID", + "name": "project_public_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "API key created successfully", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_organization_projects_api_keys_ApiKeyResponse" + } + }, + "400": { + "description": "Bad request, e.g., invalid payload or missing IDs", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized, e.g., invalid or missing token", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Not Found, e.g., project or organization not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a new API key for a specific project.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Jan", + "Jan-Organizations" + ], + "summary": "Create a new project API key", + "parameters": [ + { + "type": "string", + "description": "Organization Public ID", + "name": "org_public_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Project Public ID", + "name": "project_public_id", + "in": "path", + "required": true + }, + { + "description": "Request body for creating an API key", + "name": "requestBody", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_organization_projects_api_keys.CreateApiKeyRequest" + } + } + ], + "responses": { + "200": { + "description": "API key created successfully", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_organization_projects_api_keys_ApiKeyResponse" + } + }, + "400": { + "description": "Bad request, e.g., invalid payload or missing IDs", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized, e.g., invalid or missing token", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Not Found, e.g., project or organization not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/chat/completions": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Generates a model response for the given chat conversation.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Chat" + ], + "summary": "Create a chat completion", + "parameters": [ + { + "description": "Chat completion request payload", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/openai.ChatCompletionRequest" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_chat.ChatCompletionResponseSwagger" + } + }, + "400": { + "description": "Invalid request payload", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/conversations": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a new conversation for the authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Conversations" + ], + "summary": "Create a conversation", + "parameters": [ + { + "description": "Create conversation request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.CreateConversationRequest" + } + } + ], + "responses": { + "200": { + "description": "Created conversation", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationResponse" + } + }, + "400": { + "description": "Invalid request", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/conversations/{conversation_id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a conversation by its ID", + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Conversations" + ], + "summary": "Get a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Conversation details", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a conversation and all its items", + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Conversations" + ], + "summary": "Delete a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Deleted conversation", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.DeletedConversationResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "patch": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Updates conversation metadata", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Conversations" + ], + "summary": "Update a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + }, + { + "description": "Update conversation request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.UpdateConversationRequest" + } + } + ], + "responses": { + "200": { + "description": "Updated conversation", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationResponse" + } + }, + "400": { + "description": "Invalid request", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/conversations/{conversation_id}/items": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Lists all items in a conversation", + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Conversations" + ], + "summary": "List items in a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Number of items to return (1-100)", + "name": "limit", + "in": "query" + }, + { + "type": "string", + "description": "Cursor for pagination", + "name": "cursor", + "in": "query" + }, + { + "type": "string", + "description": "Order of items (asc/desc)", + "name": "order", + "in": "query" + } + ], + "responses": { + "200": { + "description": "List of items", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemListResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Adds multiple items to a conversation", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Conversations" + ], + "summary": "Create items in a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + }, + { + "description": "Create items request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.CreateItemsRequest" + } + } + ], + "responses": { + "200": { + "description": "Created items", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemListResponse" + } + }, + "400": { + "description": "Invalid request", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/conversations/{conversation_id}/items/{item_id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a specific item from a conversation", + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Conversations" + ], + "summary": "Get an item from a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Item ID", + "name": "item_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Item details", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a specific item from a conversation", + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Conversations" + ], + "summary": "Delete an item from a conversation", + "parameters": [ + { + "type": "string", + "description": "Conversation ID", + "name": "conversation_id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Item ID", + "name": "item_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Updated conversation", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "403": { + "description": "Access denied", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Conversation not found", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal server error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/mcp": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Handles Model Context Protocol (MCP) requests over an HTTP stream. The response is sent as a continuous stream of data.", + "consumes": [ + "application/json" + ], + "produces": [ + "text/event-stream" + ], + "tags": [ + "MCP" + ], + "summary": "MCP streamable endpoint", + "parameters": [ + { + "description": "MCP request payload", + "name": "request", + "in": "body", + "required": true, + "schema": {} + } + ], + "responses": { + "200": { + "description": "Streamed response (SSE or chunked transfer)", + "schema": { + "type": "string" + } + } + } + } + }, + "/v1/models": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a list of available models that can be used for chat completions or other tasks.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Models" + ], + "summary": "List available models", + "responses": { + "200": { + "description": "Successful response", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1.ModelsResponse" + } + } + } + } + }, + "/v1/organization/admin_api_keys": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a paginated list of all admin API keys for the authenticated organization.", + "tags": [ + "Platform", + "Platform-Organizations" + ], + "summary": "List Admin API Keys", + "parameters": [ + { + "type": "string", + "default": "\"Bearer \"", + "description": "Bearer token", + "name": "Authorization", + "in": "header", + "required": true + }, + { + "type": "integer", + "default": 20, + "description": "The maximum number of items to return", + "name": "limit", + "in": "query" + }, + { + "type": "string", + "description": "A cursor for use in pagination. The ID of the last object from the previous page", + "name": "after", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Successfully retrieved the list of admin API keys", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization.AdminApiKeyListResponse" + } + }, + "401": { + "description": "Unauthorized - invalid or missing API key", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a new admin API key for an organization. Requires a valid admin API key in the Authorization header.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Organizations" + ], + "summary": "Create Admin API Key", + "parameters": [ + { + "type": "string", + "default": "\"Bearer \"", + "description": "Bearer token", + "name": "Authorization", + "in": "header", + "required": true + }, + { + "description": "API key creation request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization.CreateOrganizationAdminAPIKeyRequest" + } + } + ], + "responses": { + "200": { + "description": "Successfully created admin API key", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization.OrganizationAdminAPIKeyResponse" + } + }, + "400": { + "description": "Bad request - invalid payload", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized - invalid or missing API key", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/organization/admin_api_keys/{id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a specific admin API key by its ID.", + "tags": [ + "Platform", + "Platform-Organizations" + ], + "summary": "Get Admin API Key", + "parameters": [ + { + "type": "string", + "default": "\"Bearer \"", + "description": "Bearer token", + "name": "Authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "description": "ID of the admin API key", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Successfully retrieved the admin API key", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization.OrganizationAdminAPIKeyResponse" + } + }, + "401": { + "description": "Unauthorized - invalid or missing API key", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Not Found - API key with the given ID does not exist or does not belong to the organization", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes an admin API key by its ID.", + "tags": [ + "Platform", + "Platform-Organizations" + ], + "summary": "Delete Admin API Key", + "parameters": [ + { + "type": "string", + "default": "\"Bearer \"", + "description": "Bearer token", + "name": "Authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "description": "ID of the admin API key to delete", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Successfully deleted the admin API key", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization.AdminAPIKeyDeletedResponse" + } + }, + "401": { + "description": "Unauthorized - invalid or missing API key", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Not Found - API key with the given ID does not exist or does not belong to the organization", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/organization/projects": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a paginated list of all projects for the authenticated organization.", + "tags": [ + "Platform", + "Platform-Organizations" + ], + "summary": "List Projects", + "parameters": [ + { + "type": "string", + "default": "\"Bearer \"", + "description": "Bearer token", + "name": "Authorization", + "in": "header", + "required": true + }, + { + "type": "integer", + "default": 20, + "description": "The maximum number of items to return", + "name": "limit", + "in": "query" + }, + { + "type": "string", + "description": "A cursor for use in pagination. The ID of the last object from the previous page", + "name": "after", + "in": "query" + }, + { + "type": "string", + "description": "Whether to include archived projects.", + "name": "include_archived", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Successfully retrieved the list of projects", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization_projects.ProjectListResponse" + } + }, + "401": { + "description": "Unauthorized - invalid or missing API key", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a new project for an organization.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Organizations" + ], + "summary": "Create Project", + "parameters": [ + { + "type": "string", + "default": "\"Bearer \"", + "description": "Bearer token", + "name": "Authorization", + "in": "header", + "required": true + }, + { + "description": "Project creation request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization_projects.CreateProjectRequest" + } + } + ], + "responses": { + "200": { + "description": "Successfully created project", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization_projects.ProjectResponse" + } + }, + "400": { + "description": "Bad request - invalid payload", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized - invalid or missing API key", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/organization/projects/{project_id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Retrieves a specific project by its ID.", + "tags": [ + "Platform", + "Platform-Organizations" + ], + "summary": "Get Project", + "parameters": [ + { + "type": "string", + "default": "\"Bearer \"", + "description": "Bearer token", + "name": "Authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "description": "ID of the project", + "name": "project_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Successfully retrieved the project", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization_projects.ProjectResponse" + } + }, + "401": { + "description": "Unauthorized - invalid or missing API key", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Not Found - project with the given ID does not exist or does not belong to the organization", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Updates a specific project by its ID.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Platform", + "Platform-Organizations" + ], + "summary": "Update Project", + "parameters": [ + { + "type": "string", + "default": "\"Bearer \"", + "description": "Bearer token", + "name": "Authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "description": "ID of the project to update", + "name": "project_id", + "in": "path", + "required": true + }, + { + "description": "Project update request", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization_projects.UpdateProjectRequest" + } + } + ], + "responses": { + "200": { + "description": "Successfully updated the project", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization_projects.ProjectResponse" + } + }, + "400": { + "description": "Bad request - invalid payload", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "401": { + "description": "Unauthorized - invalid or missing API key", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Not Found - project with the given ID does not exist", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/organization/projects/{project_id}/archive": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Archives a specific project by its ID, making it inactive.", + "tags": [ + "Platform", + "Platform-Organizations" + ], + "summary": "Archive Project", + "parameters": [ + { + "type": "string", + "default": "\"Bearer \"", + "description": "Bearer token", + "name": "Authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "description": "ID of the project to archive", + "name": "project_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Successfully archived the project", + "schema": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization_projects.ProjectResponse" + } + }, + "401": { + "description": "Unauthorized - invalid or missing API key", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + }, + "404": { + "description": "Not Found - project with the given ID does not exist", + "schema": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse" + } + } + } + } + }, + "/v1/version": { + "get": { + "description": "Returns the current build version of the API server.", + "produces": [ + "application/json" + ], + "tags": [ + "Jan Server" + ], + "summary": "Get API build version", + "responses": { + "200": { + "description": "version info", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + } + }, + "definitions": { + "app_interfaces_http_routes_jan_v1_auth.GetMeResponse": { + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_jan_v1_auth.RefreshTokenResponse": { + "type": "object", + "properties": { + "access_token": { + "type": "string" + }, + "expires_in": { + "type": "integer" + } + } + }, + "app_interfaces_http_routes_jan_v1_auth_google.GoogleCallbackRequest": { + "type": "object", + "required": [ + "code" + ], + "properties": { + "code": { + "type": "string" + }, + "state": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_jan_v1_auth_google.GoogleCallbackResponse": { + "type": "object", + "properties": { + "access_token": { + "type": "string" + }, + "expires_in": { + "type": "integer" + } + } + }, + "app_interfaces_http_routes_jan_v1_chat.ChatCompletionResponseSwagger": { + "type": "object", + "properties": { + "choices": { + "type": "array", + "items": { + "$ref": "#/definitions/openai.ChatCompletionChoice" + } + }, + "created": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "model": { + "type": "string" + }, + "object": { + "type": "string" + }, + "usage": { + "$ref": "#/definitions/openai.Usage" + } + } + }, + "app_interfaces_http_routes_jan_v1_organization.OrganizationResponse": { + "type": "object", + "properties": { + "createdAt": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "publicID": { + "type": "string" + }, + "updatedAt": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_jan_v1_organization_api_keys.ApiKeyResponse": { + "type": "object", + "properties": { + "apikeyType": { + "type": "string" + }, + "description": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "expiresAt": { + "type": "string" + }, + "id": { + "type": "string" + }, + "key": { + "type": "string" + }, + "last_usedAt": { + "type": "string" + }, + "permissions": { + "type": "string" + }, + "plaintextHint": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_jan_v1_organization_api_keys.CreateAdminKeyRequest": { + "type": "object", + "properties": { + "description": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_jan_v1_organization_projects.ProjectResponse": { + "type": "object", + "properties": { + "archivedAt": { + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "name": { + "type": "string" + }, + "organizationID": { + "type": "integer" + }, + "publicID": { + "type": "string" + }, + "status": { + "type": "string" + }, + "updatedAt": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_jan_v1_organization_projects_api_keys.ApiKeyResponse": { + "type": "object", + "properties": { + "apikeyType": { + "type": "string" + }, + "description": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "expiresAt": { + "type": "string" + }, + "id": { + "type": "string" + }, + "key": { + "type": "string" + }, + "last_usedAt": { + "type": "string" + }, + "permissions": { + "type": "string" + }, + "plaintextHint": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_jan_v1_organization_projects_api_keys.CreateApiKeyRequest": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "expiresAt": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_v1.Model": { + "type": "object", + "properties": { + "created": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "object": { + "type": "string" + }, + "owned_by": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_v1.ModelsResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/app_interfaces_http_routes_v1.Model" + } + }, + "object": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_v1_chat.ChatCompletionResponseSwagger": { + "type": "object", + "properties": { + "choices": { + "type": "array", + "items": { + "$ref": "#/definitions/openai.ChatCompletionChoice" + } + }, + "created": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "model": { + "type": "string" + }, + "object": { + "type": "string" + }, + "usage": { + "$ref": "#/definitions/openai.Usage" + } + } + }, + "app_interfaces_http_routes_v1_organization.AdminAPIKeyDeletedResponse": { + "type": "object", + "properties": { + "deleted": { + "type": "boolean" + }, + "id": { + "type": "string" + }, + "object": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_v1_organization.AdminApiKeyListResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization.OrganizationAdminAPIKeyResponse" + } + }, + "first_id": { + "type": "string" + }, + "has_more": { + "type": "boolean" + }, + "last_id": { + "type": "string" + }, + "object": { + "type": "string", + "example": "list" + } + } + }, + "app_interfaces_http_routes_v1_organization.CreateOrganizationAdminAPIKeyRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "example": "My Admin API Key" + } + } + }, + "app_interfaces_http_routes_v1_organization.OrganizationAdminAPIKeyResponse": { + "type": "object", + "properties": { + "created_at": { + "type": "integer", + "example": 1698765432 + }, + "id": { + "type": "string", + "example": "key_1234567890" + }, + "last_used_at": { + "type": "integer", + "example": 1698765432 + }, + "name": { + "type": "string", + "example": "My Admin API Key" + }, + "object": { + "type": "string", + "example": "api_key" + }, + "owner": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization.Owner" + }, + "redacted_value": { + "type": "string", + "example": "sk-...abcd" + }, + "value": { + "type": "string", + "example": "sk-abcdef1234567890" + } + } + }, + "app_interfaces_http_routes_v1_organization.Owner": { + "type": "object", + "properties": { + "created_at": { + "type": "integer", + "example": 1698765432 + }, + "id": { + "type": "string", + "example": "user_1234567890" + }, + "name": { + "type": "string", + "example": "John Doe" + }, + "object": { + "type": "string", + "example": "user" + }, + "role": { + "type": "string", + "example": "admin" + }, + "type": { + "type": "string", + "example": "user" + } + } + }, + "app_interfaces_http_routes_v1_organization_projects.CreateProjectRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "example": "New AI Project" + } + } + }, + "app_interfaces_http_routes_v1_organization_projects.ProjectListResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/app_interfaces_http_routes_v1_organization_projects.ProjectResponse" + } + }, + "first_id": { + "type": "string" + }, + "has_more": { + "type": "boolean" + }, + "last_id": { + "type": "string" + }, + "object": { + "type": "string", + "example": "list" + } + } + }, + "app_interfaces_http_routes_v1_organization_projects.ProjectResponse": { + "type": "object", + "properties": { + "archived_at": { + "type": "integer", + "example": 1698765432 + }, + "created_at": { + "type": "integer", + "example": 1698765432 + }, + "id": { + "type": "string", + "example": "proj_1234567890" + }, + "name": { + "type": "string", + "example": "My First Project" + }, + "object": { + "type": "string", + "example": "project" + }, + "status": { + "type": "string" + } + } + }, + "app_interfaces_http_routes_v1_organization_projects.UpdateProjectRequest": { + "type": "object", + "properties": { + "name": { + "type": "string", + "example": "Updated AI Project" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.AnnotationResponse": { + "type": "object", + "properties": { + "end_index": { + "type": "integer" + }, + "file_id": { + "type": "string" + }, + "index": { + "type": "integer" + }, + "start_index": { + "type": "integer" + }, + "text": { + "type": "string" + }, + "type": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ContentResponse": { + "type": "object", + "properties": { + "file": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.FileContentResponse" + }, + "image": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ImageContentResponse" + }, + "input_text": { + "type": "string" + }, + "output_text": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.OutputTextResponse" + }, + "text": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.TextResponse" + }, + "type": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationContentRequest": { + "type": "object", + "required": [ + "type" + ], + "properties": { + "text": { + "type": "string" + }, + "type": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemListResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemResponse" + } + }, + "first_id": { + "type": "string" + }, + "has_more": { + "type": "boolean" + }, + "last_id": { + "type": "string" + }, + "object": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemRequest": { + "type": "object", + "required": [ + "content", + "type" + ], + "properties": { + "content": { + "type": "array", + "items": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationContentRequest" + } + }, + "role": { + "type": "string" + }, + "type": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemResponse": { + "type": "object", + "properties": { + "content": { + "type": "array", + "items": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ContentResponse" + } + }, + "created_at": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "object": { + "type": "string" + }, + "role": { + "type": "string" + }, + "status": { + "type": "string" + }, + "type": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationResponse": { + "type": "object", + "properties": { + "created_at": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "metadata": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "object": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.CreateConversationRequest": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemRequest" + } + }, + "metadata": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.CreateItemsRequest": { + "type": "object", + "required": [ + "items" + ], + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ConversationItemRequest" + } + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.DeletedConversationResponse": { + "type": "object", + "properties": { + "deleted": { + "type": "boolean" + }, + "id": { + "type": "string" + }, + "object": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.FileContentResponse": { + "type": "object", + "properties": { + "file_id": { + "type": "string" + }, + "mime_type": { + "type": "string" + }, + "name": { + "type": "string" + }, + "size": { + "type": "integer" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.ImageContentResponse": { + "type": "object", + "properties": { + "detail": { + "type": "string" + }, + "file_id": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.OutputTextResponse": { + "type": "object", + "properties": { + "annotations": { + "type": "array", + "items": { + "$ref": "#/definitions/menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.AnnotationResponse" + } + }, + "text": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.TextResponse": { + "type": "object", + "properties": { + "value": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_handlers_conversation.UpdateConversationRequest": { + "type": "object", + "required": [ + "metadata" + ], + "properties": { + "metadata": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_responses.ErrorResponse": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "error": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_auth_GetMeResponse": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_auth.GetMeResponse" + }, + "status": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_auth_RefreshTokenResponse": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_auth.RefreshTokenResponse" + }, + "status": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_auth_google_GoogleCallbackResponse": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_auth_google.GoogleCallbackResponse" + }, + "status": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_organization_api_keys_ApiKeyResponse": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_organization_api_keys.ApiKeyResponse" + }, + "status": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_responses.GeneralResponse-app_interfaces_http_routes_jan_v1_organization_projects_api_keys_ApiKeyResponse": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_organization_projects_api_keys.ApiKeyResponse" + }, + "status": { + "type": "string" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_responses.ListResponse-app_interfaces_http_routes_jan_v1_organization_OrganizationResponse": { + "type": "object", + "properties": { + "results": { + "type": "array", + "items": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_organization.OrganizationResponse" + } + }, + "status": { + "type": "string" + }, + "total": { + "type": "integer" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_responses.ListResponse-app_interfaces_http_routes_jan_v1_organization_api_keys_ApiKeyResponse": { + "type": "object", + "properties": { + "results": { + "type": "array", + "items": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_organization_api_keys.ApiKeyResponse" + } + }, + "status": { + "type": "string" + }, + "total": { + "type": "integer" + } + } + }, + "menlo_ai_jan-api-gateway_app_interfaces_http_responses.ListResponse-app_interfaces_http_routes_jan_v1_organization_projects_ProjectResponse": { + "type": "object", + "properties": { + "results": { + "type": "array", + "items": { + "$ref": "#/definitions/app_interfaces_http_routes_jan_v1_organization_projects.ProjectResponse" + } + }, + "status": { + "type": "string" + }, + "total": { + "type": "integer" + } + } + }, + "openai.ChatCompletionChoice": { + "type": "object", + "properties": { + "content_filter_results": { + "$ref": "#/definitions/openai.ContentFilterResults" + }, + "finish_reason": { + "description": "FinishReason\nstop: API returned complete message,\nor a message terminated by one of the stop sequences provided via the stop parameter\nlength: Incomplete model output due to max_tokens parameter or token limit\nfunction_call: The model decided to call a function\ncontent_filter: Omitted content due to a flag from our content filters\nnull: API response still in progress or incomplete", + "allOf": [ + { + "$ref": "#/definitions/openai.FinishReason" + } + ] + }, + "index": { + "type": "integer" + }, + "logprobs": { + "$ref": "#/definitions/openai.LogProbs" + }, + "message": { + "$ref": "#/definitions/openai.ChatCompletionMessage" + } + } + }, + "openai.ChatCompletionMessage": { + "type": "object", + "properties": { + "content": { + "type": "string" + }, + "function_call": { + "$ref": "#/definitions/openai.FunctionCall" + }, + "multiContent": { + "type": "array", + "items": { + "$ref": "#/definitions/openai.ChatMessagePart" + } + }, + "name": { + "description": "This property isn't in the official documentation, but it's in\nthe documentation for the official library for python:\n- https://github.com/openai/openai-python/blob/main/chatml.md\n- https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb", + "type": "string" + }, + "reasoning_content": { + "description": "This property is used for the \"reasoning\" feature supported by deepseek-reasoner\nwhich is not in the official documentation.\nthe doc from deepseek:\n- https://api-docs.deepseek.com/api/create-chat-completion#responses", + "type": "string" + }, + "refusal": { + "type": "string" + }, + "role": { + "type": "string" + }, + "tool_call_id": { + "description": "For Role=tool prompts this should be set to the ID given in the assistant's prior request to call a tool.", + "type": "string" + }, + "tool_calls": { + "description": "For Role=assistant prompts this may be set to the tool calls generated by the model, such as function calls.", + "type": "array", + "items": { + "$ref": "#/definitions/openai.ToolCall" + } + } + } + }, + "openai.ChatCompletionRequest": { + "type": "object", + "properties": { + "chat_template_kwargs": { + "description": "ChatTemplateKwargs provides a way to add non-standard parameters to the request body.\nAdditional kwargs to pass to the template renderer. Will be accessible by the chat template.\nSuch as think mode for qwen3. \"chat_template_kwargs\": {\"enable_thinking\": false}\nhttps://qwen.readthedocs.io/en/latest/deployment/vllm.html#thinking-non-thinking-modes", + "type": "object", + "additionalProperties": {} + }, + "frequency_penalty": { + "type": "number" + }, + "function_call": { + "description": "Deprecated: use ToolChoice instead." + }, + "functions": { + "description": "Deprecated: use Tools instead.", + "type": "array", + "items": { + "$ref": "#/definitions/openai.FunctionDefinition" + } + }, + "guided_choice": { + "description": "GuidedChoice is a vLLM-specific extension that restricts the model's output\nto one of the predefined string choices provided in this field. This feature\nis used to constrain the model's responses to a controlled set of options,\nensuring predictable and consistent outputs in scenarios where specific\nchoices are required.", + "type": "array", + "items": { + "type": "string" + } + }, + "logit_bias": { + "description": "LogitBias is must be a token id string (specified by their token ID in the tokenizer), not a word string.\nincorrect: `\"logit_bias\":{\"You\": 6}`, correct: `\"logit_bias\":{\"1639\": 6}`\nrefs: https://platform.openai.com/docs/api-reference/chat/create#chat/create-logit_bias", + "type": "object", + "additionalProperties": { + "type": "integer" + } + }, + "logprobs": { + "description": "LogProbs indicates whether to return log probabilities of the output tokens or not.\nIf true, returns the log probabilities of each output token returned in the content of message.\nThis option is currently not available on the gpt-4-vision-preview model.", + "type": "boolean" + }, + "max_completion_tokens": { + "description": "MaxCompletionTokens An upper bound for the number of tokens that can be generated for a completion,\nincluding visible output tokens and reasoning tokens https://platform.openai.com/docs/guides/reasoning", + "type": "integer" + }, + "max_tokens": { + "description": "MaxTokens The maximum number of tokens that can be generated in the chat completion.\nThis value can be used to control costs for text generated via API.\nDeprecated: use MaxCompletionTokens. Not compatible with o1-series models.\nrefs: https://platform.openai.com/docs/api-reference/chat/create#chat-create-max_tokens", + "type": "integer" + }, + "messages": { + "type": "array", + "items": { + "$ref": "#/definitions/openai.ChatCompletionMessage" + } + }, + "metadata": { + "description": "Metadata to store with the completion.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "model": { + "type": "string" + }, + "n": { + "type": "integer" + }, + "parallel_tool_calls": { + "description": "Disable the default behavior of parallel tool calls by setting it: false." + }, + "prediction": { + "description": "Configuration for a predicted output.", + "allOf": [ + { + "$ref": "#/definitions/openai.Prediction" + } + ] + }, + "presence_penalty": { + "type": "number" + }, + "reasoning_effort": { + "description": "Controls effort on reasoning for reasoning models. It can be set to \"low\", \"medium\", or \"high\".", + "type": "string" + }, + "response_format": { + "$ref": "#/definitions/openai.ChatCompletionResponseFormat" + }, + "safety_identifier": { + "description": "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user.\nWe recommend hashing their username or email address, in order to avoid sending us any identifying information.\nhttps://platform.openai.com/docs/api-reference/chat/create#chat_create-safety_identifier", + "type": "string" + }, + "seed": { + "type": "integer" + }, + "service_tier": { + "description": "Specifies the latency tier to use for processing the request.", + "allOf": [ + { + "$ref": "#/definitions/openai.ServiceTier" + } + ] + }, + "stop": { + "type": "array", + "items": { + "type": "string" + } + }, + "store": { + "description": "Store can be set to true to store the output of this completion request for use in distillations and evals.\nhttps://platform.openai.com/docs/api-reference/chat/create#chat-create-store", + "type": "boolean" + }, + "stream": { + "type": "boolean" + }, + "stream_options": { + "description": "Options for streaming response. Only set this when you set stream: true.", + "allOf": [ + { + "$ref": "#/definitions/openai.StreamOptions" + } + ] + }, + "temperature": { + "type": "number" + }, + "tool_choice": { + "description": "This can be either a string or an ToolChoice object." + }, + "tools": { + "type": "array", + "items": { + "$ref": "#/definitions/openai.Tool" + } + }, + "top_logprobs": { + "description": "TopLogProbs is an integer between 0 and 5 specifying the number of most likely tokens to return at each\ntoken position, each with an associated log probability.\nlogprobs must be set to true if this parameter is used.", + "type": "integer" + }, + "top_p": { + "type": "number" + }, + "user": { + "type": "string" + } + } + }, + "openai.ChatCompletionResponseFormat": { + "type": "object", + "properties": { + "json_schema": { + "$ref": "#/definitions/openai.ChatCompletionResponseFormatJSONSchema" + }, + "type": { + "$ref": "#/definitions/openai.ChatCompletionResponseFormatType" + } + } + }, + "openai.ChatCompletionResponseFormatJSONSchema": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "schema": {}, + "strict": { + "type": "boolean" + } + } + }, + "openai.ChatCompletionResponseFormatType": { + "type": "string", + "enum": [ + "json_object", + "json_schema", + "text" + ], + "x-enum-varnames": [ + "ChatCompletionResponseFormatTypeJSONObject", + "ChatCompletionResponseFormatTypeJSONSchema", + "ChatCompletionResponseFormatTypeText" + ] + }, + "openai.ChatMessageImageURL": { + "type": "object", + "properties": { + "detail": { + "$ref": "#/definitions/openai.ImageURLDetail" + }, + "url": { + "type": "string" + } + } + }, + "openai.ChatMessagePart": { + "type": "object", + "properties": { + "image_url": { + "$ref": "#/definitions/openai.ChatMessageImageURL" + }, + "text": { + "type": "string" + }, + "type": { + "$ref": "#/definitions/openai.ChatMessagePartType" + } + } + }, + "openai.ChatMessagePartType": { + "type": "string", + "enum": [ + "text", + "image_url" + ], + "x-enum-varnames": [ + "ChatMessagePartTypeText", + "ChatMessagePartTypeImageURL" + ] + }, + "openai.CompletionTokensDetails": { + "type": "object", + "properties": { + "accepted_prediction_tokens": { + "type": "integer" + }, + "audio_tokens": { + "type": "integer" + }, + "reasoning_tokens": { + "type": "integer" + }, + "rejected_prediction_tokens": { + "type": "integer" + } + } + }, + "openai.ContentFilterResults": { + "type": "object", + "properties": { + "hate": { + "$ref": "#/definitions/openai.Hate" + }, + "jailbreak": { + "$ref": "#/definitions/openai.JailBreak" + }, + "profanity": { + "$ref": "#/definitions/openai.Profanity" + }, + "self_harm": { + "$ref": "#/definitions/openai.SelfHarm" + }, + "sexual": { + "$ref": "#/definitions/openai.Sexual" + }, + "violence": { + "$ref": "#/definitions/openai.Violence" + } + } + }, + "openai.FinishReason": { + "type": "string", + "enum": [ + "stop", + "length", + "function_call", + "tool_calls", + "content_filter", + "null" + ], + "x-enum-varnames": [ + "FinishReasonStop", + "FinishReasonLength", + "FinishReasonFunctionCall", + "FinishReasonToolCalls", + "FinishReasonContentFilter", + "FinishReasonNull" + ] + }, + "openai.FunctionCall": { + "type": "object", + "properties": { + "arguments": { + "description": "call function with arguments in JSON format", + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "openai.FunctionDefinition": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "parameters": { + "description": "Parameters is an object describing the function.\nYou can pass json.RawMessage to describe the schema,\nor you can pass in a struct which serializes to the proper JSON schema.\nThe jsonschema package is provided for convenience, but you should\nconsider another specialized library if you require more complex schemas." + }, + "strict": { + "type": "boolean" + } + } + }, + "openai.Hate": { + "type": "object", + "properties": { + "filtered": { + "type": "boolean" + }, + "severity": { + "type": "string" + } + } + }, + "openai.ImageURLDetail": { + "type": "string", + "enum": [ + "high", + "low", + "auto" + ], + "x-enum-varnames": [ + "ImageURLDetailHigh", + "ImageURLDetailLow", + "ImageURLDetailAuto" + ] + }, + "openai.JailBreak": { + "type": "object", + "properties": { + "detected": { + "type": "boolean" + }, + "filtered": { + "type": "boolean" + } + } + }, + "openai.LogProb": { + "type": "object", + "properties": { + "bytes": { + "description": "Omitting the field if it is null", + "type": "array", + "items": { + "type": "integer" + } + }, + "logprob": { + "type": "number" + }, + "token": { + "type": "string" + }, + "top_logprobs": { + "description": "TopLogProbs is a list of the most likely tokens and their log probability, at this token position.\nIn rare cases, there may be fewer than the number of requested top_logprobs returned.", + "type": "array", + "items": { + "$ref": "#/definitions/openai.TopLogProbs" + } + } + } + }, + "openai.LogProbs": { + "type": "object", + "properties": { + "content": { + "description": "Content is a list of message content tokens with log probability information.", + "type": "array", + "items": { + "$ref": "#/definitions/openai.LogProb" + } + } + } + }, + "openai.Prediction": { + "type": "object", + "properties": { + "content": { + "type": "string" + }, + "type": { + "type": "string" + } + } + }, + "openai.Profanity": { + "type": "object", + "properties": { + "detected": { + "type": "boolean" + }, + "filtered": { + "type": "boolean" + } + } + }, + "openai.PromptTokensDetails": { + "type": "object", + "properties": { + "audio_tokens": { + "type": "integer" + }, + "cached_tokens": { + "type": "integer" + } + } + }, + "openai.SelfHarm": { + "type": "object", + "properties": { + "filtered": { + "type": "boolean" + }, + "severity": { + "type": "string" + } + } + }, + "openai.ServiceTier": { + "type": "string", + "enum": [ + "auto", + "default", + "flex", + "priority" + ], + "x-enum-varnames": [ + "ServiceTierAuto", + "ServiceTierDefault", + "ServiceTierFlex", + "ServiceTierPriority" + ] + }, + "openai.Sexual": { + "type": "object", + "properties": { + "filtered": { + "type": "boolean" + }, + "severity": { + "type": "string" + } + } + }, + "openai.StreamOptions": { + "type": "object", + "properties": { + "include_usage": { + "description": "If set, an additional chunk will be streamed before the data: [DONE] message.\nThe usage field on this chunk shows the token usage statistics for the entire request,\nand the choices field will always be an empty array.\nAll other chunks will also include a usage field, but with a null value.", + "type": "boolean" + } + } + }, + "openai.Tool": { + "type": "object", + "properties": { + "function": { + "$ref": "#/definitions/openai.FunctionDefinition" + }, + "type": { + "$ref": "#/definitions/openai.ToolType" + } + } + }, + "openai.ToolCall": { + "type": "object", + "properties": { + "function": { + "$ref": "#/definitions/openai.FunctionCall" + }, + "id": { + "type": "string" + }, + "index": { + "description": "Index is not nil only in chat completion chunk object", + "type": "integer" + }, + "type": { + "$ref": "#/definitions/openai.ToolType" + } + } + }, + "openai.ToolType": { + "type": "string", + "enum": [ + "function" + ], + "x-enum-varnames": [ + "ToolTypeFunction" + ] + }, + "openai.TopLogProbs": { + "type": "object", + "properties": { + "bytes": { + "type": "array", + "items": { + "type": "integer" + } + }, + "logprob": { + "type": "number" + }, + "token": { + "type": "string" + } + } + }, + "openai.Usage": { + "type": "object", + "properties": { + "completion_tokens": { + "type": "integer" + }, + "completion_tokens_details": { + "$ref": "#/definitions/openai.CompletionTokensDetails" + }, + "prompt_tokens": { + "type": "integer" + }, + "prompt_tokens_details": { + "$ref": "#/definitions/openai.PromptTokensDetails" + }, + "total_tokens": { + "type": "integer" + } + } + }, + "openai.Violence": { + "type": "object", + "properties": { + "filtered": { + "type": "boolean" + }, + "severity": { + "type": "string" + } + } + } + }, + "securityDefinitions": { + "BearerAuth": { + "description": "Type \"Bearer\" followed by a space and JWT token.", + "type": "apiKey", + "name": "Authorization", + "in": "header" + } + }, + "servers": [ + { + "url": "https://api.jan.ai/v1", + "description": "Jan Server API (Production)" + }, + { + "url": "https://staging-api.jan.ai/v1", + "description": "Jan Server API (Staging)" + }, + { + "url": "http://localhost:8000/v1", + "description": "Jan Server (Local Development)" + }, + { + "url": "http://jan-server.local:8000/v1", + "description": "Jan Server (Minikube)" + } + ], + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + { + "name": "Models", + "description": "List and describe available models" + }, + { + "name": "Chat", + "description": "Chat completion endpoints for conversational AI" + }, + { + "name": "Completions", + "description": "Text completion endpoints" + }, + { + "name": "Embeddings", + "description": "Generate embeddings for text" + }, + { + "name": "Usage", + "description": "Monitor API usage and quotas" + } + ], + "components": { + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT", + "description": "Enter your Jan Server API key. Configure authentication in your server settings." + } + } + }, + "x-jan-server-features": { + "vllm": { + "version": "0.5.0", + "features": [ + "PagedAttention for efficient memory management", + "Continuous batching for high throughput", + "Tensor parallelism for multi-GPU serving", + "Quantization support (AWQ, GPTQ, SqueezeLLM)", + "Speculative decoding", + "LoRA adapter support" + ] + }, + "scaling": { + "auto_scaling": true, + "min_replicas": 1, + "max_replicas": 100, + "target_qps": 100 + }, + "limits": { + "max_tokens_per_request": 32768, + "max_batch_size": 256, + "timeout_seconds": 300 + } + } +} \ No newline at end of file diff --git a/website/public/openapi/openapi-openai.json b/website/public/openapi/openapi-openai.json new file mode 100644 index 000000000..6eccbe6e7 --- /dev/null +++ b/website/public/openapi/openapi-openai.json @@ -0,0 +1,44747 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "OpenAI API", + "description": "The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details.", + "version": "2.3.0", + "termsOfService": "https://openai.com/policies/terms-of-use", + "contact": { + "name": "OpenAI Support", + "url": "https://help.openai.com/" + }, + "license": { + "name": "MIT", + "url": "https://github.com/openai/openai-openapi/blob/master/LICENSE" + } + }, + "servers": [ + { + "url": "https://api.openai.com/v1" + } + ], + "security": [ + { + "ApiKeyAuth": [] + } + ], + "tags": [ + { + "name": "Assistants", + "description": "Build Assistants that can call models and use tools." + }, + { + "name": "Audio", + "description": "Turn audio into text or text into audio." + }, + { + "name": "Chat", + "description": "Given a list of messages comprising a conversation, the model will return a response." + }, + { + "name": "Conversations", + "description": "Manage conversations and conversation items." + }, + { + "name": "Completions", + "description": "Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position." + }, + { + "name": "Embeddings", + "description": "Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms." + }, + { + "name": "Evals", + "description": "Manage and run evals in the OpenAI platform." + }, + { + "name": "Fine-tuning", + "description": "Manage fine-tuning jobs to tailor a model to your specific training data." + }, + { + "name": "Graders", + "description": "Manage and run graders in the OpenAI platform." + }, + { + "name": "Batch", + "description": "Create large batches of API requests to run asynchronously." + }, + { + "name": "Files", + "description": "Files are used to upload documents that can be used with features like Assistants and Fine-tuning." + }, + { + "name": "Uploads", + "description": "Use Uploads to upload large files in multiple parts." + }, + { + "name": "Images", + "description": "Given a prompt and/or an input image, the model will generate a new image." + }, + { + "name": "Models", + "description": "List and describe the various models available in the API." + }, + { + "name": "Moderations", + "description": "Given text and/or image inputs, classifies if those inputs are potentially harmful." + }, + { + "name": "Audit Logs", + "description": "List user actions and configuration changes within this organization." + } + ], + "paths": { + "/assistants": { + "get": { + "operationId": "listAssistants", + "tags": [ + "Assistants" + ], + "summary": "List assistants", + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "before", + "in": "query", + "description": "A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.\n", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListAssistantsResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List assistants", + "group": "assistants", + "beta": true, + "returns": "A list of [assistant](https://platform.openai.com/docs/api-reference/assistants/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"asst_abc123\",\n \"object\": \"assistant\",\n \"created_at\": 1698982736,\n \"name\": \"Coding Tutor\",\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You are a helpful assistant designed to make me better at coding!\",\n \"tools\": [],\n \"tool_resources\": {},\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n },\n {\n \"id\": \"asst_abc456\",\n \"object\": \"assistant\",\n \"created_at\": 1698982718,\n \"name\": \"My Assistant\",\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You are a helpful assistant designed to make me better at coding!\",\n \"tools\": [],\n \"tool_resources\": {},\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n },\n {\n \"id\": \"asst_abc789\",\n \"object\": \"assistant\",\n \"created_at\": 1698982643,\n \"name\": null,\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": null,\n \"tools\": [],\n \"tool_resources\": {},\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n }\n ],\n \"first_id\": \"asst_abc123\",\n \"last_id\": \"asst_abc789\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl \"https://api.openai.com/v1/assistants?order=desc&limit=20\" \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.beta.assistants.list()\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const assistant of client.beta.assistants.list()) {\n console.log(assistant.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Beta.Assistants.List(context.TODO(), openai.BetaAssistantListParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.assistants.AssistantListPage;\nimport com.openai.models.beta.assistants.AssistantListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n AssistantListPage page = client.beta().assistants().list();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.beta.assistants.list\n\nputs(page)" + } + } + }, + "description": "Returns a list of assistants." + }, + "post": { + "operationId": "createAssistant", + "tags": [ + "Assistants" + ], + "summary": "Create assistant", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateAssistantRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create assistant", + "group": "assistants", + "beta": true, + "returns": "An [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object.", + "examples": [ + { + "title": "Code Interpreter", + "request": { + "curl": "curl \"https://api.openai.com/v1/assistants\" \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"instructions\": \"You are a personal math tutor. When asked a question, write and run Python code to answer the question.\",\n \"name\": \"Math Tutor\",\n \"tools\": [{\"type\": \"code_interpreter\"}],\n \"model\": \"gpt-4o\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nassistant = client.beta.assistants.create(\n model=\"gpt-4o\",\n)\nprint(assistant.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst assistant = await client.beta.assistants.create({ model: 'gpt-4o' });\n\nconsole.log(assistant.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n assistant, err := client.Beta.Assistants.New(context.TODO(), openai.BetaAssistantNewParams{\n Model: shared.ChatModelGPT5,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", assistant.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.ChatModel;\nimport com.openai.models.beta.assistants.Assistant;\nimport com.openai.models.beta.assistants.AssistantCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n AssistantCreateParams params = AssistantCreateParams.builder()\n .model(ChatModel.GPT_5)\n .build();\n Assistant assistant = client.beta().assistants().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nassistant = openai.beta.assistants.create(model: :\"gpt-5\")\n\nputs(assistant)" + }, + "response": "{\n \"id\": \"asst_abc123\",\n \"object\": \"assistant\",\n \"created_at\": 1698984975,\n \"name\": \"Math Tutor\",\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You are a personal math tutor. When asked a question, write and run Python code to answer the question.\",\n \"tools\": [\n {\n \"type\": \"code_interpreter\"\n }\n ],\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n}\n" + }, + { + "title": "Files", + "request": { + "curl": "curl https://api.openai.com/v1/assistants \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"instructions\": \"You are an HR bot, and you have access to files to answer employee questions about company policies.\",\n \"tools\": [{\"type\": \"file_search\"}],\n \"tool_resources\": {\"file_search\": {\"vector_store_ids\": [\"vs_123\"]}},\n \"model\": \"gpt-4o\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nassistant = client.beta.assistants.create(\n model=\"gpt-4o\",\n)\nprint(assistant.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst assistant = await client.beta.assistants.create({ model: 'gpt-4o' });\n\nconsole.log(assistant.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n assistant, err := client.Beta.Assistants.New(context.TODO(), openai.BetaAssistantNewParams{\n Model: shared.ChatModelGPT5,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", assistant.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.ChatModel;\nimport com.openai.models.beta.assistants.Assistant;\nimport com.openai.models.beta.assistants.AssistantCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n AssistantCreateParams params = AssistantCreateParams.builder()\n .model(ChatModel.GPT_5)\n .build();\n Assistant assistant = client.beta().assistants().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nassistant = openai.beta.assistants.create(model: :\"gpt-5\")\n\nputs(assistant)" + }, + "response": "{\n \"id\": \"asst_abc123\",\n \"object\": \"assistant\",\n \"created_at\": 1699009403,\n \"name\": \"HR Helper\",\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You are an HR bot, and you have access to files to answer employee questions about company policies.\",\n \"tools\": [\n {\n \"type\": \"file_search\"\n }\n ],\n \"tool_resources\": {\n \"file_search\": {\n \"vector_store_ids\": [\"vs_123\"]\n }\n },\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n}\n" + } + ] + }, + "description": "Create an assistant with a model and instructions." + } + }, + "/assistants/{assistant_id}": { + "get": { + "operationId": "getAssistant", + "tags": [ + "Assistants" + ], + "summary": "Retrieve assistant", + "parameters": [ + { + "in": "path", + "name": "assistant_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the assistant to retrieve." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve assistant", + "group": "assistants", + "beta": true, + "returns": "The [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"asst_abc123\",\n \"object\": \"assistant\",\n \"created_at\": 1699009709,\n \"name\": \"HR Helper\",\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You are an HR bot, and you have access to files to answer employee questions about company policies.\",\n \"tools\": [\n {\n \"type\": \"file_search\"\n }\n ],\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/assistants/asst_abc123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nassistant = client.beta.assistants.retrieve(\n \"assistant_id\",\n)\nprint(assistant.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst assistant = await client.beta.assistants.retrieve('assistant_id');\n\nconsole.log(assistant.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n assistant, err := client.Beta.Assistants.Get(context.TODO(), \"assistant_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", assistant.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.assistants.Assistant;\nimport com.openai.models.beta.assistants.AssistantRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Assistant assistant = client.beta().assistants().retrieve(\"assistant_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nassistant = openai.beta.assistants.retrieve(\"assistant_id\")\n\nputs(assistant)" + } + } + }, + "description": "Retrieves an assistant." + }, + "post": { + "operationId": "modifyAssistant", + "tags": [ + "Assistants" + ], + "summary": "Modify assistant", + "parameters": [ + { + "in": "path", + "name": "assistant_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the assistant to modify." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ModifyAssistantRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Modify assistant", + "group": "assistants", + "beta": true, + "returns": "The modified [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object.", + "examples": { + "response": "{\n \"id\": \"asst_123\",\n \"object\": \"assistant\",\n \"created_at\": 1699009709,\n \"name\": \"HR Helper\",\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.\",\n \"tools\": [\n {\n \"type\": \"file_search\"\n }\n ],\n \"tool_resources\": {\n \"file_search\": {\n \"vector_store_ids\": []\n }\n },\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/assistants/asst_abc123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"instructions\": \"You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.\",\n \"tools\": [{\"type\": \"file_search\"}],\n \"model\": \"gpt-4o\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nassistant = client.beta.assistants.update(\n assistant_id=\"assistant_id\",\n)\nprint(assistant.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst assistant = await client.beta.assistants.update('assistant_id');\n\nconsole.log(assistant.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n assistant, err := client.Beta.Assistants.Update(\n context.TODO(),\n \"assistant_id\",\n openai.BetaAssistantUpdateParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", assistant.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.assistants.Assistant;\nimport com.openai.models.beta.assistants.AssistantUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Assistant assistant = client.beta().assistants().update(\"assistant_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nassistant = openai.beta.assistants.update(\"assistant_id\")\n\nputs(assistant)" + } + } + }, + "description": "Modifies an assistant." + }, + "delete": { + "operationId": "deleteAssistant", + "tags": [ + "Assistants" + ], + "summary": "Delete assistant", + "parameters": [ + { + "in": "path", + "name": "assistant_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the assistant to delete." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteAssistantResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete assistant", + "group": "assistants", + "beta": true, + "returns": "Deletion status", + "examples": { + "response": "{\n \"id\": \"asst_abc123\",\n \"object\": \"assistant.deleted\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/assistants/asst_abc123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -X DELETE\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nassistant_deleted = client.beta.assistants.delete(\n \"assistant_id\",\n)\nprint(assistant_deleted.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst assistantDeleted = await client.beta.assistants.delete('assistant_id');\n\nconsole.log(assistantDeleted.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n assistantDeleted, err := client.Beta.Assistants.Delete(context.TODO(), \"assistant_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", assistantDeleted.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.assistants.AssistantDeleteParams;\nimport com.openai.models.beta.assistants.AssistantDeleted;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n AssistantDeleted assistantDeleted = client.beta().assistants().delete(\"assistant_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nassistant_deleted = openai.beta.assistants.delete(\"assistant_id\")\n\nputs(assistant_deleted)" + } + } + }, + "description": "Delete an assistant." + } + }, + "/audio/speech": { + "post": { + "operationId": "createSpeech", + "tags": [ + "Audio" + ], + "summary": "Create speech", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateSpeechRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "headers": { + "Transfer-Encoding": { + "schema": { + "type": "string" + }, + "description": "chunked" + } + }, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "text/event-stream": { + "schema": { + "$ref": "#/components/schemas/CreateSpeechResponseStreamEvent" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create speech", + "group": "audio", + "returns": "The audio file content or a [stream of audio events](https://platform.openai.com/docs/api-reference/audio/speech-audio-delta-event).", + "examples": [ + { + "title": "Default", + "request": { + "curl": "curl https://api.openai.com/v1/audio/speech \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"gpt-4o-mini-tts\",\n \"input\": \"The quick brown fox jumped over the lazy dog.\",\n \"voice\": \"alloy\"\n }' \\\n --output speech.mp3\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nspeech = client.audio.speech.create(\n input=\"input\",\n model=\"string\",\n voice=\"ash\",\n)\nprint(speech)\ncontent = speech.read()\nprint(content)", + "javascript": "import fs from \"fs\";\nimport path from \"path\";\nimport OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nconst speechFile = path.resolve(\"./speech.mp3\");\n\nasync function main() {\n const mp3 = await openai.audio.speech.create({\n model: \"gpt-4o-mini-tts\",\n voice: \"alloy\",\n input: \"Today is a wonderful day to build something people love!\",\n });\n console.log(speechFile);\n const buffer = Buffer.from(await mp3.arrayBuffer());\n await fs.promises.writeFile(speechFile, buffer);\n}\nmain();\n", + "csharp": "using System;\nusing System.IO;\n\nusing OpenAI.Audio;\n\nAudioClient client = new(\n model: \"gpt-4o-mini-tts\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nBinaryData speech = client.GenerateSpeech(\n text: \"The quick brown fox jumped over the lazy dog.\",\n voice: GeneratedSpeechVoice.Alloy\n);\n\nusing FileStream stream = File.OpenWrite(\"speech.mp3\");\nspeech.ToStream().CopyTo(stream);\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst speech = await client.audio.speech.create({ input: 'input', model: 'string', voice: 'ash' });\n\nconsole.log(speech);\n\nconst content = await speech.blob();\nconsole.log(content);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n speech, err := client.Audio.Speech.New(context.TODO(), openai.AudioSpeechNewParams{\n Input: \"input\",\n Model: openai.SpeechModelTTS1,\n Voice: openai.AudioSpeechNewParamsVoiceAlloy,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", speech)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.core.http.HttpResponse;\nimport com.openai.models.audio.speech.SpeechCreateParams;\nimport com.openai.models.audio.speech.SpeechModel;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n SpeechCreateParams params = SpeechCreateParams.builder()\n .input(\"input\")\n .model(SpeechModel.TTS_1)\n .voice(SpeechCreateParams.Voice.ALLOY)\n .build();\n HttpResponse speech = client.audio().speech().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nspeech = openai.audio.speech.create(input: \"input\", model: :\"tts-1\", voice: :alloy)\n\nputs(speech)" + } + }, + { + "title": "SSE Stream Format", + "request": { + "curl": "curl https://api.openai.com/v1/audio/speech \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"gpt-4o-mini-tts\",\n \"input\": \"The quick brown fox jumped over the lazy dog.\",\n \"voice\": \"alloy\",\n \"stream_format\": \"sse\"\n }'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst speech = await client.audio.speech.create({ input: 'input', model: 'string', voice: 'ash' });\n\nconsole.log(speech);\n\nconst content = await speech.blob();\nconsole.log(content);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nspeech = client.audio.speech.create(\n input=\"input\",\n model=\"string\",\n voice=\"ash\",\n)\nprint(speech)\ncontent = speech.read()\nprint(content)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n speech, err := client.Audio.Speech.New(context.TODO(), openai.AudioSpeechNewParams{\n Input: \"input\",\n Model: openai.SpeechModelTTS1,\n Voice: openai.AudioSpeechNewParamsVoiceAlloy,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", speech)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.core.http.HttpResponse;\nimport com.openai.models.audio.speech.SpeechCreateParams;\nimport com.openai.models.audio.speech.SpeechModel;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n SpeechCreateParams params = SpeechCreateParams.builder()\n .input(\"input\")\n .model(SpeechModel.TTS_1)\n .voice(SpeechCreateParams.Voice.ALLOY)\n .build();\n HttpResponse speech = client.audio().speech().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nspeech = openai.audio.speech.create(input: \"input\", model: :\"tts-1\", voice: :alloy)\n\nputs(speech)" + } + } + ] + }, + "description": "Generates audio from the input text." + } + }, + "/audio/transcriptions": { + "post": { + "operationId": "createTranscription", + "tags": [ + "Audio" + ], + "summary": "Create transcription", + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/CreateTranscriptionRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/CreateTranscriptionResponseJson" + }, + { + "$ref": "#/components/schemas/CreateTranscriptionResponseVerboseJson", + "x-stainless-skip": [ + "go" + ] + } + ] + } + }, + "text/event-stream": { + "schema": { + "$ref": "#/components/schemas/CreateTranscriptionResponseStreamEvent" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create transcription", + "group": "audio", + "returns": "The [transcription object](https://platform.openai.com/docs/api-reference/audio/json-object), a [verbose transcription object](https://platform.openai.com/docs/api-reference/audio/verbose-json-object) or a [stream of transcript events](https://platform.openai.com/docs/api-reference/audio/transcript-text-delta-event).", + "examples": [ + { + "title": "Default", + "request": { + "curl": "curl https://api.openai.com/v1/audio/transcriptions \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: multipart/form-data\" \\\n -F file=\"@/path/to/file/audio.mp3\" \\\n -F model=\"gpt-4o-transcribe\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ntranscription = client.audio.transcriptions.create(\n file=b\"raw file contents\",\n model=\"gpt-4o-transcribe\",\n)\nprint(transcription)", + "javascript": "import fs from \"fs\";\nimport OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nasync function main() {\n const transcription = await openai.audio.transcriptions.create({\n file: fs.createReadStream(\"audio.mp3\"),\n model: \"gpt-4o-transcribe\",\n });\n\n console.log(transcription.text);\n}\nmain();\n", + "csharp": "using System;\n\nusing OpenAI.Audio;\nstring audioFilePath = \"audio.mp3\";\n\nAudioClient client = new(\n model: \"gpt-4o-transcribe\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nAudioTranscription transcription = client.TranscribeAudio(audioFilePath);\n\nConsole.WriteLine($\"{transcription.Text}\");\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst transcription = await client.audio.transcriptions.create({\n file: fs.createReadStream('speech.mp3'),\n model: 'gpt-4o-transcribe',\n});\n\nconsole.log(transcription);", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n File: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n Model: openai.AudioModelWhisper1,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", transcription)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.audio.AudioModel;\nimport com.openai.models.audio.transcriptions.TranscriptionCreateParams;\nimport com.openai.models.audio.transcriptions.TranscriptionCreateResponse;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n TranscriptionCreateParams params = TranscriptionCreateParams.builder()\n .file(ByteArrayInputStream(\"some content\".getBytes()))\n .model(AudioModel.WHISPER_1)\n .build();\n TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ntranscription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :\"whisper-1\")\n\nputs(transcription)" + }, + "response": "{\n \"text\": \"Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that.\",\n \"usage\": {\n \"type\": \"tokens\",\n \"input_tokens\": 14,\n \"input_token_details\": {\n \"text_tokens\": 0,\n \"audio_tokens\": 14\n },\n \"output_tokens\": 45,\n \"total_tokens\": 59\n }\n}\n" + }, + { + "title": "Streaming", + "request": { + "curl": "curl https://api.openai.com/v1/audio/transcriptions \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: multipart/form-data\" \\\n -F file=\"@/path/to/file/audio.mp3\" \\\n -F model=\"gpt-4o-mini-transcribe\" \\\n -F stream=true\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ntranscription = client.audio.transcriptions.create(\n file=b\"raw file contents\",\n model=\"gpt-4o-transcribe\",\n)\nprint(transcription)", + "javascript": "import fs from \"fs\";\nimport OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nconst stream = await openai.audio.transcriptions.create({\n file: fs.createReadStream(\"audio.mp3\"),\n model: \"gpt-4o-mini-transcribe\",\n stream: true,\n});\n\nfor await (const event of stream) {\n console.log(event);\n}\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst transcription = await client.audio.transcriptions.create({\n file: fs.createReadStream('speech.mp3'),\n model: 'gpt-4o-transcribe',\n});\n\nconsole.log(transcription);", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n File: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n Model: openai.AudioModelWhisper1,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", transcription)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.audio.AudioModel;\nimport com.openai.models.audio.transcriptions.TranscriptionCreateParams;\nimport com.openai.models.audio.transcriptions.TranscriptionCreateResponse;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n TranscriptionCreateParams params = TranscriptionCreateParams.builder()\n .file(ByteArrayInputStream(\"some content\".getBytes()))\n .model(AudioModel.WHISPER_1)\n .build();\n TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ntranscription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :\"whisper-1\")\n\nputs(transcription)" + }, + "response": "data: {\"type\":\"transcript.text.delta\",\"delta\":\"I\",\"logprobs\":[{\"token\":\"I\",\"logprob\":-0.00007588794,\"bytes\":[73]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" see\",\"logprobs\":[{\"token\":\" see\",\"logprob\":-3.1281633e-7,\"bytes\":[32,115,101,101]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" skies\",\"logprobs\":[{\"token\":\" skies\",\"logprob\":-2.3392786e-6,\"bytes\":[32,115,107,105,101,115]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" of\",\"logprobs\":[{\"token\":\" of\",\"logprob\":-3.1281633e-7,\"bytes\":[32,111,102]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" blue\",\"logprobs\":[{\"token\":\" blue\",\"logprob\":-1.0280384e-6,\"bytes\":[32,98,108,117,101]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" and\",\"logprobs\":[{\"token\":\" and\",\"logprob\":-0.0005108566,\"bytes\":[32,97,110,100]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" clouds\",\"logprobs\":[{\"token\":\" clouds\",\"logprob\":-1.9361265e-7,\"bytes\":[32,99,108,111,117,100,115]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" of\",\"logprobs\":[{\"token\":\" of\",\"logprob\":-1.9361265e-7,\"bytes\":[32,111,102]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" white\",\"logprobs\":[{\"token\":\" white\",\"logprob\":-7.89631e-7,\"bytes\":[32,119,104,105,116,101]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\",\",\"logprobs\":[{\"token\":\",\",\"logprob\":-0.0014890312,\"bytes\":[44]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" the\",\"logprobs\":[{\"token\":\" the\",\"logprob\":-0.0110956915,\"bytes\":[32,116,104,101]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" bright\",\"logprobs\":[{\"token\":\" bright\",\"logprob\":0.0,\"bytes\":[32,98,114,105,103,104,116]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" blessed\",\"logprobs\":[{\"token\":\" blessed\",\"logprob\":-0.000045848617,\"bytes\":[32,98,108,101,115,115,101,100]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" days\",\"logprobs\":[{\"token\":\" days\",\"logprob\":-0.000010802739,\"bytes\":[32,100,97,121,115]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\",\",\"logprobs\":[{\"token\":\",\",\"logprob\":-0.00001700133,\"bytes\":[44]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" the\",\"logprobs\":[{\"token\":\" the\",\"logprob\":-0.0000118755715,\"bytes\":[32,116,104,101]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" dark\",\"logprobs\":[{\"token\":\" dark\",\"logprob\":-5.5122365e-7,\"bytes\":[32,100,97,114,107]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" sacred\",\"logprobs\":[{\"token\":\" sacred\",\"logprob\":-5.4385737e-6,\"bytes\":[32,115,97,99,114,101,100]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" nights\",\"logprobs\":[{\"token\":\" nights\",\"logprob\":-4.00813e-6,\"bytes\":[32,110,105,103,104,116,115]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\",\",\"logprobs\":[{\"token\":\",\",\"logprob\":-0.0036910512,\"bytes\":[44]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" and\",\"logprobs\":[{\"token\":\" and\",\"logprob\":-0.0031903093,\"bytes\":[32,97,110,100]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" I\",\"logprobs\":[{\"token\":\" I\",\"logprob\":-1.504853e-6,\"bytes\":[32,73]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" think\",\"logprobs\":[{\"token\":\" think\",\"logprob\":-4.3202e-7,\"bytes\":[32,116,104,105,110,107]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" to\",\"logprobs\":[{\"token\":\" to\",\"logprob\":-1.9361265e-7,\"bytes\":[32,116,111]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" myself\",\"logprobs\":[{\"token\":\" myself\",\"logprob\":-1.7432603e-6,\"bytes\":[32,109,121,115,101,108,102]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\",\",\"logprobs\":[{\"token\":\",\",\"logprob\":-0.29254505,\"bytes\":[44]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" what\",\"logprobs\":[{\"token\":\" what\",\"logprob\":-0.016815351,\"bytes\":[32,119,104,97,116]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" a\",\"logprobs\":[{\"token\":\" a\",\"logprob\":-3.1281633e-7,\"bytes\":[32,97]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" wonderful\",\"logprobs\":[{\"token\":\" wonderful\",\"logprob\":-2.1008714e-6,\"bytes\":[32,119,111,110,100,101,114,102,117,108]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\" world\",\"logprobs\":[{\"token\":\" world\",\"logprob\":-8.180258e-6,\"bytes\":[32,119,111,114,108,100]}]}\n\ndata: {\"type\":\"transcript.text.delta\",\"delta\":\".\",\"logprobs\":[{\"token\":\".\",\"logprob\":-0.014231676,\"bytes\":[46]}]}\n\ndata: {\"type\":\"transcript.text.done\",\"text\":\"I see skies of blue and clouds of white, the bright blessed days, the dark sacred nights, and I think to myself, what a wonderful world.\",\"logprobs\":[{\"token\":\"I\",\"logprob\":-0.00007588794,\"bytes\":[73]},{\"token\":\" see\",\"logprob\":-3.1281633e-7,\"bytes\":[32,115,101,101]},{\"token\":\" skies\",\"logprob\":-2.3392786e-6,\"bytes\":[32,115,107,105,101,115]},{\"token\":\" of\",\"logprob\":-3.1281633e-7,\"bytes\":[32,111,102]},{\"token\":\" blue\",\"logprob\":-1.0280384e-6,\"bytes\":[32,98,108,117,101]},{\"token\":\" and\",\"logprob\":-0.0005108566,\"bytes\":[32,97,110,100]},{\"token\":\" clouds\",\"logprob\":-1.9361265e-7,\"bytes\":[32,99,108,111,117,100,115]},{\"token\":\" of\",\"logprob\":-1.9361265e-7,\"bytes\":[32,111,102]},{\"token\":\" white\",\"logprob\":-7.89631e-7,\"bytes\":[32,119,104,105,116,101]},{\"token\":\",\",\"logprob\":-0.0014890312,\"bytes\":[44]},{\"token\":\" the\",\"logprob\":-0.0110956915,\"bytes\":[32,116,104,101]},{\"token\":\" bright\",\"logprob\":0.0,\"bytes\":[32,98,114,105,103,104,116]},{\"token\":\" blessed\",\"logprob\":-0.000045848617,\"bytes\":[32,98,108,101,115,115,101,100]},{\"token\":\" days\",\"logprob\":-0.000010802739,\"bytes\":[32,100,97,121,115]},{\"token\":\",\",\"logprob\":-0.00001700133,\"bytes\":[44]},{\"token\":\" the\",\"logprob\":-0.0000118755715,\"bytes\":[32,116,104,101]},{\"token\":\" dark\",\"logprob\":-5.5122365e-7,\"bytes\":[32,100,97,114,107]},{\"token\":\" sacred\",\"logprob\":-5.4385737e-6,\"bytes\":[32,115,97,99,114,101,100]},{\"token\":\" nights\",\"logprob\":-4.00813e-6,\"bytes\":[32,110,105,103,104,116,115]},{\"token\":\",\",\"logprob\":-0.0036910512,\"bytes\":[44]},{\"token\":\" and\",\"logprob\":-0.0031903093,\"bytes\":[32,97,110,100]},{\"token\":\" I\",\"logprob\":-1.504853e-6,\"bytes\":[32,73]},{\"token\":\" think\",\"logprob\":-4.3202e-7,\"bytes\":[32,116,104,105,110,107]},{\"token\":\" to\",\"logprob\":-1.9361265e-7,\"bytes\":[32,116,111]},{\"token\":\" myself\",\"logprob\":-1.7432603e-6,\"bytes\":[32,109,121,115,101,108,102]},{\"token\":\",\",\"logprob\":-0.29254505,\"bytes\":[44]},{\"token\":\" what\",\"logprob\":-0.016815351,\"bytes\":[32,119,104,97,116]},{\"token\":\" a\",\"logprob\":-3.1281633e-7,\"bytes\":[32,97]},{\"token\":\" wonderful\",\"logprob\":-2.1008714e-6,\"bytes\":[32,119,111,110,100,101,114,102,117,108]},{\"token\":\" world\",\"logprob\":-8.180258e-6,\"bytes\":[32,119,111,114,108,100]},{\"token\":\".\",\"logprob\":-0.014231676,\"bytes\":[46]}],\"usage\":{\"input_tokens\":14,\"input_token_details\":{\"text_tokens\":0,\"audio_tokens\":14},\"output_tokens\":45,\"total_tokens\":59}}\n" + }, + { + "title": "Logprobs", + "request": { + "curl": "curl https://api.openai.com/v1/audio/transcriptions \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: multipart/form-data\" \\\n -F file=\"@/path/to/file/audio.mp3\" \\\n -F \"include[]=logprobs\" \\\n -F model=\"gpt-4o-transcribe\" \\\n -F response_format=\"json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ntranscription = client.audio.transcriptions.create(\n file=b\"raw file contents\",\n model=\"gpt-4o-transcribe\",\n)\nprint(transcription)", + "javascript": "import fs from \"fs\";\nimport OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nasync function main() {\n const transcription = await openai.audio.transcriptions.create({\n file: fs.createReadStream(\"audio.mp3\"),\n model: \"gpt-4o-transcribe\",\n response_format: \"json\",\n include: [\"logprobs\"]\n });\n\n console.log(transcription);\n}\nmain();\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst transcription = await client.audio.transcriptions.create({\n file: fs.createReadStream('speech.mp3'),\n model: 'gpt-4o-transcribe',\n});\n\nconsole.log(transcription);", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n File: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n Model: openai.AudioModelWhisper1,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", transcription)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.audio.AudioModel;\nimport com.openai.models.audio.transcriptions.TranscriptionCreateParams;\nimport com.openai.models.audio.transcriptions.TranscriptionCreateResponse;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n TranscriptionCreateParams params = TranscriptionCreateParams.builder()\n .file(ByteArrayInputStream(\"some content\".getBytes()))\n .model(AudioModel.WHISPER_1)\n .build();\n TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ntranscription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :\"whisper-1\")\n\nputs(transcription)" + }, + "response": "{\n \"text\": \"Hey, my knee is hurting and I want to see the doctor tomorrow ideally.\",\n \"logprobs\": [\n { \"token\": \"Hey\", \"logprob\": -1.0415299, \"bytes\": [72, 101, 121] },\n { \"token\": \",\", \"logprob\": -9.805982e-5, \"bytes\": [44] },\n { \"token\": \" my\", \"logprob\": -0.00229799, \"bytes\": [32, 109, 121] },\n {\n \"token\": \" knee\",\n \"logprob\": -4.7159858e-5,\n \"bytes\": [32, 107, 110, 101, 101]\n },\n { \"token\": \" is\", \"logprob\": -0.043909557, \"bytes\": [32, 105, 115] },\n {\n \"token\": \" hurting\",\n \"logprob\": -1.1041146e-5,\n \"bytes\": [32, 104, 117, 114, 116, 105, 110, 103]\n },\n { \"token\": \" and\", \"logprob\": -0.011076359, \"bytes\": [32, 97, 110, 100] },\n { \"token\": \" I\", \"logprob\": -5.3193703e-6, \"bytes\": [32, 73] },\n {\n \"token\": \" want\",\n \"logprob\": -0.0017156356,\n \"bytes\": [32, 119, 97, 110, 116]\n },\n { \"token\": \" to\", \"logprob\": -7.89631e-7, \"bytes\": [32, 116, 111] },\n { \"token\": \" see\", \"logprob\": -5.5122365e-7, \"bytes\": [32, 115, 101, 101] },\n { \"token\": \" the\", \"logprob\": -0.0040786397, \"bytes\": [32, 116, 104, 101] },\n {\n \"token\": \" doctor\",\n \"logprob\": -2.3392786e-6,\n \"bytes\": [32, 100, 111, 99, 116, 111, 114]\n },\n {\n \"token\": \" tomorrow\",\n \"logprob\": -7.89631e-7,\n \"bytes\": [32, 116, 111, 109, 111, 114, 114, 111, 119]\n },\n {\n \"token\": \" ideally\",\n \"logprob\": -0.5800861,\n \"bytes\": [32, 105, 100, 101, 97, 108, 108, 121]\n },\n { \"token\": \".\", \"logprob\": -0.00011093382, \"bytes\": [46] }\n ],\n \"usage\": {\n \"type\": \"tokens\",\n \"input_tokens\": 14,\n \"input_token_details\": {\n \"text_tokens\": 0,\n \"audio_tokens\": 14\n },\n \"output_tokens\": 45,\n \"total_tokens\": 59\n }\n}\n" + }, + { + "title": "Word timestamps", + "request": { + "curl": "curl https://api.openai.com/v1/audio/transcriptions \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: multipart/form-data\" \\\n -F file=\"@/path/to/file/audio.mp3\" \\\n -F \"timestamp_granularities[]=word\" \\\n -F model=\"whisper-1\" \\\n -F response_format=\"verbose_json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ntranscription = client.audio.transcriptions.create(\n file=b\"raw file contents\",\n model=\"gpt-4o-transcribe\",\n)\nprint(transcription)", + "javascript": "import fs from \"fs\";\nimport OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nasync function main() {\n const transcription = await openai.audio.transcriptions.create({\n file: fs.createReadStream(\"audio.mp3\"),\n model: \"whisper-1\",\n response_format: \"verbose_json\",\n timestamp_granularities: [\"word\"]\n });\n\n console.log(transcription.text);\n}\nmain();\n", + "csharp": "using System;\n\nusing OpenAI.Audio;\n\nstring audioFilePath = \"audio.mp3\";\n\nAudioClient client = new(\n model: \"whisper-1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nAudioTranscriptionOptions options = new()\n{\n ResponseFormat = AudioTranscriptionFormat.Verbose,\n TimestampGranularities = AudioTimestampGranularities.Word,\n};\n\nAudioTranscription transcription = client.TranscribeAudio(audioFilePath, options);\n\nConsole.WriteLine($\"{transcription.Text}\");\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst transcription = await client.audio.transcriptions.create({\n file: fs.createReadStream('speech.mp3'),\n model: 'gpt-4o-transcribe',\n});\n\nconsole.log(transcription);", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n File: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n Model: openai.AudioModelWhisper1,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", transcription)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.audio.AudioModel;\nimport com.openai.models.audio.transcriptions.TranscriptionCreateParams;\nimport com.openai.models.audio.transcriptions.TranscriptionCreateResponse;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n TranscriptionCreateParams params = TranscriptionCreateParams.builder()\n .file(ByteArrayInputStream(\"some content\".getBytes()))\n .model(AudioModel.WHISPER_1)\n .build();\n TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ntranscription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :\"whisper-1\")\n\nputs(transcription)" + }, + "response": "{\n \"task\": \"transcribe\",\n \"language\": \"english\",\n \"duration\": 8.470000267028809,\n \"text\": \"The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.\",\n \"words\": [\n {\n \"word\": \"The\",\n \"start\": 0.0,\n \"end\": 0.23999999463558197\n },\n ...\n {\n \"word\": \"volleyball\",\n \"start\": 7.400000095367432,\n \"end\": 7.900000095367432\n }\n ],\n \"usage\": {\n \"type\": \"duration\",\n \"seconds\": 9\n }\n}\n" + }, + { + "title": "Segment timestamps", + "request": { + "curl": "curl https://api.openai.com/v1/audio/transcriptions \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: multipart/form-data\" \\\n -F file=\"@/path/to/file/audio.mp3\" \\\n -F \"timestamp_granularities[]=segment\" \\\n -F model=\"whisper-1\" \\\n -F response_format=\"verbose_json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ntranscription = client.audio.transcriptions.create(\n file=b\"raw file contents\",\n model=\"gpt-4o-transcribe\",\n)\nprint(transcription)", + "javascript": "import fs from \"fs\";\nimport OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nasync function main() {\n const transcription = await openai.audio.transcriptions.create({\n file: fs.createReadStream(\"audio.mp3\"),\n model: \"whisper-1\",\n response_format: \"verbose_json\",\n timestamp_granularities: [\"segment\"]\n });\n\n console.log(transcription.text);\n}\nmain();\n", + "csharp": "using System;\n\nusing OpenAI.Audio;\n\nstring audioFilePath = \"audio.mp3\";\n\nAudioClient client = new(\n model: \"whisper-1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nAudioTranscriptionOptions options = new()\n{\n ResponseFormat = AudioTranscriptionFormat.Verbose,\n TimestampGranularities = AudioTimestampGranularities.Segment,\n};\n\nAudioTranscription transcription = client.TranscribeAudio(audioFilePath, options);\n\nConsole.WriteLine($\"{transcription.Text}\");\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst transcription = await client.audio.transcriptions.create({\n file: fs.createReadStream('speech.mp3'),\n model: 'gpt-4o-transcribe',\n});\n\nconsole.log(transcription);", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n File: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n Model: openai.AudioModelWhisper1,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", transcription)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.audio.AudioModel;\nimport com.openai.models.audio.transcriptions.TranscriptionCreateParams;\nimport com.openai.models.audio.transcriptions.TranscriptionCreateResponse;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n TranscriptionCreateParams params = TranscriptionCreateParams.builder()\n .file(ByteArrayInputStream(\"some content\".getBytes()))\n .model(AudioModel.WHISPER_1)\n .build();\n TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ntranscription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :\"whisper-1\")\n\nputs(transcription)" + }, + "response": "{\n \"task\": \"transcribe\",\n \"language\": \"english\",\n \"duration\": 8.470000267028809,\n \"text\": \"The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.\",\n \"segments\": [\n {\n \"id\": 0,\n \"seek\": 0,\n \"start\": 0.0,\n \"end\": 3.319999933242798,\n \"text\": \" The beach was a popular spot on a hot summer day.\",\n \"tokens\": [\n 50364, 440, 7534, 390, 257, 3743, 4008, 322, 257, 2368, 4266, 786, 13, 50530\n ],\n \"temperature\": 0.0,\n \"avg_logprob\": -0.2860786020755768,\n \"compression_ratio\": 1.2363636493682861,\n \"no_speech_prob\": 0.00985979475080967\n },\n ...\n ],\n \"usage\": {\n \"type\": \"duration\",\n \"seconds\": 9\n }\n}\n" + } + ] + }, + "description": "Transcribes audio into the input language." + } + }, + "/audio/translations": { + "post": { + "operationId": "createTranslation", + "tags": [ + "Audio" + ], + "summary": "Create translation", + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/CreateTranslationRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/CreateTranslationResponseJson" + }, + { + "$ref": "#/components/schemas/CreateTranslationResponseVerboseJson", + "x-stainless-skip": [ + "go" + ] + } + ] + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create translation", + "group": "audio", + "returns": "The translated text.", + "examples": { + "response": "{\n \"text\": \"Hello, my name is Wolfgang and I come from Germany. Where are you heading today?\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/audio/translations \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: multipart/form-data\" \\\n -F file=\"@/path/to/file/german.m4a\" \\\n -F model=\"whisper-1\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ntranslation = client.audio.translations.create(\n file=b\"raw file contents\",\n model=\"whisper-1\",\n)\nprint(translation)", + "javascript": "import fs from \"fs\";\nimport OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nasync function main() {\n const translation = await openai.audio.translations.create({\n file: fs.createReadStream(\"speech.mp3\"),\n model: \"whisper-1\",\n });\n\n console.log(translation.text);\n}\nmain();\n", + "csharp": "using System;\n\nusing OpenAI.Audio;\n\nstring audioFilePath = \"audio.mp3\";\n\nAudioClient client = new(\n model: \"whisper-1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nAudioTranscription transcription = client.TranscribeAudio(audioFilePath);\n\nConsole.WriteLine($\"{transcription.Text}\");\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst translation = await client.audio.translations.create({\n file: fs.createReadStream('speech.mp3'),\n model: 'whisper-1',\n});\n\nconsole.log(translation);", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n translation, err := client.Audio.Translations.New(context.TODO(), openai.AudioTranslationNewParams{\n File: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n Model: openai.AudioModelWhisper1,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", translation)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.audio.AudioModel;\nimport com.openai.models.audio.translations.TranslationCreateParams;\nimport com.openai.models.audio.translations.TranslationCreateResponse;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n TranslationCreateParams params = TranslationCreateParams.builder()\n .file(ByteArrayInputStream(\"some content\".getBytes()))\n .model(AudioModel.WHISPER_1)\n .build();\n TranslationCreateResponse translation = client.audio().translations().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ntranslation = openai.audio.translations.create(file: Pathname(__FILE__), model: :\"whisper-1\")\n\nputs(translation)" + } + } + }, + "description": "Translates audio into English." + } + }, + "/batches": { + "post": { + "summary": "Create batch", + "operationId": "createBatch", + "tags": [ + "Batch" + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "input_file_id", + "endpoint", + "completion_window" + ], + "properties": { + "input_file_id": { + "type": "string", + "description": "The ID of an uploaded file that contains requests for the new batch.\n\nSee [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file.\n\nYour input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 200 MB in size.\n" + }, + "endpoint": { + "type": "string", + "enum": [ + "/v1/responses", + "/v1/chat/completions", + "/v1/embeddings", + "/v1/completions" + ], + "description": "The endpoint to be used for all requests in the batch. Currently `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch." + }, + "completion_window": { + "type": "string", + "enum": [ + "24h" + ], + "description": "The time frame within which the batch should be processed. Currently only `24h` is supported." + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "output_expires_after": { + "$ref": "#/components/schemas/BatchFileExpirationAfter" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Batch created successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Batch" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create batch", + "group": "batch", + "returns": "The created [Batch](https://platform.openai.com/docs/api-reference/batch/object) object.", + "examples": { + "response": "{\n \"id\": \"batch_abc123\",\n \"object\": \"batch\",\n \"endpoint\": \"/v1/chat/completions\",\n \"errors\": null,\n \"input_file_id\": \"file-abc123\",\n \"completion_window\": \"24h\",\n \"status\": \"validating\",\n \"output_file_id\": null,\n \"error_file_id\": null,\n \"created_at\": 1711471533,\n \"in_progress_at\": null,\n \"expires_at\": null,\n \"finalizing_at\": null,\n \"completed_at\": null,\n \"failed_at\": null,\n \"expired_at\": null,\n \"cancelling_at\": null,\n \"cancelled_at\": null,\n \"request_counts\": {\n \"total\": 0,\n \"completed\": 0,\n \"failed\": 0\n },\n \"metadata\": {\n \"customer_id\": \"user_123456789\",\n \"batch_description\": \"Nightly eval job\",\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/batches \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"input_file_id\": \"file-abc123\",\n \"endpoint\": \"/v1/chat/completions\",\n \"completion_window\": \"24h\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nbatch = client.batches.create(\n completion_window=\"24h\",\n endpoint=\"/v1/responses\",\n input_file_id=\"input_file_id\",\n)\nprint(batch.id)", + "node": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nasync function main() {\n const batch = await openai.batches.create({\n input_file_id: \"file-abc123\",\n endpoint: \"/v1/chat/completions\",\n completion_window: \"24h\"\n });\n\n console.log(batch);\n}\n\nmain();\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst batch = await client.batches.create({\n completion_window: '24h',\n endpoint: '/v1/responses',\n input_file_id: 'input_file_id',\n});\n\nconsole.log(batch.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n batch, err := client.Batches.New(context.TODO(), openai.BatchNewParams{\n CompletionWindow: openai.BatchNewParamsCompletionWindow24h,\n Endpoint: openai.BatchNewParamsEndpointV1Responses,\n InputFileID: \"input_file_id\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", batch.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.batches.Batch;\nimport com.openai.models.batches.BatchCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n BatchCreateParams params = BatchCreateParams.builder()\n .completionWindow(BatchCreateParams.CompletionWindow._24H)\n .endpoint(BatchCreateParams.Endpoint.V1_RESPONSES)\n .inputFileId(\"input_file_id\")\n .build();\n Batch batch = client.batches().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nbatch = openai.batches.create(\n completion_window: :\"24h\",\n endpoint: :\"/v1/responses\",\n input_file_id: \"input_file_id\"\n)\n\nputs(batch)" + } + } + }, + "description": "Creates and executes a batch from an uploaded file of requests" + }, + "get": { + "operationId": "listBatches", + "tags": [ + "Batch" + ], + "summary": "List batch", + "parameters": [ + { + "in": "query", + "name": "after", + "required": false, + "schema": { + "type": "string" + }, + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n" + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + } + ], + "responses": { + "200": { + "description": "Batch listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListBatchesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List batch", + "group": "batch", + "returns": "A list of paginated [Batch](https://platform.openai.com/docs/api-reference/batch/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"batch_abc123\",\n \"object\": \"batch\",\n \"endpoint\": \"/v1/chat/completions\",\n \"errors\": null,\n \"input_file_id\": \"file-abc123\",\n \"completion_window\": \"24h\",\n \"status\": \"completed\",\n \"output_file_id\": \"file-cvaTdG\",\n \"error_file_id\": \"file-HOWS94\",\n \"created_at\": 1711471533,\n \"in_progress_at\": 1711471538,\n \"expires_at\": 1711557933,\n \"finalizing_at\": 1711493133,\n \"completed_at\": 1711493163,\n \"failed_at\": null,\n \"expired_at\": null,\n \"cancelling_at\": null,\n \"cancelled_at\": null,\n \"request_counts\": {\n \"total\": 100,\n \"completed\": 95,\n \"failed\": 5\n },\n \"metadata\": {\n \"customer_id\": \"user_123456789\",\n \"batch_description\": \"Nightly job\",\n }\n },\n { ... },\n ],\n \"first_id\": \"batch_abc123\",\n \"last_id\": \"batch_abc456\",\n \"has_more\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/batches?limit=2 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.batches.list()\npage = page.data[0]\nprint(page.id)", + "node": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nasync function main() {\n const list = await openai.batches.list();\n\n for await (const batch of list) {\n console.log(batch);\n }\n}\n\nmain();\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const batch of client.batches.list()) {\n console.log(batch.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Batches.List(context.TODO(), openai.BatchListParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.batches.BatchListPage;\nimport com.openai.models.batches.BatchListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n BatchListPage page = client.batches().list();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.batches.list\n\nputs(page)" + } + } + }, + "description": "List your organization's batches." + } + }, + "/batches/{batch_id}": { + "get": { + "operationId": "retrieveBatch", + "tags": [ + "Batch" + ], + "summary": "Retrieve batch", + "parameters": [ + { + "in": "path", + "name": "batch_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the batch to retrieve." + } + ], + "responses": { + "200": { + "description": "Batch retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Batch" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve batch", + "group": "batch", + "returns": "The [Batch](https://platform.openai.com/docs/api-reference/batch/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"batch_abc123\",\n \"object\": \"batch\",\n \"endpoint\": \"/v1/completions\",\n \"errors\": null,\n \"input_file_id\": \"file-abc123\",\n \"completion_window\": \"24h\",\n \"status\": \"completed\",\n \"output_file_id\": \"file-cvaTdG\",\n \"error_file_id\": \"file-HOWS94\",\n \"created_at\": 1711471533,\n \"in_progress_at\": 1711471538,\n \"expires_at\": 1711557933,\n \"finalizing_at\": 1711493133,\n \"completed_at\": 1711493163,\n \"failed_at\": null,\n \"expired_at\": null,\n \"cancelling_at\": null,\n \"cancelled_at\": null,\n \"request_counts\": {\n \"total\": 100,\n \"completed\": 95,\n \"failed\": 5\n },\n \"metadata\": {\n \"customer_id\": \"user_123456789\",\n \"batch_description\": \"Nightly eval job\",\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/batches/batch_abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nbatch = client.batches.retrieve(\n \"batch_id\",\n)\nprint(batch.id)", + "node": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nasync function main() {\n const batch = await openai.batches.retrieve(\"batch_abc123\");\n\n console.log(batch);\n}\n\nmain();\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst batch = await client.batches.retrieve('batch_id');\n\nconsole.log(batch.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n batch, err := client.Batches.Get(context.TODO(), \"batch_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", batch.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.batches.Batch;\nimport com.openai.models.batches.BatchRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Batch batch = client.batches().retrieve(\"batch_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nbatch = openai.batches.retrieve(\"batch_id\")\n\nputs(batch)" + } + } + }, + "description": "Retrieves a batch." + } + }, + "/batches/{batch_id}/cancel": { + "post": { + "operationId": "cancelBatch", + "tags": [ + "Batch" + ], + "summary": "Cancel batch", + "parameters": [ + { + "in": "path", + "name": "batch_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the batch to cancel." + } + ], + "responses": { + "200": { + "description": "Batch is cancelling. Returns the cancelling batch's details.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Batch" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Cancel batch", + "group": "batch", + "returns": "The [Batch](https://platform.openai.com/docs/api-reference/batch/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"batch_abc123\",\n \"object\": \"batch\",\n \"endpoint\": \"/v1/chat/completions\",\n \"errors\": null,\n \"input_file_id\": \"file-abc123\",\n \"completion_window\": \"24h\",\n \"status\": \"cancelling\",\n \"output_file_id\": null,\n \"error_file_id\": null,\n \"created_at\": 1711471533,\n \"in_progress_at\": 1711471538,\n \"expires_at\": 1711557933,\n \"finalizing_at\": null,\n \"completed_at\": null,\n \"failed_at\": null,\n \"expired_at\": null,\n \"cancelling_at\": 1711475133,\n \"cancelled_at\": null,\n \"request_counts\": {\n \"total\": 100,\n \"completed\": 23,\n \"failed\": 1\n },\n \"metadata\": {\n \"customer_id\": \"user_123456789\",\n \"batch_description\": \"Nightly eval job\",\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/batches/batch_abc123/cancel \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -X POST\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nbatch = client.batches.cancel(\n \"batch_id\",\n)\nprint(batch.id)", + "node": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nasync function main() {\n const batch = await openai.batches.cancel(\"batch_abc123\");\n\n console.log(batch);\n}\n\nmain();\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst batch = await client.batches.cancel('batch_id');\n\nconsole.log(batch.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n batch, err := client.Batches.Cancel(context.TODO(), \"batch_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", batch.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.batches.Batch;\nimport com.openai.models.batches.BatchCancelParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Batch batch = client.batches().cancel(\"batch_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nbatch = openai.batches.cancel(\"batch_id\")\n\nputs(batch)" + } + } + }, + "description": "Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, before changing to `cancelled`, where it will have partial results (if any) available in the output file." + } + }, + "/chat/completions": { + "get": { + "operationId": "listChatCompletions", + "tags": [ + "Chat" + ], + "summary": "List Chat Completions", + "parameters": [ + { + "name": "model", + "in": "query", + "description": "The model used to generate the Chat Completions.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "metadata", + "in": "query", + "description": "A list of metadata keys to filter the Chat Completions by. Example:\n\n`metadata[key1]=value1&metadata[key2]=value2`\n", + "required": false, + "schema": { + "$ref": "#/components/schemas/Metadata" + } + }, + { + "name": "after", + "in": "query", + "description": "Identifier for the last chat completion from the previous pagination request.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of Chat Completions to retrieve.", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order for Chat Completions by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "asc", + "desc" + ], + "default": "asc" + } + } + ], + "responses": { + "200": { + "description": "A list of Chat Completions", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatCompletionList" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List Chat Completions", + "group": "chat", + "returns": "A list of [Chat Completions](https://platform.openai.com/docs/api-reference/chat/list-object) matching the specified filters.", + "path": "list", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"chat.completion\",\n \"id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2\",\n \"model\": \"gpt-4.1-2025-04-14\",\n \"created\": 1738960610,\n \"request_id\": \"req_ded8ab984ec4bf840f37566c1011c417\",\n \"tool_choice\": null,\n \"usage\": {\n \"total_tokens\": 31,\n \"completion_tokens\": 18,\n \"prompt_tokens\": 13\n },\n \"seed\": 4944116822809979520,\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"presence_penalty\": 0.0,\n \"frequency_penalty\": 0.0,\n \"system_fingerprint\": \"fp_50cad350e4\",\n \"input_user\": null,\n \"service_tier\": \"default\",\n \"tools\": null,\n \"metadata\": {},\n \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"content\": \"Mind of circuits hum, \\nLearning patterns in silence— \\nFuture's quiet spark.\",\n \"role\": \"assistant\",\n \"tool_calls\": null,\n \"function_call\": null\n },\n \"finish_reason\": \"stop\",\n \"logprobs\": null\n }\n ],\n \"response_format\": null\n }\n ],\n \"first_id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2\",\n \"last_id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/chat/completions \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.chat.completions.list()\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const chatCompletion of client.chat.completions.list()) {\n console.log(chatCompletion.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Chat.Completions.List(context.TODO(), openai.ChatCompletionListParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.chat.completions.ChatCompletionListPage;\nimport com.openai.models.chat.completions.ChatCompletionListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ChatCompletionListPage page = client.chat().completions().list();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.chat.completions.list\n\nputs(page)" + } + } + }, + "description": "List stored Chat Completions. Only Chat Completions that have been stored\nwith the `store` parameter set to `true` will be returned.\n" + }, + "post": { + "operationId": "createChatCompletion", + "tags": [ + "Chat" + ], + "summary": "Create chat completion", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateChatCompletionRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateChatCompletionResponse" + } + }, + "text/event-stream": { + "schema": { + "$ref": "#/components/schemas/CreateChatCompletionStreamResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create chat completion", + "group": "chat", + "returns": "Returns a [chat completion](https://platform.openai.com/docs/api-reference/chat/object) object, or a streamed sequence of [chat completion chunk](https://platform.openai.com/docs/api-reference/chat/streaming) objects if the request is streamed.\n", + "path": "create", + "examples": [ + { + "title": "Default", + "request": { + "curl": "curl https://api.openai.com/v1/chat/completions \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"VAR_chat_model_id\",\n \"messages\": [\n {\n \"role\": \"developer\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Hello!\"\n }\n ]\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nchat_completion = client.chat.completions.create(\n messages=[{\n \"content\": \"string\",\n \"role\": \"developer\",\n }],\n model=\"gpt-4o\",\n)\nprint(chat_completion)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst chatCompletion = await client.chat.completions.create({\n messages: [{ content: 'string', role: 'developer' }],\n model: 'gpt-4o',\n});\n\nconsole.log(chatCompletion);", + "csharp": "using System;\nusing System.Collections.Generic;\n\nusing OpenAI.Chat;\n\nChatClient client = new(\n model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nList messages =\n[\n new SystemChatMessage(\"You are a helpful assistant.\"),\n new UserChatMessage(\"Hello!\")\n];\n\nChatCompletion completion = client.CompleteChat(messages);\n\nConsole.WriteLine(completion.Content[0].Text);\n", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{\n Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{\n OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{\n Content: openai.ChatCompletionDeveloperMessageParamContentUnion{\n OfString: openai.String(\"string\"),\n },\n },\n }},\n Model: shared.ChatModelGPT5,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", chatCompletion)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.ChatModel;\nimport com.openai.models.chat.completions.ChatCompletion;\nimport com.openai.models.chat.completions.ChatCompletionCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()\n .addDeveloperMessage(\"string\")\n .model(ChatModel.GPT_5)\n .build();\n ChatCompletion chatCompletion = client.chat().completions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nchat_completion = openai.chat.completions.create(messages: [{content: \"string\", role: :developer}], model: :\"gpt-5\")\n\nputs(chat_completion)" + }, + "response": "{\n \"id\": \"chatcmpl-B9MBs8CjcvOU2jLn4n570S5qMJKcT\",\n \"object\": \"chat.completion\",\n \"created\": 1741569952,\n \"model\": \"gpt-4.1-2025-04-14\",\n \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\": \"assistant\",\n \"content\": \"Hello! How can I assist you today?\",\n \"refusal\": null,\n \"annotations\": []\n },\n \"logprobs\": null,\n \"finish_reason\": \"stop\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 19,\n \"completion_tokens\": 10,\n \"total_tokens\": 29,\n \"prompt_tokens_details\": {\n \"cached_tokens\": 0,\n \"audio_tokens\": 0\n },\n \"completion_tokens_details\": {\n \"reasoning_tokens\": 0,\n \"audio_tokens\": 0,\n \"accepted_prediction_tokens\": 0,\n \"rejected_prediction_tokens\": 0\n }\n },\n \"service_tier\": \"default\"\n}\n" + }, + { + "title": "Image input", + "request": { + "curl": "curl https://api.openai.com/v1/chat/completions \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"gpt-4.1\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": \"What is in this image?\"\n },\n {\n \"type\": \"image_url\",\n \"image_url\": {\n \"url\": \"https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg\"\n }\n }\n ]\n }\n ],\n \"max_tokens\": 300\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nchat_completion = client.chat.completions.create(\n messages=[{\n \"content\": \"string\",\n \"role\": \"developer\",\n }],\n model=\"gpt-4o\",\n)\nprint(chat_completion)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst chatCompletion = await client.chat.completions.create({\n messages: [{ content: 'string', role: 'developer' }],\n model: 'gpt-4o',\n});\n\nconsole.log(chatCompletion);", + "csharp": "using System;\nusing System.Collections.Generic;\n\nusing OpenAI.Chat;\n\nChatClient client = new(\n model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nList messages =\n[\n new UserChatMessage(\n [\n ChatMessageContentPart.CreateTextPart(\"What's in this image?\"),\n ChatMessageContentPart.CreateImagePart(new Uri(\"https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg\"))\n ])\n];\n\nChatCompletion completion = client.CompleteChat(messages);\n\nConsole.WriteLine(completion.Content[0].Text);\n", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{\n Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{\n OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{\n Content: openai.ChatCompletionDeveloperMessageParamContentUnion{\n OfString: openai.String(\"string\"),\n },\n },\n }},\n Model: shared.ChatModelGPT5,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", chatCompletion)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.ChatModel;\nimport com.openai.models.chat.completions.ChatCompletion;\nimport com.openai.models.chat.completions.ChatCompletionCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()\n .addDeveloperMessage(\"string\")\n .model(ChatModel.GPT_5)\n .build();\n ChatCompletion chatCompletion = client.chat().completions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nchat_completion = openai.chat.completions.create(messages: [{content: \"string\", role: :developer}], model: :\"gpt-5\")\n\nputs(chat_completion)" + }, + "response": "{\n \"id\": \"chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG\",\n \"object\": \"chat.completion\",\n \"created\": 1741570283,\n \"model\": \"gpt-4.1-2025-04-14\",\n \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\": \"assistant\",\n \"content\": \"The image shows a wooden boardwalk path running through a lush green field or meadow. The sky is bright blue with some scattered clouds, giving the scene a serene and peaceful atmosphere. Trees and shrubs are visible in the background.\",\n \"refusal\": null,\n \"annotations\": []\n },\n \"logprobs\": null,\n \"finish_reason\": \"stop\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 1117,\n \"completion_tokens\": 46,\n \"total_tokens\": 1163,\n \"prompt_tokens_details\": {\n \"cached_tokens\": 0,\n \"audio_tokens\": 0\n },\n \"completion_tokens_details\": {\n \"reasoning_tokens\": 0,\n \"audio_tokens\": 0,\n \"accepted_prediction_tokens\": 0,\n \"rejected_prediction_tokens\": 0\n }\n },\n \"service_tier\": \"default\"\n}\n" + }, + { + "title": "Streaming", + "request": { + "curl": "curl https://api.openai.com/v1/chat/completions \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"VAR_chat_model_id\",\n \"messages\": [\n {\n \"role\": \"developer\",\n \"content\": \"You are a helpful assistant.\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Hello!\"\n }\n ],\n \"stream\": true\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nchat_completion = client.chat.completions.create(\n messages=[{\n \"content\": \"string\",\n \"role\": \"developer\",\n }],\n model=\"gpt-4o\",\n)\nprint(chat_completion)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst chatCompletion = await client.chat.completions.create({\n messages: [{ content: 'string', role: 'developer' }],\n model: 'gpt-4o',\n});\n\nconsole.log(chatCompletion);", + "csharp": "using System;\nusing System.ClientModel;\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\n\nusing OpenAI.Chat;\n\nChatClient client = new( model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nList messages =\n[ new SystemChatMessage(\"You are a helpful assistant.\"),\n new UserChatMessage(\"Hello!\")\n];\n\nAsyncCollectionResult completionUpdates = client.CompleteChatStreamingAsync(messages);\n\nawait foreach (StreamingChatCompletionUpdate completionUpdate in completionUpdates)\n{ if (completionUpdate.ContentUpdate.Count > 0)\n {\n Console.Write(completionUpdate.ContentUpdate[0].Text);\n }\n}\n", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{\n Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{\n OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{\n Content: openai.ChatCompletionDeveloperMessageParamContentUnion{\n OfString: openai.String(\"string\"),\n },\n },\n }},\n Model: shared.ChatModelGPT5,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", chatCompletion)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.ChatModel;\nimport com.openai.models.chat.completions.ChatCompletion;\nimport com.openai.models.chat.completions.ChatCompletionCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()\n .addDeveloperMessage(\"string\")\n .model(ChatModel.GPT_5)\n .build();\n ChatCompletion chatCompletion = client.chat().completions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nchat_completion = openai.chat.completions.create(messages: [{content: \"string\", role: :developer}], model: :\"gpt-5\")\n\nputs(chat_completion)" + }, + "response": "{\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1694268190,\"model\":\"gpt-4o-mini\", \"system_fingerprint\": \"fp_44709d6fcb\", \"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"\"},\"logprobs\":null,\"finish_reason\":null}]}\n\n{\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1694268190,\"model\":\"gpt-4o-mini\", \"system_fingerprint\": \"fp_44709d6fcb\", \"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"},\"logprobs\":null,\"finish_reason\":null}]}\n\n....\n\n{\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1694268190,\"model\":\"gpt-4o-mini\", \"system_fingerprint\": \"fp_44709d6fcb\", \"choices\":[{\"index\":0,\"delta\":{},\"logprobs\":null,\"finish_reason\":\"stop\"}]}\n" + }, + { + "title": "Functions", + "request": { + "curl": "curl https://api.openai.com/v1/chat/completions \\\n-H \"Content-Type: application/json\" \\\n-H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n-d '{\n \"model\": \"gpt-4.1\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"What is the weather like in Boston today?\"\n }\n ],\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_current_weather\",\n \"description\": \"Get the current weather in a given location\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and state, e.g. San Francisco, CA\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\"celsius\", \"fahrenheit\"]\n }\n },\n \"required\": [\"location\"]\n }\n }\n }\n ],\n \"tool_choice\": \"auto\"\n}'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nchat_completion = client.chat.completions.create(\n messages=[{\n \"content\": \"string\",\n \"role\": \"developer\",\n }],\n model=\"gpt-4o\",\n)\nprint(chat_completion)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst chatCompletion = await client.chat.completions.create({\n messages: [{ content: 'string', role: 'developer' }],\n model: 'gpt-4o',\n});\n\nconsole.log(chatCompletion);", + "csharp": "using System;\nusing System.Collections.Generic;\n\nusing OpenAI.Chat;\n\nChatClient client = new(\n model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(\n functionName: \"get_current_weather\",\n functionDescription: \"Get the current weather in a given location\",\n functionParameters: BinaryData.FromString(\"\"\"\n {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and state, e.g. San Francisco, CA\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [ \"celsius\", \"fahrenheit\" ]\n }\n },\n \"required\": [ \"location\" ]\n }\n \"\"\")\n);\n\nList messages =\n[\n new UserChatMessage(\"What's the weather like in Boston today?\"),\n];\n\nChatCompletionOptions options = new()\n{\n Tools =\n {\n getCurrentWeatherTool\n },\n ToolChoice = ChatToolChoice.CreateAutoChoice(),\n};\n\nChatCompletion completion = client.CompleteChat(messages, options);\n", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{\n Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{\n OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{\n Content: openai.ChatCompletionDeveloperMessageParamContentUnion{\n OfString: openai.String(\"string\"),\n },\n },\n }},\n Model: shared.ChatModelGPT5,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", chatCompletion)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.ChatModel;\nimport com.openai.models.chat.completions.ChatCompletion;\nimport com.openai.models.chat.completions.ChatCompletionCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()\n .addDeveloperMessage(\"string\")\n .model(ChatModel.GPT_5)\n .build();\n ChatCompletion chatCompletion = client.chat().completions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nchat_completion = openai.chat.completions.create(messages: [{content: \"string\", role: :developer}], model: :\"gpt-5\")\n\nputs(chat_completion)" + }, + "response": "{\n \"id\": \"chatcmpl-abc123\",\n \"object\": \"chat.completion\",\n \"created\": 1699896916,\n \"model\": \"gpt-4o-mini\",\n \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\": \"assistant\",\n \"content\": null,\n \"tool_calls\": [\n {\n \"id\": \"call_abc123\",\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_current_weather\",\n \"arguments\": \"{\\n\\\"location\\\": \\\"Boston, MA\\\"\\n}\"\n }\n }\n ]\n },\n \"logprobs\": null,\n \"finish_reason\": \"tool_calls\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 82,\n \"completion_tokens\": 17,\n \"total_tokens\": 99,\n \"completion_tokens_details\": {\n \"reasoning_tokens\": 0,\n \"accepted_prediction_tokens\": 0,\n \"rejected_prediction_tokens\": 0\n }\n }\n}\n" + }, + { + "title": "Logprobs", + "request": { + "curl": "curl https://api.openai.com/v1/chat/completions \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"VAR_chat_model_id\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Hello!\"\n }\n ],\n \"logprobs\": true,\n \"top_logprobs\": 2\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nchat_completion = client.chat.completions.create(\n messages=[{\n \"content\": \"string\",\n \"role\": \"developer\",\n }],\n model=\"gpt-4o\",\n)\nprint(chat_completion)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst chatCompletion = await client.chat.completions.create({\n messages: [{ content: 'string', role: 'developer' }],\n model: 'gpt-4o',\n});\n\nconsole.log(chatCompletion);", + "csharp": "using System;\nusing System.Collections.Generic;\n\nusing OpenAI.Chat;\n\nChatClient client = new(\n model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nList messages =\n[\n new UserChatMessage(\"Hello!\")\n];\n\nChatCompletionOptions options = new()\n{\n IncludeLogProbabilities = true,\n TopLogProbabilityCount = 2\n};\n\nChatCompletion completion = client.CompleteChat(messages, options);\n\nConsole.WriteLine(completion.Content[0].Text);\n", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{\n Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{\n OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{\n Content: openai.ChatCompletionDeveloperMessageParamContentUnion{\n OfString: openai.String(\"string\"),\n },\n },\n }},\n Model: shared.ChatModelGPT5,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", chatCompletion)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.ChatModel;\nimport com.openai.models.chat.completions.ChatCompletion;\nimport com.openai.models.chat.completions.ChatCompletionCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()\n .addDeveloperMessage(\"string\")\n .model(ChatModel.GPT_5)\n .build();\n ChatCompletion chatCompletion = client.chat().completions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nchat_completion = openai.chat.completions.create(messages: [{content: \"string\", role: :developer}], model: :\"gpt-5\")\n\nputs(chat_completion)" + }, + "response": "{\n \"id\": \"chatcmpl-123\",\n \"object\": \"chat.completion\",\n \"created\": 1702685778,\n \"model\": \"gpt-4o-mini\",\n \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\": \"assistant\",\n \"content\": \"Hello! How can I assist you today?\"\n },\n \"logprobs\": {\n \"content\": [\n {\n \"token\": \"Hello\",\n \"logprob\": -0.31725305,\n \"bytes\": [72, 101, 108, 108, 111],\n \"top_logprobs\": [\n {\n \"token\": \"Hello\",\n \"logprob\": -0.31725305,\n \"bytes\": [72, 101, 108, 108, 111]\n },\n {\n \"token\": \"Hi\",\n \"logprob\": -1.3190403,\n \"bytes\": [72, 105]\n }\n ]\n },\n {\n \"token\": \"!\",\n \"logprob\": -0.02380986,\n \"bytes\": [\n 33\n ],\n \"top_logprobs\": [\n {\n \"token\": \"!\",\n \"logprob\": -0.02380986,\n \"bytes\": [33]\n },\n {\n \"token\": \" there\",\n \"logprob\": -3.787621,\n \"bytes\": [32, 116, 104, 101, 114, 101]\n }\n ]\n },\n {\n \"token\": \" How\",\n \"logprob\": -0.000054669687,\n \"bytes\": [32, 72, 111, 119],\n \"top_logprobs\": [\n {\n \"token\": \" How\",\n \"logprob\": -0.000054669687,\n \"bytes\": [32, 72, 111, 119]\n },\n {\n \"token\": \"<|end|>\",\n \"logprob\": -10.953937,\n \"bytes\": null\n }\n ]\n },\n {\n \"token\": \" can\",\n \"logprob\": -0.015801601,\n \"bytes\": [32, 99, 97, 110],\n \"top_logprobs\": [\n {\n \"token\": \" can\",\n \"logprob\": -0.015801601,\n \"bytes\": [32, 99, 97, 110]\n },\n {\n \"token\": \" may\",\n \"logprob\": -4.161023,\n \"bytes\": [32, 109, 97, 121]\n }\n ]\n },\n {\n \"token\": \" I\",\n \"logprob\": -3.7697225e-6,\n \"bytes\": [\n 32,\n 73\n ],\n \"top_logprobs\": [\n {\n \"token\": \" I\",\n \"logprob\": -3.7697225e-6,\n \"bytes\": [32, 73]\n },\n {\n \"token\": \" assist\",\n \"logprob\": -13.596657,\n \"bytes\": [32, 97, 115, 115, 105, 115, 116]\n }\n ]\n },\n {\n \"token\": \" assist\",\n \"logprob\": -0.04571125,\n \"bytes\": [32, 97, 115, 115, 105, 115, 116],\n \"top_logprobs\": [\n {\n \"token\": \" assist\",\n \"logprob\": -0.04571125,\n \"bytes\": [32, 97, 115, 115, 105, 115, 116]\n },\n {\n \"token\": \" help\",\n \"logprob\": -3.1089056,\n \"bytes\": [32, 104, 101, 108, 112]\n }\n ]\n },\n {\n \"token\": \" you\",\n \"logprob\": -5.4385737e-6,\n \"bytes\": [32, 121, 111, 117],\n \"top_logprobs\": [\n {\n \"token\": \" you\",\n \"logprob\": -5.4385737e-6,\n \"bytes\": [32, 121, 111, 117]\n },\n {\n \"token\": \" today\",\n \"logprob\": -12.807695,\n \"bytes\": [32, 116, 111, 100, 97, 121]\n }\n ]\n },\n {\n \"token\": \" today\",\n \"logprob\": -0.0040071653,\n \"bytes\": [32, 116, 111, 100, 97, 121],\n \"top_logprobs\": [\n {\n \"token\": \" today\",\n \"logprob\": -0.0040071653,\n \"bytes\": [32, 116, 111, 100, 97, 121]\n },\n {\n \"token\": \"?\",\n \"logprob\": -5.5247097,\n \"bytes\": [63]\n }\n ]\n },\n {\n \"token\": \"?\",\n \"logprob\": -0.0008108172,\n \"bytes\": [63],\n \"top_logprobs\": [\n {\n \"token\": \"?\",\n \"logprob\": -0.0008108172,\n \"bytes\": [63]\n },\n {\n \"token\": \"?\\n\",\n \"logprob\": -7.184561,\n \"bytes\": [63, 10]\n }\n ]\n }\n ]\n },\n \"finish_reason\": \"stop\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 9,\n \"completion_tokens\": 9,\n \"total_tokens\": 18,\n \"completion_tokens_details\": {\n \"reasoning_tokens\": 0,\n \"accepted_prediction_tokens\": 0,\n \"rejected_prediction_tokens\": 0\n }\n },\n \"system_fingerprint\": null\n}\n" + } + ] + }, + "description": "**Starting a new project?** We recommend trying [Responses](https://platform.openai.com/docs/api-reference/responses)\nto take advantage of the latest OpenAI platform features. Compare\n[Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses).\n\n---\n\nCreates a model response for the given chat conversation. Learn more in the\n[text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision),\nand [audio](https://platform.openai.com/docs/guides/audio) guides.\n\nParameter support can differ depending on the model used to generate the\nresponse, particularly for newer reasoning models. Parameters that are only\nsupported for reasoning models are noted below. For the current state of\nunsupported parameters in reasoning models,\n[refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning).\n" + } + }, + "/chat/completions/{completion_id}": { + "get": { + "operationId": "getChatCompletion", + "tags": [ + "Chat" + ], + "summary": "Get chat completion", + "parameters": [ + { + "in": "path", + "name": "completion_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the chat completion to retrieve." + } + ], + "responses": { + "200": { + "description": "A chat completion", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateChatCompletionResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Get chat completion", + "group": "chat", + "returns": "The [ChatCompletion](https://platform.openai.com/docs/api-reference/chat/object) object matching the specified ID.", + "examples": { + "response": "{\n \"object\": \"chat.completion\",\n \"id\": \"chatcmpl-abc123\",\n \"model\": \"gpt-4o-2024-08-06\",\n \"created\": 1738960610,\n \"request_id\": \"req_ded8ab984ec4bf840f37566c1011c417\",\n \"tool_choice\": null,\n \"usage\": {\n \"total_tokens\": 31,\n \"completion_tokens\": 18,\n \"prompt_tokens\": 13\n },\n \"seed\": 4944116822809979520,\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"presence_penalty\": 0.0,\n \"frequency_penalty\": 0.0,\n \"system_fingerprint\": \"fp_50cad350e4\",\n \"input_user\": null,\n \"service_tier\": \"default\",\n \"tools\": null,\n \"metadata\": {},\n \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"content\": \"Mind of circuits hum, \\nLearning patterns in silence— \\nFuture's quiet spark.\",\n \"role\": \"assistant\",\n \"tool_calls\": null,\n \"function_call\": null\n },\n \"finish_reason\": \"stop\",\n \"logprobs\": null\n }\n ],\n \"response_format\": null\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/chat/completions/chatcmpl-abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nchat_completion = client.chat.completions.retrieve(\n \"completion_id\",\n)\nprint(chat_completion.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst chatCompletion = await client.chat.completions.retrieve('completion_id');\n\nconsole.log(chatCompletion.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n chatCompletion, err := client.Chat.Completions.Get(context.TODO(), \"completion_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", chatCompletion.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.chat.completions.ChatCompletion;\nimport com.openai.models.chat.completions.ChatCompletionRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ChatCompletion chatCompletion = client.chat().completions().retrieve(\"completion_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nchat_completion = openai.chat.completions.retrieve(\"completion_id\")\n\nputs(chat_completion)" + } + } + }, + "description": "Get a stored chat completion. Only Chat Completions that have been created\nwith the `store` parameter set to `true` will be returned.\n" + }, + "post": { + "operationId": "updateChatCompletion", + "tags": [ + "Chat" + ], + "summary": "Update chat completion", + "parameters": [ + { + "in": "path", + "name": "completion_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the chat completion to update." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "metadata" + ], + "properties": { + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "A chat completion", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateChatCompletionResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Update chat completion", + "group": "chat", + "returns": "The [ChatCompletion](https://platform.openai.com/docs/api-reference/chat/object) object matching the specified ID.", + "examples": { + "response": "{\n \"object\": \"chat.completion\",\n \"id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2\",\n \"model\": \"gpt-4o-2024-08-06\",\n \"created\": 1738960610,\n \"request_id\": \"req_ded8ab984ec4bf840f37566c1011c417\",\n \"tool_choice\": null,\n \"usage\": {\n \"total_tokens\": 31,\n \"completion_tokens\": 18,\n \"prompt_tokens\": 13\n },\n \"seed\": 4944116822809979520,\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"presence_penalty\": 0.0,\n \"frequency_penalty\": 0.0,\n \"system_fingerprint\": \"fp_50cad350e4\",\n \"input_user\": null,\n \"service_tier\": \"default\",\n \"tools\": null,\n \"metadata\": {\n \"foo\": \"bar\"\n },\n \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"content\": \"Mind of circuits hum, \\nLearning patterns in silence— \\nFuture's quiet spark.\",\n \"role\": \"assistant\",\n \"tool_calls\": null,\n \"function_call\": null\n },\n \"finish_reason\": \"stop\",\n \"logprobs\": null\n }\n ],\n \"response_format\": null\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/chat/completions/chat_abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"metadata\": {\"foo\": \"bar\"}}'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nchat_completion = client.chat.completions.update(\n completion_id=\"completion_id\",\n metadata={\n \"foo\": \"string\"\n },\n)\nprint(chat_completion.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst chatCompletion = await client.chat.completions.update('completion_id', { metadata: { foo: 'string' } });\n\nconsole.log(chatCompletion.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n chatCompletion, err := client.Chat.Completions.Update(\n context.TODO(),\n \"completion_id\",\n openai.ChatCompletionUpdateParams{\n Metadata: shared.Metadata{\n \"foo\": \"string\",\n },\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", chatCompletion.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.core.JsonValue;\nimport com.openai.models.chat.completions.ChatCompletion;\nimport com.openai.models.chat.completions.ChatCompletionUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ChatCompletionUpdateParams params = ChatCompletionUpdateParams.builder()\n .completionId(\"completion_id\")\n .metadata(ChatCompletionUpdateParams.Metadata.builder()\n .putAdditionalProperty(\"foo\", JsonValue.from(\"string\"))\n .build())\n .build();\n ChatCompletion chatCompletion = client.chat().completions().update(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nchat_completion = openai.chat.completions.update(\"completion_id\", metadata: {foo: \"string\"})\n\nputs(chat_completion)" + } + } + }, + "description": "Modify a stored chat completion. Only Chat Completions that have been\ncreated with the `store` parameter set to `true` can be modified. Currently,\nthe only supported modification is to update the `metadata` field.\n" + }, + "delete": { + "operationId": "deleteChatCompletion", + "tags": [ + "Chat" + ], + "summary": "Delete chat completion", + "parameters": [ + { + "in": "path", + "name": "completion_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the chat completion to delete." + } + ], + "responses": { + "200": { + "description": "The chat completion was deleted successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatCompletionDeleted" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete chat completion", + "group": "chat", + "returns": "A deletion confirmation object.", + "examples": { + "response": "{\n \"object\": \"chat.completion.deleted\",\n \"id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/chat/completions/chat_abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nchat_completion_deleted = client.chat.completions.delete(\n \"completion_id\",\n)\nprint(chat_completion_deleted.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst chatCompletionDeleted = await client.chat.completions.delete('completion_id');\n\nconsole.log(chatCompletionDeleted.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n chatCompletionDeleted, err := client.Chat.Completions.Delete(context.TODO(), \"completion_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", chatCompletionDeleted.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.chat.completions.ChatCompletionDeleteParams;\nimport com.openai.models.chat.completions.ChatCompletionDeleted;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ChatCompletionDeleted chatCompletionDeleted = client.chat().completions().delete(\"completion_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nchat_completion_deleted = openai.chat.completions.delete(\"completion_id\")\n\nputs(chat_completion_deleted)" + } + } + }, + "description": "Delete a stored chat completion. Only Chat Completions that have been\ncreated with the `store` parameter set to `true` can be deleted.\n" + } + }, + "/chat/completions/{completion_id}/messages": { + "get": { + "operationId": "getChatCompletionMessages", + "tags": [ + "Chat" + ], + "summary": "Get chat messages", + "parameters": [ + { + "in": "path", + "name": "completion_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the chat completion to retrieve messages from." + }, + { + "name": "after", + "in": "query", + "description": "Identifier for the last message from the previous pagination request.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of messages to retrieve.", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order for messages by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "asc", + "desc" + ], + "default": "asc" + } + } + ], + "responses": { + "200": { + "description": "A list of messages", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatCompletionMessageList" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Get chat messages", + "group": "chat", + "returns": "A list of [messages](https://platform.openai.com/docs/api-reference/chat/message-list) for the specified chat completion.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0\",\n \"role\": \"user\",\n \"content\": \"write a haiku about ai\",\n \"name\": null,\n \"content_parts\": null\n }\n ],\n \"first_id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0\",\n \"last_id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/chat/completions/chat_abc123/messages \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.chat.completions.messages.list(\n completion_id=\"completion_id\",\n)\npage = page.data[0]\nprint(page)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const chatCompletionStoreMessage of client.chat.completions.messages.list('completion_id')) { console.log(chatCompletionStoreMessage);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Chat.Completions.Messages.List(\n context.TODO(),\n \"completion_id\",\n openai.ChatCompletionMessageListParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.chat.completions.messages.MessageListPage;\nimport com.openai.models.chat.completions.messages.MessageListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n MessageListPage page = client.chat().completions().messages().list(\"completion_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.chat.completions.messages.list(\"completion_id\")\n\nputs(page)" + } + } + }, + "description": "Get the messages in a stored chat completion. Only Chat Completions that\nhave been created with the `store` parameter set to `true` will be\nreturned.\n" + } + }, + "/completions": { + "post": { + "operationId": "createCompletion", + "tags": [ + "Completions" + ], + "summary": "Create completion", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateCompletionRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateCompletionResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create completion", + "group": "completions", + "returns": "Returns a [completion](https://platform.openai.com/docs/api-reference/completions/object) object, or a sequence of completion objects if the request is streamed.\n", + "legacy": true, + "examples": [ + { + "title": "No streaming", + "request": { + "curl": "curl https://api.openai.com/v1/completions \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"VAR_completion_model_id\",\n \"prompt\": \"Say this is a test\",\n \"max_tokens\": 7,\n \"temperature\": 0\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ncompletion = client.completions.create(\n model=\"string\",\n prompt=\"This is a test.\",\n)\nprint(completion)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst completion = await client.completions.create({ model: 'string', prompt: 'This is a test.' });\n\nconsole.log(completion);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n completion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{\n Model: openai.CompletionNewParamsModelGPT3_5TurboInstruct,\n Prompt: openai.CompletionNewParamsPromptUnion{\n OfString: openai.String(\"This is a test.\"),\n },\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", completion)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.completions.Completion;\nimport com.openai.models.completions.CompletionCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n CompletionCreateParams params = CompletionCreateParams.builder()\n .model(CompletionCreateParams.Model.GPT_3_5_TURBO_INSTRUCT)\n .prompt(\"This is a test.\")\n .build();\n Completion completion = client.completions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ncompletion = openai.completions.create(model: :\"gpt-3.5-turbo-instruct\", prompt: \"This is a test.\")\n\nputs(completion)" + }, + "response": "{\n \"id\": \"cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7\",\n \"object\": \"text_completion\",\n \"created\": 1589478378,\n \"model\": \"VAR_completion_model_id\",\n \"system_fingerprint\": \"fp_44709d6fcb\",\n \"choices\": [\n {\n \"text\": \"\\n\\nThis is indeed a test\",\n \"index\": 0,\n \"logprobs\": null,\n \"finish_reason\": \"length\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 5,\n \"completion_tokens\": 7,\n \"total_tokens\": 12\n }\n}\n" + }, + { + "title": "Streaming", + "request": { + "curl": "curl https://api.openai.com/v1/completions \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"VAR_completion_model_id\",\n \"prompt\": \"Say this is a test\",\n \"max_tokens\": 7,\n \"temperature\": 0,\n \"stream\": true\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ncompletion = client.completions.create(\n model=\"string\",\n prompt=\"This is a test.\",\n)\nprint(completion)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst completion = await client.completions.create({ model: 'string', prompt: 'This is a test.' });\n\nconsole.log(completion);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n completion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{\n Model: openai.CompletionNewParamsModelGPT3_5TurboInstruct,\n Prompt: openai.CompletionNewParamsPromptUnion{\n OfString: openai.String(\"This is a test.\"),\n },\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", completion)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.completions.Completion;\nimport com.openai.models.completions.CompletionCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n CompletionCreateParams params = CompletionCreateParams.builder()\n .model(CompletionCreateParams.Model.GPT_3_5_TURBO_INSTRUCT)\n .prompt(\"This is a test.\")\n .build();\n Completion completion = client.completions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ncompletion = openai.completions.create(model: :\"gpt-3.5-turbo-instruct\", prompt: \"This is a test.\")\n\nputs(completion)" + }, + "response": "{\n \"id\": \"cmpl-7iA7iJjj8V2zOkCGvWF2hAkDWBQZe\",\n \"object\": \"text_completion\",\n \"created\": 1690759702,\n \"choices\": [\n {\n \"text\": \"This\",\n \"index\": 0,\n \"logprobs\": null,\n \"finish_reason\": null\n }\n ],\n \"model\": \"gpt-3.5-turbo-instruct\"\n \"system_fingerprint\": \"fp_44709d6fcb\",\n}\n" + } + ] + }, + "description": "Creates a completion for the provided prompt and parameters." + } + }, + "/containers": { + "get": { + "summary": "List containers", + "description": "List Containers", + "operationId": "ListContainers", + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContainerListResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List containers", + "group": "containers", + "returns": "a list of [container](https://platform.openai.com/docs/api-reference/containers/object) objects.", + "path": "get", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863\",\n \"object\": \"container\",\n \"created_at\": 1747844794,\n \"status\": \"running\",\n \"expires_after\": {\n \"anchor\": \"last_active_at\",\n \"minutes\": 20\n },\n \"last_active_at\": 1747844794,\n \"name\": \"My Container\"\n }\n ],\n \"first_id\": \"container_123\",\n \"last_id\": \"container_123\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/containers \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const containerListResponse of client.containers.list()) {\n console.log(containerListResponse.id);\n}", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.containers.list()\npage = page.data[0]\nprint(page.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Containers.List(context.TODO(), openai.ContainerListParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.containers.ContainerListPage;\nimport com.openai.models.containers.ContainerListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ContainerListPage page = client.containers().list();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.containers.list\n\nputs(page)" + } + } + } + }, + "post": { + "summary": "Create container", + "description": "Create Container", + "operationId": "CreateContainer", + "parameters": [], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateContainerBody" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContainerResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create container", + "group": "containers", + "returns": "The created [container](https://platform.openai.com/docs/api-reference/containers/object) object.", + "path": "post", + "examples": { + "response": "{\n \"id\": \"cntr_682e30645a488191b6363a0cbefc0f0a025ec61b66250591\",\n \"object\": \"container\",\n \"created_at\": 1747857508,\n \"status\": \"running\",\n \"expires_after\": {\n \"anchor\": \"last_active_at\",\n \"minutes\": 20\n },\n \"last_active_at\": 1747857508,\n \"name\": \"My Container\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/containers \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"My Container\"\n }'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst container = await client.containers.create({ name: 'name' });\n\nconsole.log(container.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ncontainer = client.containers.create(\n name=\"name\",\n)\nprint(container.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n container, err := client.Containers.New(context.TODO(), openai.ContainerNewParams{\n Name: \"name\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", container.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.containers.ContainerCreateParams;\nimport com.openai.models.containers.ContainerCreateResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ContainerCreateParams params = ContainerCreateParams.builder()\n .name(\"name\")\n .build();\n ContainerCreateResponse container = client.containers().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ncontainer = openai.containers.create(name: \"name\")\n\nputs(container)" + } + } + } + } + }, + "/containers/{container_id}": { + "get": { + "summary": "Retrieve container", + "description": "Retrieve Container", + "operationId": "RetrieveContainer", + "parameters": [ + { + "name": "container_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContainerResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve container", + "group": "containers", + "returns": "The [container](https://platform.openai.com/docs/api-reference/containers/object) object.", + "path": "get", + "examples": { + "response": "{\n \"id\": \"cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863\",\n \"object\": \"container\",\n \"created_at\": 1747844794,\n \"status\": \"running\",\n \"expires_after\": {\n \"anchor\": \"last_active_at\",\n \"minutes\": 20\n },\n \"last_active_at\": 1747844794,\n \"name\": \"My Container\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863 \\ -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst container = await client.containers.retrieve('container_id');\n\nconsole.log(container.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ncontainer = client.containers.retrieve(\n \"container_id\",\n)\nprint(container.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n container, err := client.Containers.Get(context.TODO(), \"container_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", container.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.containers.ContainerRetrieveParams;\nimport com.openai.models.containers.ContainerRetrieveResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ContainerRetrieveResponse container = client.containers().retrieve(\"container_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ncontainer = openai.containers.retrieve(\"container_id\")\n\nputs(container)" + } + } + } + }, + "delete": { + "operationId": "DeleteContainer", + "summary": "Delete a container", + "description": "Delete Container", + "parameters": [ + { + "name": "container_id", + "in": "path", + "description": "The ID of the container to delete.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "x-oaiMeta": { + "name": "Delete a container", + "group": "containers", + "returns": "Deletion Status", + "path": "delete", + "examples": { + "response": "{\n \"id\": \"cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863\",\n \"object\": \"container.deleted\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863 \\ -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nawait client.containers.delete('container_id');", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nclient.containers.delete(\n \"container_id\",\n)", + "go": "package main\n\nimport (\n \"context\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n err := client.Containers.Delete(context.TODO(), \"container_id\")\n if err != nil {\n panic(err.Error())\n }\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.containers.ContainerDeleteParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n client.containers().delete(\"container_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresult = openai.containers.delete(\"container_id\")\n\nputs(result)" + } + } + } + } + }, + "/containers/{container_id}/files": { + "post": { + "summary": "Create container file", + "description": "Create a Container File\n\nYou can send either a multipart/form-data request with the raw file content, or a JSON request with a file ID.\n", + "operationId": "CreateContainerFile", + "parameters": [ + { + "name": "container_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/CreateContainerFileBody" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContainerFileResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create container file", + "group": "containers", + "returns": "The created [container file](https://platform.openai.com/docs/api-reference/container-files/object) object.", + "path": "post", + "examples": { + "response": "{\n \"id\": \"cfile_682e0e8a43c88191a7978f477a09bdf5\",\n \"object\": \"container.file\",\n \"created_at\": 1747848842,\n \"bytes\": 880,\n \"container_id\": \"cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04\",\n \"path\": \"/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json\",\n \"source\": \"user\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/containers/cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04/files \\ -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -F file=\"@example.txt\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst file = await client.containers.files.create('container_id');\n\nconsole.log(file.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfile = client.containers.files.create(\n container_id=\"container_id\",\n)\nprint(file.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n file, err := client.Containers.Files.New(\n context.TODO(),\n \"container_id\",\n openai.ContainerFileNewParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", file.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.containers.files.FileCreateParams;\nimport com.openai.models.containers.files.FileCreateResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileCreateResponse file = client.containers().files().create(\"container_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfile = openai.containers.files.create(\"container_id\")\n\nputs(file)" + } + } + } + }, + "get": { + "summary": "List container files", + "description": "List Container files", + "operationId": "ListContainerFiles", + "parameters": [ + { + "name": "container_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContainerFileListResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List container files", + "group": "containers", + "returns": "a list of [container file](https://platform.openai.com/docs/api-reference/container-files/object) objects.", + "path": "get", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"cfile_682e0e8a43c88191a7978f477a09bdf5\",\n \"object\": \"container.file\",\n \"created_at\": 1747848842,\n \"bytes\": 880,\n \"container_id\": \"cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04\",\n \"path\": \"/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json\",\n \"source\": \"user\"\n }\n ],\n \"first_id\": \"cfile_682e0e8a43c88191a7978f477a09bdf5\",\n \"has_more\": false,\n \"last_id\": \"cfile_682e0e8a43c88191a7978f477a09bdf5\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/containers/cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04/files \\ -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const fileListResponse of client.containers.files.list('container_id')) {\n console.log(fileListResponse.id);\n}", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.containers.files.list(\n container_id=\"container_id\",\n)\npage = page.data[0]\nprint(page.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Containers.Files.List(\n context.TODO(),\n \"container_id\",\n openai.ContainerFileListParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.containers.files.FileListPage;\nimport com.openai.models.containers.files.FileListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileListPage page = client.containers().files().list(\"container_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.containers.files.list(\"container_id\")\n\nputs(page)" + } + } + } + } + }, + "/containers/{container_id}/files/{file_id}": { + "get": { + "summary": "Retrieve container file", + "description": "Retrieve Container File", + "operationId": "RetrieveContainerFile", + "parameters": [ + { + "name": "container_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "file_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContainerFileResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve container file", + "group": "containers", + "returns": "The [container file](https://platform.openai.com/docs/api-reference/container-files/object) object.", + "path": "get", + "examples": { + "response": "{\n \"id\": \"cfile_682e0e8a43c88191a7978f477a09bdf5\",\n \"object\": \"container.file\",\n \"created_at\": 1747848842,\n \"bytes\": 880,\n \"container_id\": \"cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04\",\n \"path\": \"/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json\",\n \"source\": \"user\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/containers/container_123/files/file_456 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst file = await client.containers.files.retrieve('file_id', { container_id: 'container_id' });\n\nconsole.log(file.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfile = client.containers.files.retrieve(\n file_id=\"file_id\",\n container_id=\"container_id\",\n)\nprint(file.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n file, err := client.Containers.Files.Get(\n context.TODO(),\n \"container_id\",\n \"file_id\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", file.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.containers.files.FileRetrieveParams;\nimport com.openai.models.containers.files.FileRetrieveResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileRetrieveParams params = FileRetrieveParams.builder()\n .containerId(\"container_id\")\n .fileId(\"file_id\")\n .build();\n FileRetrieveResponse file = client.containers().files().retrieve(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfile = openai.containers.files.retrieve(\"file_id\", container_id: \"container_id\")\n\nputs(file)" + } + } + } + }, + "delete": { + "operationId": "DeleteContainerFile", + "summary": "Delete a container file", + "description": "Delete Container File", + "parameters": [ + { + "name": "container_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "file_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "x-oaiMeta": { + "name": "Delete a container file", + "group": "containers", + "returns": "Deletion Status", + "path": "delete", + "examples": { + "response": "{\n \"id\": \"cfile_682e0e8a43c88191a7978f477a09bdf5\",\n \"object\": \"container.file.deleted\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863/files/cfile_682e0e8a43c88191a7978f477a09bdf5 \\ -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nawait client.containers.files.delete('file_id', { container_id: 'container_id' });", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nclient.containers.files.delete(\n file_id=\"file_id\",\n container_id=\"container_id\",\n)", + "go": "package main\n\nimport (\n \"context\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n err := client.Containers.Files.Delete(\n context.TODO(),\n \"container_id\",\n \"file_id\",\n )\n if err != nil {\n panic(err.Error())\n }\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.containers.files.FileDeleteParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileDeleteParams params = FileDeleteParams.builder()\n .containerId(\"container_id\")\n .fileId(\"file_id\")\n .build();\n client.containers().files().delete(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresult = openai.containers.files.delete(\"file_id\", container_id: \"container_id\")\n\nputs(result)" + } + } + } + } + }, + "/containers/{container_id}/files/{file_id}/content": { + "get": { + "summary": "Retrieve container file content", + "description": "Retrieve Container File Content", + "operationId": "RetrieveContainerFileContent", + "parameters": [ + { + "name": "container_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "file_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Success" + } + }, + "x-oaiMeta": { + "name": "Retrieve container file content", + "group": "containers", + "returns": "The contents of the container file.", + "path": "get", + "examples": { + "response": "\n", + "request": { + "curl": "curl https://api.openai.com/v1/containers/container_123/files/cfile_456/content \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst content = await client.containers.files.content.retrieve('file_id', { container_id: 'container_id' });\n\nconsole.log(content);\n\nconst data = await content.blob();\nconsole.log(data);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ncontent = client.containers.files.content.retrieve(\n file_id=\"file_id\",\n container_id=\"container_id\",\n)\nprint(content)\ndata = content.read()\nprint(data)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n content, err := client.Containers.Files.Content.Get(\n context.TODO(),\n \"container_id\",\n \"file_id\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", content)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.core.http.HttpResponse;\nimport com.openai.models.containers.files.content.ContentRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ContentRetrieveParams params = ContentRetrieveParams.builder()\n .containerId(\"container_id\")\n .fileId(\"file_id\")\n .build();\n HttpResponse content = client.containers().files().content().retrieve(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ncontent = openai.containers.files.content.retrieve(\"file_id\", container_id: \"container_id\")\n\nputs(content)" + } + } + } + } + }, + "/conversations": { + "post": { + "operationId": "createConversation", + "tags": [ + "Conversations" + ], + "summary": "Create a conversation", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateConversationRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConversationResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create a conversation", + "group": "conversations", + "returns": "Returns a [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) object.\n", + "path": "create", + "examples": [ + { + "title": "Create a conversation.", + "request": { + "curl": "curl https://api.openai.com/v1/conversations \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"metadata\": {\"topic\": \"demo\"},\n \"items\": [\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": \"Hello!\"\n }\n ]\n }'\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst conversation = await client.conversations.create({\n metadata: { topic: \"demo\" },\n items: [\n { type: \"message\", role: \"user\", content: \"Hello!\" }\n ],\n});\nconsole.log(conversation);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nconversation = client.conversations.create()\nprint(conversation.id)", + "csharp": "using System;\nusing System.Collections.Generic;\nusing OpenAI.Conversations;\n\nOpenAIConversationClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nConversation conversation = client.CreateConversation(\n new CreateConversationOptions\n {\n Metadata = new Dictionary\n {\n { \"topic\", \"demo\" }\n },\n Items =\n {\n new ConversationMessageInput\n {\n Role = \"user\",\n Content = \"Hello!\"\n }\n }\n }\n);\nConsole.WriteLine(conversation.Id);\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst conversation = await client.conversations.create();\n\nconsole.log(conversation.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/conversations\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n conversation, err := client.Conversations.New(context.TODO(), conversations.ConversationNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", conversation.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.conversations.Conversation;\nimport com.openai.models.conversations.ConversationCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Conversation conversation = client.conversations().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nconversation = openai.conversations.create\n\nputs(conversation)" + }, + "response": "{\n \"id\": \"conv_123\",\n \"object\": \"conversation\",\n \"created_at\": 1741900000,\n \"metadata\": {\"topic\": \"demo\"}\n}\n" + } + ] + }, + "description": "Create a conversation." + } + }, + "/conversations/{conversation_id}": { + "get": { + "operationId": "getConversation", + "tags": [ + "Conversations" + ], + "summary": "Retrieve a conversation", + "parameters": [ + { + "in": "path", + "name": "conversation_id", + "required": true, + "schema": { + "type": "string", + "example": "conv_123" + }, + "description": "The ID of the conversation to retrieve." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConversationResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve a conversation", + "group": "conversations", + "returns": "Returns a [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) object.\n", + "path": "retrieve", + "examples": [ + { + "title": "Retrieve a conversation", + "request": { + "curl": "curl https://api.openai.com/v1/conversations/conv_123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst conversation = await client.conversations.retrieve(\"conv_123\");\nconsole.log(conversation);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nconversation = client.conversations.retrieve(\n \"conv_123\",\n)\nprint(conversation.id)", + "csharp": "using System;\nusing OpenAI.Conversations;\n\nOpenAIConversationClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nConversation conversation = client.GetConversation(\"conv_123\");\nConsole.WriteLine(conversation.Id);\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst conversation = await client.conversations.retrieve('conv_123');\n\nconsole.log(conversation.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n conversation, err := client.Conversations.Get(context.TODO(), \"conv_123\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", conversation.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.conversations.Conversation;\nimport com.openai.models.conversations.ConversationRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Conversation conversation = client.conversations().retrieve(\"conv_123\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nconversation = openai.conversations.retrieve(\"conv_123\")\n\nputs(conversation)" + }, + "response": "{\n \"id\": \"conv_123\",\n \"object\": \"conversation\",\n \"created_at\": 1741900000,\n \"metadata\": {\"topic\": \"demo\"}\n}\n" + } + ] + }, + "description": "Get a conversation with the given ID." + }, + "post": { + "operationId": "updateConversation", + "tags": [ + "Conversations" + ], + "summary": "Update a conversation", + "parameters": [ + { + "in": "path", + "name": "conversation_id", + "required": true, + "schema": { + "type": "string", + "example": "conv_123" + }, + "description": "The ID of the conversation to update." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateConversationBody" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConversationResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Update a conversation", + "group": "conversations", + "returns": "Returns the updated [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) object.\n", + "path": "update", + "examples": [ + { + "title": "Update conversation metadata", + "request": { + "curl": "curl https://api.openai.com/v1/conversations/conv_123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"metadata\": {\"topic\": \"project-x\"}\n }'\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst updated = await client.conversations.update(\n \"conv_123\",\n { metadata: { topic: \"project-x\" } }\n);\nconsole.log(updated);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nconversation = client.conversations.update(\n conversation_id=\"conv_123\",\n metadata={\n \"foo\": \"string\"\n },\n)\nprint(conversation.id)", + "csharp": "using System;\nusing System.Collections.Generic;\nusing OpenAI.Conversations;\n\nOpenAIConversationClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nConversation updated = client.UpdateConversation(\n conversationId: \"conv_123\",\n new UpdateConversationOptions\n {\n Metadata = new Dictionary\n {\n { \"topic\", \"project-x\" }\n }\n }\n);\nConsole.WriteLine(updated.Id);\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst conversation = await client.conversations.update('conv_123', { metadata: { foo: 'string' } });\n\nconsole.log(conversation.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/conversations\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n conversation, err := client.Conversations.Update(\n context.TODO(),\n \"conv_123\",\n conversations.ConversationUpdateParams{\n Metadata: map[string]string{\n \"foo\": \"string\",\n },\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", conversation.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.core.JsonValue;\nimport com.openai.models.conversations.Conversation;\nimport com.openai.models.conversations.ConversationUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ConversationUpdateParams params = ConversationUpdateParams.builder()\n .conversationId(\"conv_123\")\n .metadata(ConversationUpdateParams.Metadata.builder()\n .putAdditionalProperty(\"foo\", JsonValue.from(\"string\"))\n .build())\n .build();\n Conversation conversation = client.conversations().update(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nconversation = openai.conversations.update(\"conv_123\", metadata: {foo: \"string\"})\n\nputs(conversation)" + }, + "response": "{\n \"id\": \"conv_123\",\n \"object\": \"conversation\",\n \"created_at\": 1741900000,\n \"metadata\": {\"topic\": \"project-x\"}\n}\n" + } + ] + }, + "description": "Update a conversation's metadata with the given ID." + }, + "delete": { + "operationId": "deleteConversation", + "tags": [ + "Conversations" + ], + "summary": "Delete a conversation", + "parameters": [ + { + "in": "path", + "name": "conversation_id", + "required": true, + "schema": { + "type": "string", + "example": "conv_123" + }, + "description": "The ID of the conversation to delete." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletedConversationResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete a conversation", + "group": "conversations", + "returns": "A success message.\n", + "path": "delete", + "examples": [ + { + "title": "Delete a conversation", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/conversations/conv_123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst deleted = await client.conversations.delete(\"conv_123\");\nconsole.log(deleted);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nconversation_deleted_resource = client.conversations.delete(\n \"conv_123\",\n)\nprint(conversation_deleted_resource.id)", + "csharp": "using System;\nusing OpenAI.Conversations;\n\nOpenAIConversationClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nDeletedConversation deleted = client.DeleteConversation(\"conv_123\");\nConsole.WriteLine(deleted.Id);\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst conversationDeletedResource = await client.conversations.delete('conv_123');\n\nconsole.log(conversationDeletedResource.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n conversationDeletedResource, err := client.Conversations.Delete(context.TODO(), \"conv_123\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", conversationDeletedResource.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.conversations.ConversationDeleteParams;\nimport com.openai.models.conversations.ConversationDeletedResource;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ConversationDeletedResource conversationDeletedResource = client.conversations().delete(\"conv_123\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nconversation_deleted_resource = openai.conversations.delete(\"conv_123\")\n\nputs(conversation_deleted_resource)" + }, + "response": "{\n \"id\": \"conv_123\",\n \"object\": \"conversation.deleted\",\n \"deleted\": true\n}\n" + } + ] + }, + "description": "Delete a conversation with the given ID." + } + }, + "/conversations/{conversation_id}/items": { + "post": { + "operationId": "createConversationItems", + "tags": [ + "Conversations" + ], + "summary": "Create items", + "parameters": [ + { + "in": "path", + "name": "conversation_id", + "required": true, + "schema": { + "type": "string", + "example": "conv_123" + }, + "description": "The ID of the conversation to add the item to." + }, + { + "name": "include", + "in": "query", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Includable" + } + }, + "description": "Additional fields to include in the response. See the `include`\nparameter for [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include) for more information.\n" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "properties": { + "items": { + "type": "array", + "description": "The items to add to the conversation. You may add up to 20 items at a time.\n", + "items": { + "$ref": "#/components/schemas/InputItem" + }, + "maxItems": 20 + } + }, + "required": [ + "items" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConversationItemList" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create items", + "group": "conversations", + "returns": "Returns the list of added [items](https://platform.openai.com/docs/api-reference/conversations/list-items-object).\n", + "path": "create-item", + "examples": [ + { + "title": "Add a user message to a conversation", + "request": { + "curl": "curl https://api.openai.com/v1/conversations/conv_123/items \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"items\": [\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": [\n {\"type\": \"input_text\", \"text\": \"Hello!\"}\n ]\n },\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": [\n {\"type\": \"input_text\", \"text\": \"How are you?\"}\n ]\n }\n ]\n }'\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst items = await client.conversations.items.create(\n \"conv_123\",\n {\n items: [\n {\n type: \"message\",\n role: \"user\",\n content: [{ type: \"input_text\", text: \"Hello!\" }],\n },\n {\n type: \"message\",\n role: \"user\",\n content: [{ type: \"input_text\", text: \"How are you?\" }],\n },\n ],\n }\n);\nconsole.log(items.data);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nconversation_item_list = client.conversations.items.create(\n conversation_id=\"conv_123\",\n items=[{\n \"content\": \"string\",\n \"role\": \"user\",\n }],\n)\nprint(conversation_item_list.first_id)", + "csharp": "using System;\nusing System.Collections.Generic;\nusing OpenAI.Conversations;\n\nOpenAIConversationClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nConversationItemList created = client.ConversationItems.Create(\n conversationId: \"conv_123\",\n new CreateConversationItemsOptions\n {\n Items = new List\n {\n new ConversationMessage\n {\n Role = \"user\",\n Content =\n {\n new ConversationInputText { Text = \"Hello!\" }\n }\n },\n new ConversationMessage\n {\n Role = \"user\",\n Content =\n {\n new ConversationInputText { Text = \"How are you?\" }\n }\n }\n }\n }\n);\nConsole.WriteLine(created.Data.Count);\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst conversationItemList = await client.conversations.items.create('conv_123', {\n items: [{ content: 'string', role: 'user' }],\n});\n\nconsole.log(conversationItemList.first_id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/conversations\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n conversationItemList, err := client.Conversations.Items.New(\n context.TODO(),\n \"conv_123\",\n conversations.ItemNewParams{\n Items: []responses.ResponseInputItemUnionParam{responses.ResponseInputItemUnionParam{\n OfMessage: &responses.EasyInputMessageParam{\n Content: responses.EasyInputMessageContentUnionParam{\n OfString: openai.String(\"string\"),\n },\n Role: responses.EasyInputMessageRoleUser,\n },\n }},\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", conversationItemList.FirstID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.conversations.items.ConversationItemList;\nimport com.openai.models.conversations.items.ItemCreateParams;\nimport com.openai.models.responses.EasyInputMessage;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ItemCreateParams params = ItemCreateParams.builder()\n .conversationId(\"conv_123\")\n .addItem(EasyInputMessage.builder()\n .content(\"string\")\n .role(EasyInputMessage.Role.USER)\n .build())\n .build();\n ConversationItemList conversationItemList = client.conversations().items().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nconversation_item_list = openai.conversations.items.create(\"conv_123\", items: [{content: \"string\", role: :user}])\n\nputs(conversation_item_list)" + }, + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"type\": \"message\",\n \"id\": \"msg_abc\",\n \"status\": \"completed\",\n \"role\": \"user\",\n \"content\": [\n {\"type\": \"input_text\", \"text\": \"Hello!\"}\n ]\n },\n {\n \"type\": \"message\",\n \"id\": \"msg_def\",\n \"status\": \"completed\",\n \"role\": \"user\",\n \"content\": [\n {\"type\": \"input_text\", \"text\": \"How are you?\"}\n ]\n }\n ],\n \"first_id\": \"msg_abc\",\n \"last_id\": \"msg_def\",\n \"has_more\": false\n}\n" + } + ] + }, + "description": "Create items in a conversation with the given ID." + }, + "get": { + "operationId": "listConversationItems", + "tags": [ + "Conversations" + ], + "summary": "List items", + "parameters": [ + { + "in": "path", + "name": "conversation_id", + "required": true, + "schema": { + "type": "string", + "example": "conv_123" + }, + "description": "The ID of the conversation to list items for." + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between\n1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "in": "query", + "name": "order", + "schema": { + "type": "string", + "enum": [ + "asc", + "desc" + ] + }, + "description": "The order to return the input items in. Default is `desc`.\n- `asc`: Return the input items in ascending order.\n- `desc`: Return the input items in descending order.\n" + }, + { + "in": "query", + "name": "after", + "schema": { + "type": "string" + }, + "description": "An item ID to list items after, used in pagination.\n" + }, + { + "name": "include", + "in": "query", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Includable" + } + }, + "description": "Specify additional output data to include in the model response. Currently\nsupported values are:\n- `web_search_call.action.sources`: Include the sources of the web search tool call.\n- `code_interpreter_call.outputs`: Includes the outputs of python code execution\n in code interpreter tool call items.\n- `computer_call_output.output.image_url`: Include image urls from the computer call output.\n- `file_search_call.results`: Include the search results of\n the file search tool call.\n- `message.input_image.image_url`: Include image urls from the input message.\n- `message.output_text.logprobs`: Include logprobs with assistant messages.\n- `reasoning.encrypted_content`: Includes an encrypted version of reasoning\n tokens in reasoning item outputs. This enables reasoning items to be used in\n multi-turn conversations when using the Responses API statelessly (like\n when the `store` parameter is set to `false`, or when an organization is\n enrolled in the zero data retention program).\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConversationItemList" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List items", + "group": "conversations", + "returns": "Returns a [list object](https://platform.openai.com/docs/api-reference/conversations/list-items-object) containing Conversation items.\n", + "path": "list-items", + "examples": [ + { + "title": "List items in a conversation", + "request": { + "curl": "curl \"https://api.openai.com/v1/conversations/conv_123/items?limit=10\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst items = await client.conversations.items.list(\"conv_123\", { limit: 10 });\nconsole.log(items.data);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.conversations.items.list(\n conversation_id=\"conv_123\",\n)\npage = page.data[0]\nprint(page)", + "csharp": "using System;\nusing OpenAI.Conversations;\n\nOpenAIConversationClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nConversationItemList items = client.ConversationItems.List(\n conversationId: \"conv_123\",\n new ListConversationItemsOptions { Limit = 10 }\n);\nConsole.WriteLine(items.Data.Count);\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const conversationItem of client.conversations.items.list('conv_123')) {\n console.log(conversationItem);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/conversations\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Conversations.Items.List(\n context.TODO(),\n \"conv_123\",\n conversations.ItemListParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.conversations.items.ItemListPage;\nimport com.openai.models.conversations.items.ItemListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ItemListPage page = client.conversations().items().list(\"conv_123\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.conversations.items.list(\"conv_123\")\n\nputs(page)" + }, + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"type\": \"message\",\n \"id\": \"msg_abc\",\n \"status\": \"completed\",\n \"role\": \"user\",\n \"content\": [\n {\"type\": \"input_text\", \"text\": \"Hello!\"}\n ]\n }\n ],\n \"first_id\": \"msg_abc\",\n \"last_id\": \"msg_abc\",\n \"has_more\": false\n}\n" + } + ] + }, + "description": "List all items for a conversation with the given ID." + } + }, + "/conversations/{conversation_id}/items/{item_id}": { + "get": { + "operationId": "getConversationItem", + "tags": [ + "Conversations" + ], + "summary": "Retrieve an item", + "parameters": [ + { + "in": "path", + "name": "conversation_id", + "required": true, + "schema": { + "type": "string", + "example": "conv_123" + }, + "description": "The ID of the conversation that contains the item." + }, + { + "in": "path", + "name": "item_id", + "required": true, + "schema": { + "type": "string", + "example": "msg_abc" + }, + "description": "The ID of the item to retrieve." + }, + { + "name": "include", + "in": "query", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Includable" + } + }, + "description": "Additional fields to include in the response. See the `include`\nparameter for [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include) for more information.\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConversationItem" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve an item", + "group": "conversations", + "returns": "Returns a [Conversation Item](https://platform.openai.com/docs/api-reference/conversations/item-object).\n", + "path": "get-item", + "examples": [ + { + "title": "Retrieve an item", + "request": { + "curl": "curl https://api.openai.com/v1/conversations/conv_123/items/msg_abc \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst item = await client.conversations.items.retrieve(\n \"conv_123\",\n \"msg_abc\"\n);\nconsole.log(item);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nconversation_item = client.conversations.items.retrieve(\n item_id=\"msg_abc\",\n conversation_id=\"conv_123\",\n)\nprint(conversation_item)", + "csharp": "using System;\nusing OpenAI.Conversations;\n\nOpenAIConversationClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nConversationItem item = client.ConversationItems.Get(\n conversationId: \"conv_123\",\n itemId: \"msg_abc\"\n);\nConsole.WriteLine(item.Id);\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst conversationItem = await client.conversations.items.retrieve('msg_abc', {\n conversation_id: 'conv_123',\n});\n\nconsole.log(conversationItem);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/conversations\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n conversationItem, err := client.Conversations.Items.Get(\n context.TODO(),\n \"conv_123\",\n \"msg_abc\",\n conversations.ItemGetParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", conversationItem)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.conversations.items.ConversationItem;\nimport com.openai.models.conversations.items.ItemRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ItemRetrieveParams params = ItemRetrieveParams.builder()\n .conversationId(\"conv_123\")\n .itemId(\"msg_abc\")\n .build();\n ConversationItem conversationItem = client.conversations().items().retrieve(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nconversation_item = openai.conversations.items.retrieve(\"msg_abc\", conversation_id: \"conv_123\")\n\nputs(conversation_item)" + }, + "response": "{\n \"type\": \"message\",\n \"id\": \"msg_abc\",\n \"status\": \"completed\",\n \"role\": \"user\",\n \"content\": [\n {\"type\": \"input_text\", \"text\": \"Hello!\"}\n ]\n}\n" + } + ] + }, + "description": "Get a single item from a conversation with the given IDs." + }, + "delete": { + "operationId": "deleteConversationItem", + "tags": [ + "Conversations" + ], + "summary": "Delete an item", + "parameters": [ + { + "in": "path", + "name": "conversation_id", + "required": true, + "schema": { + "type": "string", + "example": "conv_123" + }, + "description": "The ID of the conversation that contains the item." + }, + { + "in": "path", + "name": "item_id", + "required": true, + "schema": { + "type": "string", + "example": "msg_abc" + }, + "description": "The ID of the item to delete." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConversationResource" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete an item", + "group": "conversations", + "returns": "Returns the updated [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) object.\n", + "path": "delete-item", + "examples": [ + { + "title": "Delete an item", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/conversations/conv_123/items/msg_abc \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst conversation = await client.conversations.items.delete(\n \"conv_123\",\n \"msg_abc\"\n);\nconsole.log(conversation);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nconversation = client.conversations.items.delete(\n item_id=\"msg_abc\",\n conversation_id=\"conv_123\",\n)\nprint(conversation.id)", + "csharp": "using System;\nusing OpenAI.Conversations;\n\nOpenAIConversationClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nConversation conversation = client.ConversationItems.Delete(\n conversationId: \"conv_123\",\n itemId: \"msg_abc\"\n);\nConsole.WriteLine(conversation.Id);\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst conversation = await client.conversations.items.delete('msg_abc', { conversation_id: 'conv_123' });\n\nconsole.log(conversation.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n conversation, err := client.Conversations.Items.Delete(\n context.TODO(),\n \"conv_123\",\n \"msg_abc\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", conversation.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.conversations.Conversation;\nimport com.openai.models.conversations.items.ItemDeleteParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ItemDeleteParams params = ItemDeleteParams.builder()\n .conversationId(\"conv_123\")\n .itemId(\"msg_abc\")\n .build();\n Conversation conversation = client.conversations().items().delete(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nconversation = openai.conversations.items.delete(\"msg_abc\", conversation_id: \"conv_123\")\n\nputs(conversation)" + }, + "response": "{\n \"id\": \"conv_123\",\n \"object\": \"conversation\",\n \"created_at\": 1741900000,\n \"metadata\": {\"topic\": \"demo\"}\n}\n" + } + ] + }, + "description": "Delete an item from a conversation with the given IDs." + } + }, + "/embeddings": { + "post": { + "operationId": "createEmbedding", + "tags": [ + "Embeddings" + ], + "summary": "Create embeddings", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateEmbeddingRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateEmbeddingResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create embeddings", + "group": "embeddings", + "returns": "A list of [embedding](https://platform.openai.com/docs/api-reference/embeddings/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"embedding\",\n \"embedding\": [\n 0.0023064255,\n -0.009327292,\n .... (1536 floats total for ada-002)\n -0.0028842222,\n ],\n \"index\": 0\n }\n ],\n \"model\": \"text-embedding-ada-002\",\n \"usage\": {\n \"prompt_tokens\": 8,\n \"total_tokens\": 8\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/embeddings \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"input\": \"The food was delicious and the waiter...\",\n \"model\": \"text-embedding-ada-002\",\n \"encoding_format\": \"float\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\ncreate_embedding_response = client.embeddings.create(\n input=\"The quick brown fox jumped over the lazy dog\",\n model=\"text-embedding-3-small\",\n)\nprint(create_embedding_response.data)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst createEmbeddingResponse = await client.embeddings.create({\n input: 'The quick brown fox jumped over the lazy dog',\n model: 'text-embedding-3-small',\n});\n\nconsole.log(createEmbeddingResponse.data);", + "csharp": "using System;\n\nusing OpenAI.Embeddings;\n\nEmbeddingClient client = new( model: \"text-embedding-3-small\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nOpenAIEmbedding embedding = client.GenerateEmbedding(input: \"The quick brown fox jumped over the lazy dog\");\nReadOnlyMemory vector = embedding.ToFloats();\n\nfor (int i = 0; i < vector.Length; i++)\n{ Console.WriteLine($\" [{i,4}] = {vector.Span[i]}\");\n}\n", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n createEmbeddingResponse, err := client.Embeddings.New(context.TODO(), openai.EmbeddingNewParams{\n Input: openai.EmbeddingNewParamsInputUnion{\n OfString: openai.String(\"The quick brown fox jumped over the lazy dog\"),\n },\n Model: openai.EmbeddingModelTextEmbeddingAda002,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", createEmbeddingResponse.Data)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.embeddings.CreateEmbeddingResponse;\nimport com.openai.models.embeddings.EmbeddingCreateParams;\nimport com.openai.models.embeddings.EmbeddingModel;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n EmbeddingCreateParams params = EmbeddingCreateParams.builder()\n .input(\"The quick brown fox jumped over the lazy dog\")\n .model(EmbeddingModel.TEXT_EMBEDDING_ADA_002)\n .build();\n CreateEmbeddingResponse createEmbeddingResponse = client.embeddings().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\ncreate_embedding_response = openai.embeddings.create(\n input: \"The quick brown fox jumped over the lazy dog\",\n model: :\"text-embedding-ada-002\"\n)\n\nputs(create_embedding_response)" + } + } + }, + "description": "Creates an embedding vector representing the input text." + } + }, + "/evals": { + "get": { + "operationId": "listEvals", + "tags": [ + "Evals" + ], + "summary": "List evals", + "parameters": [ + { + "name": "after", + "in": "query", + "description": "Identifier for the last eval from the previous pagination request.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of evals to retrieve.", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order for evals by timestamp. Use `asc` for ascending order or `desc` for descending order.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "asc", + "desc" + ], + "default": "asc" + } + }, + { + "name": "order_by", + "in": "query", + "description": "Evals can be ordered by creation time or last updated time. Use\n`created_at` for creation time or `updated_at` for last updated time.\n", + "required": false, + "schema": { + "type": "string", + "enum": [ + "created_at", + "updated_at" + ], + "default": "created_at" + } + } + ], + "responses": { + "200": { + "description": "A list of evals", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvalList" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List evals", + "group": "evals", + "returns": "A list of [evals](https://platform.openai.com/docs/api-reference/evals/object) matching the specified filters.", + "path": "list", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"object\": \"eval\",\n \"data_source_config\": {\n \"type\": \"stored_completions\",\n \"metadata\": {\n \"usecase\": \"push_notifications_summarizer\"\n },\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"item\": {\n \"type\": \"object\"\n },\n \"sample\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"item\",\n \"sample\"\n ]\n }\n },\n \"testing_criteria\": [\n {\n \"name\": \"Push Notification Summary Grader\",\n \"id\": \"Push Notification Summary Grader-9b876f24-4762-4be9-aff4-db7a9b31c673\",\n \"type\": \"label_model\",\n \"model\": \"o3-mini\",\n \"input\": [\n {\n \"type\": \"message\",\n \"role\": \"developer\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"\\nLabel the following push notification summary as either correct or incorrect.\\nThe push notification and the summary will be provided below.\\nA good push notificiation summary is concise and snappy.\\nIf it is good, then label it as correct, if not, then incorrect.\\n\"\n }\n },\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"\\nPush notifications: {{item.input}}\\nSummary: {{sample.output_text}}\\n\"\n }\n }\n ],\n \"passing_labels\": [\n \"correct\"\n ],\n \"labels\": [\n \"correct\",\n \"incorrect\"\n ],\n \"sampling_params\": null\n }\n ],\n \"name\": \"Push Notification Summary Grader\",\n \"created_at\": 1739314509,\n \"metadata\": {\n \"description\": \"A stored completions eval for push notification summaries\"\n }\n }\n ],\n \"first_id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"last_id\": \"eval_67aa884cf6688190b58f657d4441c8b7\",\n \"has_more\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals?limit=1 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.evals.list()\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const evalListResponse of client.evals.list()) {\n console.log(evalListResponse.id);\n}", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.evals.EvalListPage;\nimport com.openai.models.evals.EvalListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n EvalListPage page = client.evals().list();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.evals.list\n\nputs(page)" + } + } + }, + "description": "List evaluations for a project.\n" + }, + "post": { + "operationId": "createEval", + "tags": [ + "Evals" + ], + "summary": "Create eval", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateEvalRequest" + } + } + } + }, + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Eval" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create eval", + "group": "evals", + "returns": "The created [Eval](https://platform.openai.com/docs/api-reference/evals/object) object.", + "path": "post", + "examples": { + "response": "{\n \"object\": \"eval\",\n \"id\": \"eval_67b7fa9a81a88190ab4aa417e397ea21\",\n \"data_source_config\": {\n \"type\": \"stored_completions\",\n \"metadata\": {\n \"usecase\": \"chatbot\"\n },\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"item\": {\n \"type\": \"object\"\n },\n \"sample\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"item\",\n \"sample\"\n ]\n },\n \"testing_criteria\": [\n {\n \"name\": \"Example label grader\",\n \"type\": \"label_model\",\n \"model\": \"o3-mini\",\n \"input\": [\n {\n \"type\": \"message\",\n \"role\": \"developer\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"Classify the sentiment of the following statement as one of positive, neutral, or negative\"\n }\n },\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"Statement: {{item.input}}\"\n }\n }\n ],\n \"passing_labels\": [\n \"positive\"\n ],\n \"labels\": [\n \"positive\",\n \"neutral\",\n \"negative\"\n ]\n }\n ],\n \"name\": \"Sentiment\",\n \"created_at\": 1740110490,\n \"metadata\": {\n \"description\": \"An eval for sentiment analysis\"\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"Sentiment\",\n \"data_source_config\": {\n \"type\": \"stored_completions\",\n \"metadata\": {\n \"usecase\": \"chatbot\"\n }\n },\n \"testing_criteria\": [\n {\n \"type\": \"label_model\",\n \"model\": \"o3-mini\",\n \"input\": [\n {\n \"role\": \"developer\",\n \"content\": \"Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Statement: {{item.input}}\"\n }\n ],\n \"passing_labels\": [\n \"positive\"\n ],\n \"labels\": [\n \"positive\",\n \"neutral\",\n \"negative\"\n ],\n \"name\": \"Example label grader\"\n }\n ]\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\neval = client.evals.create(\n data_source_config={\n \"item_schema\": {\n \"foo\": \"bar\"\n },\n \"type\": \"custom\",\n },\n testing_criteria=[{\n \"input\": [{\n \"content\": \"content\",\n \"role\": \"role\",\n }],\n \"labels\": [\"string\"],\n \"model\": \"model\",\n \"name\": \"name\",\n \"passing_labels\": [\"string\"],\n \"type\": \"label_model\",\n }],\n)\nprint(eval.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst _eval = await client.evals.create({\n data_source_config: { item_schema: { foo: 'bar' }, type: 'custom' },\n testing_criteria: [\n {\n input: [{ content: 'content', role: 'role' }],\n labels: ['string'],\n model: 'model',\n name: 'name',\n passing_labels: ['string'],\n type: 'label_model',\n },\n ],\n});\n\nconsole.log(_eval.id);", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.core.JsonValue;\nimport com.openai.models.evals.EvalCreateParams;\nimport com.openai.models.evals.EvalCreateResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n EvalCreateParams params = EvalCreateParams.builder()\n .customDataSourceConfig(EvalCreateParams.DataSourceConfig.Custom.ItemSchema.builder()\n .putAdditionalProperty(\"foo\", JsonValue.from(\"bar\"))\n .build())\n .addTestingCriterion(EvalCreateParams.TestingCriterion.LabelModel.builder()\n .addInput(EvalCreateParams.TestingCriterion.LabelModel.Input.SimpleInputMessage.builder()\n .content(\"content\")\n .role(\"role\")\n .build())\n .addLabel(\"string\")\n .model(\"model\")\n .name(\"name\")\n .addPassingLabel(\"string\")\n .build())\n .build();\n EvalCreateResponse eval = client.evals().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\neval_ = openai.evals.create(\n data_source_config: {item_schema: {foo: \"bar\"}, type: :custom},\n testing_criteria: [\n {\n input: [{content: \"content\", role: \"role\"}],\n labels: [\"string\"],\n model: \"model\",\n name: \"name\",\n passing_labels: [\"string\"],\n type: :label_model\n }\n ]\n)\n\nputs(eval_)" + } + } + }, + "description": "Create the structure of an evaluation that can be used to test a model's performance.\nAn evaluation is a set of testing criteria and the config for a data source, which dictates the schema of the data used in the evaluation. After creating an evaluation, you can run it on different models and model parameters. We support several types of graders and datasources.\nFor more information, see the [Evals guide](https://platform.openai.com/docs/guides/evals).\n" + } + }, + "/evals/{eval_id}": { + "get": { + "operationId": "getEval", + "tags": [ + "Evals" + ], + "summary": "Get an eval", + "parameters": [ + { + "name": "eval_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the evaluation to retrieve." + } + ], + "responses": { + "200": { + "description": "The evaluation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Eval" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Get an eval", + "group": "evals", + "returns": "The [Eval](https://platform.openai.com/docs/api-reference/evals/object) object matching the specified ID.", + "path": "get", + "examples": { + "response": "{\n \"object\": \"eval\",\n \"id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"data_source_config\": {\n \"type\": \"custom\",\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"item\": {\n \"type\": \"object\",\n \"properties\": {\n \"input\": {\n \"type\": \"string\"\n },\n \"ground_truth\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"input\",\n \"ground_truth\"\n ]\n }\n },\n \"required\": [\n \"item\"\n ]\n }\n },\n \"testing_criteria\": [\n {\n \"name\": \"String check\",\n \"id\": \"String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2\",\n \"type\": \"string_check\",\n \"input\": \"{{item.input}}\",\n \"reference\": \"{{item.ground_truth}}\",\n \"operation\": \"eq\"\n }\n ],\n \"name\": \"External Data Eval\",\n \"created_at\": 1739314509,\n \"metadata\": {},\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\neval = client.evals.retrieve(\n \"eval_id\",\n)\nprint(eval.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst _eval = await client.evals.retrieve('eval_id');\n\nconsole.log(_eval.id);", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.evals.EvalRetrieveParams;\nimport com.openai.models.evals.EvalRetrieveResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n EvalRetrieveResponse eval = client.evals().retrieve(\"eval_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\neval_ = openai.evals.retrieve(\"eval_id\")\n\nputs(eval_)" + } + } + }, + "description": "Get an evaluation by ID.\n" + }, + "post": { + "operationId": "updateEval", + "tags": [ + "Evals" + ], + "summary": "Update an eval", + "parameters": [ + { + "name": "eval_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the evaluation to update." + } + ], + "requestBody": { + "description": "Request to update an evaluation", + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Rename the evaluation." + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The updated evaluation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Eval" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Update an eval", + "group": "evals", + "returns": "The [Eval](https://platform.openai.com/docs/api-reference/evals/object) object matching the updated version.", + "path": "update", + "examples": { + "response": "{\n \"object\": \"eval\",\n \"id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"data_source_config\": {\n \"type\": \"custom\",\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"item\": {\n \"type\": \"object\",\n \"properties\": {\n \"input\": {\n \"type\": \"string\"\n },\n \"ground_truth\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"input\",\n \"ground_truth\"\n ]\n }\n },\n \"required\": [\n \"item\"\n ]\n }\n },\n \"testing_criteria\": [\n {\n \"name\": \"String check\",\n \"id\": \"String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2\",\n \"type\": \"string_check\",\n \"input\": \"{{item.input}}\",\n \"reference\": \"{{item.ground_truth}}\",\n \"operation\": \"eq\"\n }\n ],\n \"name\": \"Updated Eval\",\n \"created_at\": 1739314509,\n \"metadata\": {\"description\": \"Updated description\"},\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"name\": \"Updated Eval\", \"metadata\": {\"description\": \"Updated description\"}}'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\neval = client.evals.update(\n eval_id=\"eval_id\",\n)\nprint(eval.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst _eval = await client.evals.update('eval_id');\n\nconsole.log(_eval.id);", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.evals.EvalUpdateParams;\nimport com.openai.models.evals.EvalUpdateResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n EvalUpdateResponse eval = client.evals().update(\"eval_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\neval_ = openai.evals.update(\"eval_id\")\n\nputs(eval_)" + } + } + }, + "description": "Update certain properties of an evaluation.\n" + }, + "delete": { + "operationId": "deleteEval", + "tags": [ + "Evals" + ], + "summary": "Delete an eval", + "parameters": [ + { + "name": "eval_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the evaluation to delete." + } + ], + "responses": { + "200": { + "description": "Successfully deleted the evaluation.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "object": { + "type": "string", + "example": "eval.deleted" + }, + "deleted": { + "type": "boolean", + "example": true + }, + "eval_id": { + "type": "string", + "example": "eval_abc123" + } + }, + "required": [ + "object", + "deleted", + "eval_id" + ] + } + } + } + }, + "404": { + "description": "Evaluation not found.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete an eval", + "group": "evals", + "returns": "A deletion confirmation object.", + "examples": { + "response": "{\n \"object\": \"eval.deleted\",\n \"deleted\": true,\n \"eval_id\": \"eval_abc123\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals/eval_abc123 \\\n -X DELETE \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\neval = client.evals.delete(\n \"eval_id\",\n)\nprint(eval.eval_id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst _eval = await client.evals.delete('eval_id');\n\nconsole.log(_eval.eval_id);", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.evals.EvalDeleteParams;\nimport com.openai.models.evals.EvalDeleteResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n EvalDeleteResponse eval = client.evals().delete(\"eval_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\neval_ = openai.evals.delete(\"eval_id\")\n\nputs(eval_)" + } + } + }, + "description": "Delete an evaluation.\n" + } + }, + "/evals/{eval_id}/runs": { + "get": { + "operationId": "getEvalRuns", + "tags": [ + "Evals" + ], + "summary": "Get eval runs", + "parameters": [ + { + "name": "eval_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the evaluation to retrieve runs for." + }, + { + "name": "after", + "in": "query", + "description": "Identifier for the last run from the previous pagination request.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of runs to retrieve.", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "asc", + "desc" + ], + "default": "asc" + } + }, + { + "name": "status", + "in": "query", + "description": "Filter runs by status. One of `queued` | `in_progress` | `failed` | `completed` | `canceled`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "queued", + "in_progress", + "completed", + "canceled", + "failed" + ] + } + } + ], + "responses": { + "200": { + "description": "A list of runs for the evaluation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvalRunList" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Get eval runs", + "group": "evals", + "returns": "A list of [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) objects matching the specified ID.", + "path": "get-runs", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"eval.run\",\n \"id\": \"evalrun_67e0c7d31560819090d60c0780591042\",\n \"eval_id\": \"eval_67e0c726d560819083f19a957c4c640b\",\n \"report_url\": \"https://platform.openai.com/evaluations/eval_67e0c726d560819083f19a957c4c640b\",\n \"status\": \"completed\",\n \"model\": \"o3-mini\",\n \"name\": \"bulk_with_negative_examples_o3-mini\",\n \"created_at\": 1742784467,\n \"result_counts\": {\n \"total\": 1,\n \"errored\": 0,\n \"failed\": 0,\n \"passed\": 1\n },\n \"per_model_usage\": [\n {\n \"model_name\": \"o3-mini\",\n \"invocation_count\": 1,\n \"prompt_tokens\": 563,\n \"completion_tokens\": 874,\n \"total_tokens\": 1437,\n \"cached_tokens\": 0\n }\n ],\n \"per_testing_criteria_results\": [\n {\n \"testing_criteria\": \"Push Notification Summary Grader-1808cd0b-eeec-4e0b-a519-337e79f4f5d1\",\n \"passed\": 1,\n \"failed\": 0\n }\n ],\n \"data_source\": {\n \"type\": \"completions\",\n \"source\": {\n \"type\": \"file_content\",\n \"content\": [\n {\n \"item\": {\n \"notifications\": \"\\n- New message from Sarah: \\\"Can you call me later?\\\"\\n- Your package has been delivered!\\n- Flash sale: 20% off electronics for the next 2 hours!\\n\"\n }\n }\n ]\n },\n \"input_messages\": {\n \"type\": \"template\",\n \"template\": [\n {\n \"type\": \"message\",\n \"role\": \"developer\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"\\n\\n\\n\\nYou are a helpful assistant that takes in an array of push notifications and returns a collapsed summary of them.\\nThe push notification will be provided as follows:\\n\\n...notificationlist...\\n\\n\\nYou should return just the summary and nothing else.\\n\\n\\nYou should return a summary that is concise and snappy.\\n\\n\\nHere is an example of a good summary:\\n\\n- Traffic alert: Accident reported on Main Street.- Package out for delivery: Expected by 5 PM.- New friend suggestion: Connect with Emma.\\n\\n\\nTraffic alert, package expected by 5pm, suggestion for new friend (Emily).\\n\\n\\n\\nHere is an example of a bad summary:\\n\\n- Traffic alert: Accident reported on Main Street.- Package out for delivery: Expected by 5 PM.- New friend suggestion: Connect with Emma.\\n\\n\\nTraffic alert reported on main street. You have a package that will arrive by 5pm, Emily is a new friend suggested for you.\\n\\n\"\n }\n },\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"{{item.notifications}}\"\n }\n }\n ]\n },\n \"model\": \"o3-mini\",\n \"sampling_params\": null\n },\n \"error\": null,\n \"metadata\": {}\n }\n ],\n \"first_id\": \"evalrun_67e0c7d31560819090d60c0780591042\",\n \"last_id\": \"evalrun_67e0c7d31560819090d60c0780591042\",\n \"has_more\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals/egroup_67abd54d9b0081909a86353f6fb9317a/runs \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.evals.runs.list(\n eval_id=\"eval_id\",\n)\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const runListResponse of client.evals.runs.list('eval_id')) {\n console.log(runListResponse.id);\n}", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.evals.runs.RunListPage;\nimport com.openai.models.evals.runs.RunListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunListPage page = client.evals().runs().list(\"eval_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.evals.runs.list(\"eval_id\")\n\nputs(page)" + } + } + }, + "description": "Get a list of runs for an evaluation.\n" + }, + "post": { + "operationId": "createEvalRun", + "tags": [ + "Evals" + ], + "summary": "Create eval run", + "parameters": [ + { + "in": "path", + "name": "eval_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the evaluation to create a run for." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateEvalRunRequest" + } + } + } + }, + "responses": { + "201": { + "description": "Successfully created a run for the evaluation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvalRun" + } + } + } + }, + "400": { + "description": "Bad request (for example, missing eval object)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create eval run", + "group": "evals", + "returns": "The [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object matching the specified ID.", + "examples": { + "response": "{\n \"object\": \"eval.run\",\n \"id\": \"evalrun_67e57965b480819094274e3a32235e4c\",\n \"eval_id\": \"eval_67e579652b548190aaa83ada4b125f47\",\n \"report_url\": \"https://platform.openai.com/evaluations/eval_67e579652b548190aaa83ada4b125f47&run_id=evalrun_67e57965b480819094274e3a32235e4c\",\n \"status\": \"queued\",\n \"model\": \"gpt-4o-mini\",\n \"name\": \"gpt-4o-mini\",\n \"created_at\": 1743092069,\n \"result_counts\": {\n \"total\": 0,\n \"errored\": 0,\n \"failed\": 0,\n \"passed\": 0\n },\n \"per_model_usage\": null,\n \"per_testing_criteria_results\": null,\n \"data_source\": {\n \"type\": \"completions\",\n \"source\": {\n \"type\": \"file_content\",\n \"content\": [\n {\n \"item\": {\n \"input\": \"Tech Company Launches Advanced Artificial Intelligence Platform\",\n \"ground_truth\": \"Technology\"\n }\n }\n ]\n },\n \"input_messages\": {\n \"type\": \"template\",\n \"template\": [\n {\n \"type\": \"message\",\n \"role\": \"developer\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\\n\\n# Steps\\n\\n1. Analyze the content of the news headline to understand its primary focus.\\n2. Extract the subject matter, identifying any key indicators or keywords.\\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\\n4. Ensure only one category is selected per headline.\\n\\n# Output Format\\n\\nRespond with the chosen category as a single word. For instance: \\\"Technology\\\", \\\"Markets\\\", \\\"World\\\", \\\"Business\\\", or \\\"Sports\\\".\\n\\n# Examples\\n\\n**Input**: \\\"Apple Unveils New iPhone Model, Featuring Advanced AI Features\\\" \\n**Output**: \\\"Technology\\\"\\n\\n**Input**: \\\"Global Stocks Mixed as Investors Await Central Bank Decisions\\\" \\n**Output**: \\\"Markets\\\"\\n\\n**Input**: \\\"War in Ukraine: Latest Updates on Negotiation Status\\\" \\n**Output**: \\\"World\\\"\\n\\n**Input**: \\\"Microsoft in Talks to Acquire Gaming Company for $2 Billion\\\" \\n**Output**: \\\"Business\\\"\\n\\n**Input**: \\\"Manchester United Secures Win in Premier League Football Match\\\" \\n**Output**: \\\"Sports\\\" \\n\\n# Notes\\n\\n- If the headline appears to fit into more than one category, choose the most dominant theme.\\n- Keywords or phrases such as \\\"stocks\\\", \\\"company acquisition\\\", \\\"match\\\", or technological brands can be good indicators for classification.\\n\"\n }\n },\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"{{item.input}}\"\n }\n }\n ]\n },\n \"model\": \"gpt-4o-mini\",\n \"sampling_params\": {\n \"seed\": 42,\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_completions_tokens\": 2048\n }\n },\n \"error\": null,\n \"metadata\": {}\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals/eval_67e579652b548190aaa83ada4b125f47/runs \\\n -X POST \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"name\":\"gpt-4o-mini\",\"data_source\":{\"type\":\"completions\",\"input_messages\":{\"type\":\"template\",\"template\":[{\"role\":\"developer\",\"content\":\"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\\n\\n# Steps\\n\\n1. Analyze the content of the news headline to understand its primary focus.\\n2. Extract the subject matter, identifying any key indicators or keywords.\\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\\n4. Ensure only one category is selected per headline.\\n\\n# Output Format\\n\\nRespond with the chosen category as a single word. For instance: \\\"Technology\\\", \\\"Markets\\\", \\\"World\\\", \\\"Business\\\", or \\\"Sports\\\".\\n\\n# Examples\\n\\n**Input**: \\\"Apple Unveils New iPhone Model, Featuring Advanced AI Features\\\" \\n**Output**: \\\"Technology\\\"\\n\\n**Input**: \\\"Global Stocks Mixed as Investors Await Central Bank Decisions\\\" \\n**Output**: \\\"Markets\\\"\\n\\n**Input**: \\\"War in Ukraine: Latest Updates on Negotiation Status\\\" \\n**Output**: \\\"World\\\"\\n\\n**Input**: \\\"Microsoft in Talks to Acquire Gaming Company for $2 Billion\\\" \\n**Output**: \\\"Business\\\"\\n\\n**Input**: \\\"Manchester United Secures Win in Premier League Football Match\\\" \\n**Output**: \\\"Sports\\\" \\n\\n# Notes\\n\\n- If the headline appears to fit into more than one category, choose the most dominant theme.\\n- Keywords or phrases such as \\\"stocks\\\", \\\"company acquisition\\\", \\\"match\\\", or technological brands can be good indicators for classification.\\n\"} , {\"role\":\"user\",\"content\":\"{{item.input}}\"}]} ,\"sampling_params\":{\"temperature\":1,\"max_completions_tokens\":2048,\"top_p\":1,\"seed\":42},\"model\":\"gpt-4o-mini\",\"source\":{\"type\":\"file_content\",\"content\":[{\"item\":{\"input\":\"Tech Company Launches Advanced Artificial Intelligence Platform\",\"ground_truth\":\"Technology\"}}]}}'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.evals.runs.create(\n eval_id=\"eval_id\",\n data_source={\n \"source\": {\n \"content\": [{\n \"item\": {\n \"foo\": \"bar\"\n }\n }],\n \"type\": \"file_content\",\n },\n \"type\": \"jsonl\",\n },\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.evals.runs.create('eval_id', {\n data_source: { source: { content: [{ item: { foo: 'bar' } }], type: 'file_content' }, type: 'jsonl' },\n});\n\nconsole.log(run.id);", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.core.JsonValue;\nimport com.openai.models.evals.runs.CreateEvalJsonlRunDataSource;\nimport com.openai.models.evals.runs.RunCreateParams;\nimport com.openai.models.evals.runs.RunCreateResponse;\nimport java.util.List;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunCreateParams params = RunCreateParams.builder()\n .evalId(\"eval_id\")\n .dataSource(CreateEvalJsonlRunDataSource.builder()\n .fileContentSource(List.of(CreateEvalJsonlRunDataSource.Source.FileContent.Content.builder()\n .item(CreateEvalJsonlRunDataSource.Source.FileContent.Content.Item.builder()\n .putAdditionalProperty(\"foo\", JsonValue.from(\"bar\"))\n .build())\n .build()))\n .build())\n .build();\n RunCreateResponse run = client.evals().runs().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.evals.runs.create(\n \"eval_id\",\n data_source: {source: {content: [{item: {foo: \"bar\"}}], type: :file_content}, type: :jsonl}\n)\n\nputs(run)" + } + } + }, + "description": "Kicks off a new run for a given evaluation, specifying the data source, and what model configuration to use to test. The datasource will be validated against the schema specified in the config of the evaluation.\n" + } + }, + "/evals/{eval_id}/runs/{run_id}": { + "get": { + "operationId": "getEvalRun", + "tags": [ + "Evals" + ], + "summary": "Get an eval run", + "parameters": [ + { + "name": "eval_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the evaluation to retrieve runs for." + }, + { + "name": "run_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run to retrieve." + } + ], + "responses": { + "200": { + "description": "The evaluation run", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvalRun" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Get an eval run", + "group": "evals", + "returns": "The [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object matching the specified ID.", + "path": "get", + "examples": { + "response": "{\n \"object\": \"eval.run\",\n \"id\": \"evalrun_67abd54d60ec8190832b46859da808f7\",\n \"eval_id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"report_url\": \"https://platform.openai.com/evaluations/eval_67abd54d9b0081909a86353f6fb9317a?run_id=evalrun_67abd54d60ec8190832b46859da808f7\",\n \"status\": \"queued\",\n \"model\": \"gpt-4o-mini\",\n \"name\": \"gpt-4o-mini\",\n \"created_at\": 1743092069,\n \"result_counts\": {\n \"total\": 0,\n \"errored\": 0,\n \"failed\": 0,\n \"passed\": 0\n },\n \"per_model_usage\": null,\n \"per_testing_criteria_results\": null,\n \"data_source\": {\n \"type\": \"completions\",\n \"source\": {\n \"type\": \"file_content\",\n \"content\": [\n {\n \"item\": {\n \"input\": \"Tech Company Launches Advanced Artificial Intelligence Platform\",\n \"ground_truth\": \"Technology\"\n }\n },\n {\n \"item\": {\n \"input\": \"Central Bank Increases Interest Rates Amid Inflation Concerns\",\n \"ground_truth\": \"Markets\"\n }\n },\n {\n \"item\": {\n \"input\": \"International Summit Addresses Climate Change Strategies\",\n \"ground_truth\": \"World\"\n }\n },\n {\n \"item\": {\n \"input\": \"Major Retailer Reports Record-Breaking Holiday Sales\",\n \"ground_truth\": \"Business\"\n }\n },\n {\n \"item\": {\n \"input\": \"National Team Qualifies for World Championship Finals\",\n \"ground_truth\": \"Sports\"\n }\n },\n {\n \"item\": {\n \"input\": \"Stock Markets Rally After Positive Economic Data Released\",\n \"ground_truth\": \"Markets\"\n }\n },\n {\n \"item\": {\n \"input\": \"Global Manufacturer Announces Merger with Competitor\",\n \"ground_truth\": \"Business\"\n }\n },\n {\n \"item\": {\n \"input\": \"Breakthrough in Renewable Energy Technology Unveiled\",\n \"ground_truth\": \"Technology\"\n }\n },\n {\n \"item\": {\n \"input\": \"World Leaders Sign Historic Climate Agreement\",\n \"ground_truth\": \"World\"\n }\n },\n {\n \"item\": {\n \"input\": \"Professional Athlete Sets New Record in Championship Event\",\n \"ground_truth\": \"Sports\"\n }\n },\n {\n \"item\": {\n \"input\": \"Financial Institutions Adapt to New Regulatory Requirements\",\n \"ground_truth\": \"Business\"\n }\n },\n {\n \"item\": {\n \"input\": \"Tech Conference Showcases Advances in Artificial Intelligence\",\n \"ground_truth\": \"Technology\"\n }\n },\n {\n \"item\": {\n \"input\": \"Global Markets Respond to Oil Price Fluctuations\",\n \"ground_truth\": \"Markets\"\n }\n },\n {\n \"item\": {\n \"input\": \"International Cooperation Strengthened Through New Treaty\",\n \"ground_truth\": \"World\"\n }\n },\n {\n \"item\": {\n \"input\": \"Sports League Announces Revised Schedule for Upcoming Season\",\n \"ground_truth\": \"Sports\"\n }\n }\n ]\n },\n \"input_messages\": {\n \"type\": \"template\",\n \"template\": [\n {\n \"type\": \"message\",\n \"role\": \"developer\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\\n\\n# Steps\\n\\n1. Analyze the content of the news headline to understand its primary focus.\\n2. Extract the subject matter, identifying any key indicators or keywords.\\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\\n4. Ensure only one category is selected per headline.\\n\\n# Output Format\\n\\nRespond with the chosen category as a single word. For instance: \\\"Technology\\\", \\\"Markets\\\", \\\"World\\\", \\\"Business\\\", or \\\"Sports\\\".\\n\\n# Examples\\n\\n**Input**: \\\"Apple Unveils New iPhone Model, Featuring Advanced AI Features\\\" \\n**Output**: \\\"Technology\\\"\\n\\n**Input**: \\\"Global Stocks Mixed as Investors Await Central Bank Decisions\\\" \\n**Output**: \\\"Markets\\\"\\n\\n**Input**: \\\"War in Ukraine: Latest Updates on Negotiation Status\\\" \\n**Output**: \\\"World\\\"\\n\\n**Input**: \\\"Microsoft in Talks to Acquire Gaming Company for $2 Billion\\\" \\n**Output**: \\\"Business\\\"\\n\\n**Input**: \\\"Manchester United Secures Win in Premier League Football Match\\\" \\n**Output**: \\\"Sports\\\" \\n\\n# Notes\\n\\n- If the headline appears to fit into more than one category, choose the most dominant theme.\\n- Keywords or phrases such as \\\"stocks\\\", \\\"company acquisition\\\", \\\"match\\\", or technological brands can be good indicators for classification.\\n\"\n }\n },\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"{{item.input}}\"\n }\n }\n ]\n },\n \"model\": \"gpt-4o-mini\",\n \"sampling_params\": {\n \"seed\": 42,\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_completions_tokens\": 2048\n }\n },\n \"error\": null,\n \"metadata\": {}\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7 \\ -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.evals.runs.retrieve(\n run_id=\"run_id\",\n eval_id=\"eval_id\",\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.evals.runs.retrieve('run_id', { eval_id: 'eval_id' });\n\nconsole.log(run.id);", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.evals.runs.RunRetrieveParams;\nimport com.openai.models.evals.runs.RunRetrieveResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunRetrieveParams params = RunRetrieveParams.builder()\n .evalId(\"eval_id\")\n .runId(\"run_id\")\n .build();\n RunRetrieveResponse run = client.evals().runs().retrieve(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.evals.runs.retrieve(\"run_id\", eval_id: \"eval_id\")\n\nputs(run)" + } + } + }, + "description": "Get an evaluation run by ID.\n" + }, + "post": { + "operationId": "cancelEvalRun", + "tags": [ + "Evals" + ], + "summary": "Cancel eval run", + "parameters": [ + { + "name": "eval_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the evaluation whose run you want to cancel." + }, + { + "name": "run_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run to cancel." + } + ], + "responses": { + "200": { + "description": "The canceled eval run object", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvalRun" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Cancel eval run", + "group": "evals", + "returns": "The updated [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object reflecting that the run is canceled.", + "path": "post", + "examples": { + "response": "{\n \"object\": \"eval.run\",\n \"id\": \"evalrun_67abd54d60ec8190832b46859da808f7\",\n \"eval_id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"report_url\": \"https://platform.openai.com/evaluations/eval_67abd54d9b0081909a86353f6fb9317a?run_id=evalrun_67abd54d60ec8190832b46859da808f7\",\n \"status\": \"canceled\",\n \"model\": \"gpt-4o-mini\",\n \"name\": \"gpt-4o-mini\",\n \"created_at\": 1743092069,\n \"result_counts\": {\n \"total\": 0,\n \"errored\": 0,\n \"failed\": 0,\n \"passed\": 0\n },\n \"per_model_usage\": null,\n \"per_testing_criteria_results\": null,\n \"data_source\": {\n \"type\": \"completions\",\n \"source\": {\n \"type\": \"file_content\",\n \"content\": [\n {\n \"item\": {\n \"input\": \"Tech Company Launches Advanced Artificial Intelligence Platform\",\n \"ground_truth\": \"Technology\"\n }\n },\n {\n \"item\": {\n \"input\": \"Central Bank Increases Interest Rates Amid Inflation Concerns\",\n \"ground_truth\": \"Markets\"\n }\n },\n {\n \"item\": {\n \"input\": \"International Summit Addresses Climate Change Strategies\",\n \"ground_truth\": \"World\"\n }\n },\n {\n \"item\": {\n \"input\": \"Major Retailer Reports Record-Breaking Holiday Sales\",\n \"ground_truth\": \"Business\"\n }\n },\n {\n \"item\": {\n \"input\": \"National Team Qualifies for World Championship Finals\",\n \"ground_truth\": \"Sports\"\n }\n },\n {\n \"item\": {\n \"input\": \"Stock Markets Rally After Positive Economic Data Released\",\n \"ground_truth\": \"Markets\"\n }\n },\n {\n \"item\": {\n \"input\": \"Global Manufacturer Announces Merger with Competitor\",\n \"ground_truth\": \"Business\"\n }\n },\n {\n \"item\": {\n \"input\": \"Breakthrough in Renewable Energy Technology Unveiled\",\n \"ground_truth\": \"Technology\"\n }\n },\n {\n \"item\": {\n \"input\": \"World Leaders Sign Historic Climate Agreement\",\n \"ground_truth\": \"World\"\n }\n },\n {\n \"item\": {\n \"input\": \"Professional Athlete Sets New Record in Championship Event\",\n \"ground_truth\": \"Sports\"\n }\n },\n {\n \"item\": {\n \"input\": \"Financial Institutions Adapt to New Regulatory Requirements\",\n \"ground_truth\": \"Business\"\n }\n },\n {\n \"item\": {\n \"input\": \"Tech Conference Showcases Advances in Artificial Intelligence\",\n \"ground_truth\": \"Technology\"\n }\n },\n {\n \"item\": {\n \"input\": \"Global Markets Respond to Oil Price Fluctuations\",\n \"ground_truth\": \"Markets\"\n }\n },\n {\n \"item\": {\n \"input\": \"International Cooperation Strengthened Through New Treaty\",\n \"ground_truth\": \"World\"\n }\n },\n {\n \"item\": {\n \"input\": \"Sports League Announces Revised Schedule for Upcoming Season\",\n \"ground_truth\": \"Sports\"\n }\n }\n ]\n },\n \"input_messages\": {\n \"type\": \"template\",\n \"template\": [\n {\n \"type\": \"message\",\n \"role\": \"developer\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\\n\\n# Steps\\n\\n1. Analyze the content of the news headline to understand its primary focus.\\n2. Extract the subject matter, identifying any key indicators or keywords.\\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\\n4. Ensure only one category is selected per headline.\\n\\n# Output Format\\n\\nRespond with the chosen category as a single word. For instance: \\\"Technology\\\", \\\"Markets\\\", \\\"World\\\", \\\"Business\\\", or \\\"Sports\\\".\\n\\n# Examples\\n\\n**Input**: \\\"Apple Unveils New iPhone Model, Featuring Advanced AI Features\\\" \\n**Output**: \\\"Technology\\\"\\n\\n**Input**: \\\"Global Stocks Mixed as Investors Await Central Bank Decisions\\\" \\n**Output**: \\\"Markets\\\"\\n\\n**Input**: \\\"War in Ukraine: Latest Updates on Negotiation Status\\\" \\n**Output**: \\\"World\\\"\\n\\n**Input**: \\\"Microsoft in Talks to Acquire Gaming Company for $2 Billion\\\" \\n**Output**: \\\"Business\\\"\\n\\n**Input**: \\\"Manchester United Secures Win in Premier League Football Match\\\" \\n**Output**: \\\"Sports\\\" \\n\\n# Notes\\n\\n- If the headline appears to fit into more than one category, choose the most dominant theme.\\n- Keywords or phrases such as \\\"stocks\\\", \\\"company acquisition\\\", \\\"match\\\", or technological brands can be good indicators for classification.\\n\"\n }\n },\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"{{item.input}}\"\n }\n }\n ]\n },\n \"model\": \"gpt-4o-mini\",\n \"sampling_params\": {\n \"seed\": 42,\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_completions_tokens\": 2048\n }\n },\n \"error\": null,\n \"metadata\": {}\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7/cancel \\ -X POST \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.evals.runs.cancel(\n run_id=\"run_id\",\n eval_id=\"eval_id\",\n)\nprint(response.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.evals.runs.cancel('run_id', { eval_id: 'eval_id' });\n\nconsole.log(response.id);", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.evals.runs.RunCancelParams;\nimport com.openai.models.evals.runs.RunCancelResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunCancelParams params = RunCancelParams.builder()\n .evalId(\"eval_id\")\n .runId(\"run_id\")\n .build();\n RunCancelResponse response = client.evals().runs().cancel(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.evals.runs.cancel(\"run_id\", eval_id: \"eval_id\")\n\nputs(response)" + } + } + }, + "description": "Cancel an ongoing evaluation run.\n" + }, + "delete": { + "operationId": "deleteEvalRun", + "tags": [ + "Evals" + ], + "summary": "Delete eval run", + "parameters": [ + { + "name": "eval_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the evaluation to delete the run from." + }, + { + "name": "run_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run to delete." + } + ], + "responses": { + "200": { + "description": "Successfully deleted the eval run", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "object": { + "type": "string", + "example": "eval.run.deleted" + }, + "deleted": { + "type": "boolean", + "example": true + }, + "run_id": { + "type": "string", + "example": "evalrun_677469f564d48190807532a852da3afb" + } + } + } + } + } + }, + "404": { + "description": "Run not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete eval run", + "group": "evals", + "returns": "An object containing the status of the delete operation.", + "path": "delete", + "examples": { + "response": "{\n \"object\": \"eval.run.deleted\",\n \"deleted\": true,\n \"run_id\": \"evalrun_abc456\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals/eval_123abc/runs/evalrun_abc456 \\\n -X DELETE \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.evals.runs.delete(\n run_id=\"run_id\",\n eval_id=\"eval_id\",\n)\nprint(run.run_id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.evals.runs.delete('run_id', { eval_id: 'eval_id' });\n\nconsole.log(run.run_id);", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.evals.runs.RunDeleteParams;\nimport com.openai.models.evals.runs.RunDeleteResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunDeleteParams params = RunDeleteParams.builder()\n .evalId(\"eval_id\")\n .runId(\"run_id\")\n .build();\n RunDeleteResponse run = client.evals().runs().delete(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.evals.runs.delete(\"run_id\", eval_id: \"eval_id\")\n\nputs(run)" + } + } + }, + "description": "Delete an eval run.\n" + } + }, + "/evals/{eval_id}/runs/{run_id}/output_items": { + "get": { + "operationId": "getEvalRunOutputItems", + "tags": [ + "Evals" + ], + "summary": "Get eval run output items", + "parameters": [ + { + "name": "eval_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the evaluation to retrieve runs for." + }, + { + "name": "run_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run to retrieve output items for." + }, + { + "name": "after", + "in": "query", + "description": "Identifier for the last output item from the previous pagination request.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of output items to retrieve.", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "status", + "in": "query", + "description": "Filter output items by status. Use `failed` to filter by failed output\nitems or `pass` to filter by passed output items.\n", + "required": false, + "schema": { + "type": "string", + "enum": [ + "fail", + "pass" + ] + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order for output items by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "asc", + "desc" + ], + "default": "asc" + } + } + ], + "responses": { + "200": { + "description": "A list of output items for the evaluation run", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvalRunOutputItemList" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Get eval run output items", + "group": "evals", + "returns": "A list of [EvalRunOutputItem](https://platform.openai.com/docs/api-reference/evals/run-output-item-object) objects matching the specified ID.", + "path": "get", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"eval.run.output_item\",\n \"id\": \"outputitem_67e5796c28e081909917bf79f6e6214d\",\n \"created_at\": 1743092076,\n \"run_id\": \"evalrun_67abd54d60ec8190832b46859da808f7\",\n \"eval_id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"status\": \"pass\",\n \"datasource_item_id\": 5,\n \"datasource_item\": {\n \"input\": \"Stock Markets Rally After Positive Economic Data Released\",\n \"ground_truth\": \"Markets\"\n },\n \"results\": [\n {\n \"name\": \"String check-a2486074-d803-4445-b431-ad2262e85d47\",\n \"sample\": null,\n \"passed\": true,\n \"score\": 1.0\n }\n ],\n \"sample\": {\n \"input\": [\n {\n \"role\": \"developer\",\n \"content\": \"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\\n\\n# Steps\\n\\n1. Analyze the content of the news headline to understand its primary focus.\\n2. Extract the subject matter, identifying any key indicators or keywords.\\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\\n4. Ensure only one category is selected per headline.\\n\\n# Output Format\\n\\nRespond with the chosen category as a single word. For instance: \\\"Technology\\\", \\\"Markets\\\", \\\"World\\\", \\\"Business\\\", or \\\"Sports\\\".\\n\\n# Examples\\n\\n**Input**: \\\"Apple Unveils New iPhone Model, Featuring Advanced AI Features\\\" \\n**Output**: \\\"Technology\\\"\\n\\n**Input**: \\\"Global Stocks Mixed as Investors Await Central Bank Decisions\\\" \\n**Output**: \\\"Markets\\\"\\n\\n**Input**: \\\"War in Ukraine: Latest Updates on Negotiation Status\\\" \\n**Output**: \\\"World\\\"\\n\\n**Input**: \\\"Microsoft in Talks to Acquire Gaming Company for $2 Billion\\\" \\n**Output**: \\\"Business\\\"\\n\\n**Input**: \\\"Manchester United Secures Win in Premier League Football Match\\\" \\n**Output**: \\\"Sports\\\" \\n\\n# Notes\\n\\n- If the headline appears to fit into more than one category, choose the most dominant theme.\\n- Keywords or phrases such as \\\"stocks\\\", \\\"company acquisition\\\", \\\"match\\\", or technological brands can be good indicators for classification.\\n\",\n \"tool_call_id\": null,\n \"tool_calls\": null,\n \"function_call\": null\n },\n {\n \"role\": \"user\",\n \"content\": \"Stock Markets Rally After Positive Economic Data Released\",\n \"tool_call_id\": null,\n \"tool_calls\": null,\n \"function_call\": null\n }\n ],\n \"output\": [\n {\n \"role\": \"assistant\",\n \"content\": \"Markets\",\n \"tool_call_id\": null,\n \"tool_calls\": null,\n \"function_call\": null\n }\n ],\n \"finish_reason\": \"stop\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"usage\": {\n \"total_tokens\": 325,\n \"completion_tokens\": 2,\n \"prompt_tokens\": 323,\n \"cached_tokens\": 0\n },\n \"error\": null,\n \"temperature\": 1.0,\n \"max_completion_tokens\": 2048,\n \"top_p\": 1.0,\n \"seed\": 42\n }\n }\n ],\n \"first_id\": \"outputitem_67e5796c28e081909917bf79f6e6214d\",\n \"last_id\": \"outputitem_67e5796c28e081909917bf79f6e6214d\",\n \"has_more\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals/egroup_67abd54d9b0081909a86353f6fb9317a/runs/erun_67abd54d60ec8190832b46859da808f7/output_items \\ -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.evals.runs.output_items.list(\n run_id=\"run_id\",\n eval_id=\"eval_id\",\n)\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const outputItemListResponse of client.evals.runs.outputItems.list('run_id', {\n eval_id: 'eval_id',\n})) {\n console.log(outputItemListResponse.id);\n}", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.evals.runs.outputitems.OutputItemListPage;\nimport com.openai.models.evals.runs.outputitems.OutputItemListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n OutputItemListParams params = OutputItemListParams.builder()\n .evalId(\"eval_id\")\n .runId(\"run_id\")\n .build();\n OutputItemListPage page = client.evals().runs().outputItems().list(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.evals.runs.output_items.list(\"run_id\", eval_id: \"eval_id\")\n\nputs(page)" + } + } + }, + "description": "Get a list of output items for an evaluation run.\n" + } + }, + "/evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}": { + "get": { + "operationId": "getEvalRunOutputItem", + "tags": [ + "Evals" + ], + "summary": "Get an output item of an eval run", + "parameters": [ + { + "name": "eval_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the evaluation to retrieve runs for." + }, + { + "name": "run_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run to retrieve." + }, + { + "name": "output_item_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the output item to retrieve." + } + ], + "responses": { + "200": { + "description": "The evaluation run output item", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvalRunOutputItem" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Get an output item of an eval run", + "group": "evals", + "returns": "The [EvalRunOutputItem](https://platform.openai.com/docs/api-reference/evals/run-output-item-object) object matching the specified ID.", + "path": "get", + "examples": { + "response": "{\n \"object\": \"eval.run.output_item\",\n \"id\": \"outputitem_67e5796c28e081909917bf79f6e6214d\",\n \"created_at\": 1743092076,\n \"run_id\": \"evalrun_67abd54d60ec8190832b46859da808f7\",\n \"eval_id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"status\": \"pass\",\n \"datasource_item_id\": 5,\n \"datasource_item\": {\n \"input\": \"Stock Markets Rally After Positive Economic Data Released\",\n \"ground_truth\": \"Markets\"\n },\n \"results\": [\n {\n \"name\": \"String check-a2486074-d803-4445-b431-ad2262e85d47\",\n \"sample\": null,\n \"passed\": true,\n \"score\": 1.0\n }\n ],\n \"sample\": {\n \"input\": [\n {\n \"role\": \"developer\",\n \"content\": \"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\\n\\n# Steps\\n\\n1. Analyze the content of the news headline to understand its primary focus.\\n2. Extract the subject matter, identifying any key indicators or keywords.\\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\\n4. Ensure only one category is selected per headline.\\n\\n# Output Format\\n\\nRespond with the chosen category as a single word. For instance: \\\"Technology\\\", \\\"Markets\\\", \\\"World\\\", \\\"Business\\\", or \\\"Sports\\\".\\n\\n# Examples\\n\\n**Input**: \\\"Apple Unveils New iPhone Model, Featuring Advanced AI Features\\\" \\n**Output**: \\\"Technology\\\"\\n\\n**Input**: \\\"Global Stocks Mixed as Investors Await Central Bank Decisions\\\" \\n**Output**: \\\"Markets\\\"\\n\\n**Input**: \\\"War in Ukraine: Latest Updates on Negotiation Status\\\" \\n**Output**: \\\"World\\\"\\n\\n**Input**: \\\"Microsoft in Talks to Acquire Gaming Company for $2 Billion\\\" \\n**Output**: \\\"Business\\\"\\n\\n**Input**: \\\"Manchester United Secures Win in Premier League Football Match\\\" \\n**Output**: \\\"Sports\\\" \\n\\n# Notes\\n\\n- If the headline appears to fit into more than one category, choose the most dominant theme.\\n- Keywords or phrases such as \\\"stocks\\\", \\\"company acquisition\\\", \\\"match\\\", or technological brands can be good indicators for classification.\\n\",\n \"tool_call_id\": null,\n \"tool_calls\": null,\n \"function_call\": null\n },\n {\n \"role\": \"user\",\n \"content\": \"Stock Markets Rally After Positive Economic Data Released\",\n \"tool_call_id\": null,\n \"tool_calls\": null,\n \"function_call\": null\n }\n ],\n \"output\": [\n {\n \"role\": \"assistant\",\n \"content\": \"Markets\",\n \"tool_call_id\": null,\n \"tool_calls\": null,\n \"function_call\": null\n }\n ],\n \"finish_reason\": \"stop\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"usage\": {\n \"total_tokens\": 325,\n \"completion_tokens\": 2,\n \"prompt_tokens\": 323,\n \"cached_tokens\": 0\n },\n \"error\": null,\n \"temperature\": 1.0,\n \"max_completion_tokens\": 2048,\n \"top_p\": 1.0,\n \"seed\": 42\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7/output_items/outputitem_67abd55eb6548190bb580745d5644a33 \\ -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\noutput_item = client.evals.runs.output_items.retrieve(\n output_item_id=\"output_item_id\",\n eval_id=\"eval_id\",\n run_id=\"run_id\",\n)\nprint(output_item.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst outputItem = await client.evals.runs.outputItems.retrieve('output_item_id', {\n eval_id: 'eval_id',\n run_id: 'run_id',\n});\n\nconsole.log(outputItem.id);", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.evals.runs.outputitems.OutputItemRetrieveParams;\nimport com.openai.models.evals.runs.outputitems.OutputItemRetrieveResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n OutputItemRetrieveParams params = OutputItemRetrieveParams.builder()\n .evalId(\"eval_id\")\n .runId(\"run_id\")\n .outputItemId(\"output_item_id\")\n .build();\n OutputItemRetrieveResponse outputItem = client.evals().runs().outputItems().retrieve(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\noutput_item = openai.evals.runs.output_items.retrieve(\"output_item_id\", eval_id: \"eval_id\", run_id: \"run_id\")\n\nputs(output_item)" + } + } + }, + "description": "Get an evaluation run output item by ID.\n" + } + }, + "/files": { + "get": { + "operationId": "listFiles", + "tags": [ + "Files" + ], + "summary": "List files", + "parameters": [ + { + "in": "query", + "name": "purpose", + "required": false, + "schema": { + "type": "string" + }, + "description": "Only return files with the given purpose." + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 10,000, and the default is 10,000.\n", + "required": false, + "schema": { + "type": "integer", + "default": 10000 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListFilesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List files", + "group": "files", + "returns": "A list of [File](https://platform.openai.com/docs/api-reference/files/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"file-abc123\",\n \"object\": \"file\",\n \"bytes\": 175,\n \"created_at\": 1613677385,\n \"expires_at\": 1677614202,\n \"filename\": \"salesOverview.pdf\",\n \"purpose\": \"assistants\",\n },\n {\n \"id\": \"file-abc456\",\n \"object\": \"file\",\n \"bytes\": 140,\n \"created_at\": 1613779121,\n \"expires_at\": 1677614202,\n \"filename\": \"puppy.jsonl\",\n \"purpose\": \"fine-tune\",\n }\n ],\n \"first_id\": \"file-abc123\",\n \"last_id\": \"file-abc456\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/files \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.files.list()\npage = page.data[0]\nprint(page)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const fileObject of client.files.list()) {\n console.log(fileObject);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Files.List(context.TODO(), openai.FileListParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.files.FileListPage;\nimport com.openai.models.files.FileListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileListPage page = client.files().list();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.files.list\n\nputs(page)" + } + } + }, + "description": "Returns a list of files." + }, + "post": { + "operationId": "createFile", + "tags": [ + "Files" + ], + "summary": "Upload file", + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/CreateFileRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAIFile" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Upload file", + "group": "files", + "returns": "The uploaded [File](https://platform.openai.com/docs/api-reference/files/object) object.", + "examples": { + "response": "{\n \"id\": \"file-abc123\",\n \"object\": \"file\",\n \"bytes\": 120000,\n \"created_at\": 1677610602,\n \"expires_at\": 1677614202,\n \"filename\": \"mydata.jsonl\",\n \"purpose\": \"fine-tune\",\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/files \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -F purpose=\"fine-tune\" \\\n -F file=\"@mydata.jsonl\"\n -F expires_after[anchor]=\"created_at\"\n -F expires_after[seconds]=3600\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfile_object = client.files.create(\n file=b\"raw file contents\",\n purpose=\"assistants\",\n)\nprint(file_object.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fileObject = await client.files.create({\n file: fs.createReadStream('fine-tune.jsonl'),\n purpose: 'assistants',\n});\n\nconsole.log(fileObject.id);", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fileObject, err := client.Files.New(context.TODO(), openai.FileNewParams{\n File: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n Purpose: openai.FilePurposeAssistants,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fileObject.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.files.FileCreateParams;\nimport com.openai.models.files.FileObject;\nimport com.openai.models.files.FilePurpose;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileCreateParams params = FileCreateParams.builder()\n .file(ByteArrayInputStream(\"some content\".getBytes()))\n .purpose(FilePurpose.ASSISTANTS)\n .build();\n FileObject fileObject = client.files().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfile_object = openai.files.create(file: Pathname(__FILE__), purpose: :assistants)\n\nputs(file_object)" + } + } + }, + "description": "Upload a file that can be used across various endpoints. Individual files can be up to 512 MB, and the size of all files uploaded by one organization can be up to 1 TB.\n\nThe Assistants API supports files up to 2 million tokens and of specific file types. See the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for details.\n\nThe Fine-tuning API only supports `.jsonl` files. The input also has certain required formats for fine-tuning [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) models.\n\nThe Batch API only supports `.jsonl` files up to 200 MB in size. The input also has a specific required [format](https://platform.openai.com/docs/api-reference/batch/request-input).\n\nPlease [contact us](https://help.openai.com/) if you need to increase these storage limits.\n" + } + }, + "/files/{file_id}": { + "delete": { + "operationId": "deleteFile", + "tags": [ + "Files" + ], + "summary": "Delete file", + "parameters": [ + { + "in": "path", + "name": "file_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the file to use for this request." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteFileResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete file", + "group": "files", + "returns": "Deletion status.", + "examples": { + "response": "{\n \"id\": \"file-abc123\",\n \"object\": \"file\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/files/file-abc123 \\\n -X DELETE \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfile_deleted = client.files.delete(\n \"file_id\",\n)\nprint(file_deleted.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fileDeleted = await client.files.delete('file_id');\n\nconsole.log(fileDeleted.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fileDeleted, err := client.Files.Delete(context.TODO(), \"file_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fileDeleted.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.files.FileDeleteParams;\nimport com.openai.models.files.FileDeleted;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileDeleted fileDeleted = client.files().delete(\"file_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfile_deleted = openai.files.delete(\"file_id\")\n\nputs(file_deleted)" + } + } + }, + "description": "Delete a file." + }, + "get": { + "operationId": "retrieveFile", + "tags": [ + "Files" + ], + "summary": "Retrieve file", + "parameters": [ + { + "in": "path", + "name": "file_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the file to use for this request." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenAIFile" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve file", + "group": "files", + "returns": "The [File](https://platform.openai.com/docs/api-reference/files/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"file-abc123\",\n \"object\": \"file\",\n \"bytes\": 120000,\n \"created_at\": 1677610602,\n \"expires_at\": 1677614202,\n \"filename\": \"mydata.jsonl\",\n \"purpose\": \"fine-tune\",\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/files/file-abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfile_object = client.files.retrieve(\n \"file_id\",\n)\nprint(file_object.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fileObject = await client.files.retrieve('file_id');\n\nconsole.log(fileObject.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fileObject, err := client.Files.Get(context.TODO(), \"file_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fileObject.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.files.FileObject;\nimport com.openai.models.files.FileRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileObject fileObject = client.files().retrieve(\"file_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfile_object = openai.files.retrieve(\"file_id\")\n\nputs(file_object)" + } + } + }, + "description": "Returns information about a specific file." + } + }, + "/files/{file_id}/content": { + "get": { + "operationId": "downloadFile", + "tags": [ + "Files" + ], + "summary": "Retrieve file content", + "parameters": [ + { + "in": "path", + "name": "file_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the file to use for this request." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve file content", + "group": "files", + "returns": "The file content.", + "examples": { + "response": "", + "request": { + "curl": "curl https://api.openai.com/v1/files/file-abc123/content \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" > file.jsonl\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.files.content(\n \"file_id\",\n)\nprint(response)\ncontent = response.read()\nprint(content)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.files.content('file_id');\n\nconsole.log(response);\n\nconst content = await response.blob();\nconsole.log(content);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Files.Content(context.TODO(), \"file_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.core.http.HttpResponse;\nimport com.openai.models.files.FileContentParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n HttpResponse response = client.files().content(\"file_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.files.content(\"file_id\")\n\nputs(response)" + } + } + }, + "description": "Returns the contents of the specified file." + } + }, + "/fine_tuning/alpha/graders/run": { + "post": { + "operationId": "runGrader", + "tags": [ + "Fine-tuning" + ], + "summary": "Run grader", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunGraderRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunGraderResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Run grader", + "beta": true, + "group": "graders", + "returns": "The results from the grader run.", + "examples": { + "response": "{\n \"reward\": 1.0,\n \"metadata\": {\n \"name\": \"Example score model grader\",\n \"type\": \"score_model\",\n \"errors\": {\n \"formula_parse_error\": false,\n \"sample_parse_error\": false,\n \"truncated_observation_error\": false,\n \"unresponsive_reward_error\": false,\n \"invalid_variable_error\": false,\n \"other_error\": false,\n \"python_grader_server_error\": false,\n \"python_grader_server_error_type\": null,\n \"python_grader_runtime_error\": false,\n \"python_grader_runtime_error_details\": null,\n \"model_grader_server_error\": false,\n \"model_grader_refusal_error\": false,\n \"model_grader_parse_error\": false,\n \"model_grader_server_error_details\": null\n },\n \"execution_time\": 4.365238428115845,\n \"scores\": {},\n \"token_usage\": {\n \"prompt_tokens\": 190,\n \"total_tokens\": 324,\n \"completion_tokens\": 134,\n \"cached_tokens\": 0\n },\n \"sampled_model_name\": \"gpt-4o-2024-08-06\"\n },\n \"sub_rewards\": {},\n \"model_grader_token_usage_per_model\": {\n \"gpt-4o-2024-08-06\": {\n \"prompt_tokens\": 190,\n \"total_tokens\": 324,\n \"completion_tokens\": 134,\n \"cached_tokens\": 0\n }\n }\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/fine_tuning/alpha/graders/run \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"grader\": {\n \"type\": \"score_model\",\n \"name\": \"Example score model grader\",\n \"input\": [\n {\n \"role\": \"user\",\n \"content\": \"Score how close the reference answer is to the model answer. Score 1.0 if they are the same and 0.0 if they are different. Return just a floating point score\\n\\nReference answer: {{item.reference_answer}}\\n\\nModel answer: {{sample.output_text}}\"\n }\n ],\n \"model\": \"gpt-4o-2024-08-06\",\n \"sampling_params\": {\n \"temperature\": 1,\n \"top_p\": 1,\n \"seed\": 42\n }\n },\n \"item\": {\n \"reference_answer\": \"fuzzy wuzzy was a bear\"\n },\n \"model_sample\": \"fuzzy wuzzy was a bear\"\n }'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.fineTuning.alpha.graders.run({\n grader: { input: 'input', name: 'name', operation: 'eq', reference: 'reference', type: 'string_check' },\n model_sample: 'model_sample',\n});\n\nconsole.log(response.metadata);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.fine_tuning.alpha.graders.run(\n grader={\n \"input\": \"input\",\n \"name\": \"name\",\n \"operation\": \"eq\",\n \"reference\": \"reference\",\n \"type\": \"string_check\",\n },\n model_sample=\"model_sample\",\n)\nprint(response.metadata)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.FineTuning.Alpha.Graders.Run(context.TODO(), openai.FineTuningAlphaGraderRunParams{\n Grader: openai.FineTuningAlphaGraderRunParamsGraderUnion{\n OfStringCheck: &openai.StringCheckGraderParam{\n Input: \"input\",\n Name: \"name\",\n Operation: openai.StringCheckGraderOperationEq,\n Reference: \"reference\",\n },\n },\n ModelSample: \"model_sample\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.Metadata)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.alpha.graders.GraderRunParams;\nimport com.openai.models.finetuning.alpha.graders.GraderRunResponse;\nimport com.openai.models.graders.gradermodels.StringCheckGrader;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n GraderRunParams params = GraderRunParams.builder()\n .grader(StringCheckGrader.builder()\n .input(\"input\")\n .name(\"name\")\n .operation(StringCheckGrader.Operation.EQ)\n .reference(\"reference\")\n .build())\n .modelSample(\"model_sample\")\n .build();\n GraderRunResponse response = client.fineTuning().alpha().graders().run(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.fine_tuning.alpha.graders.run(\n grader: {input: \"input\", name: \"name\", operation: :eq, reference: \"reference\", type: :string_check},\n model_sample: \"model_sample\"\n)\n\nputs(response)" + } + } + }, + "description": "Run a grader.\n" + } + }, + "/fine_tuning/alpha/graders/validate": { + "post": { + "operationId": "validateGrader", + "tags": [ + "Fine-tuning" + ], + "summary": "Validate grader", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidateGraderRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidateGraderResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Validate grader", + "beta": true, + "group": "graders", + "returns": "The validated grader object.", + "examples": { + "response": "{\n \"grader\": {\n \"type\": \"string_check\",\n \"name\": \"Example string check grader\",\n \"input\": \"{{sample.output_text}}\",\n \"reference\": \"{{item.label}}\",\n \"operation\": \"eq\"\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/alpha/graders/validate \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"grader\": {\n \"type\": \"string_check\",\n \"name\": \"Example string check grader\",\n \"input\": \"{{sample.output_text}}\",\n \"reference\": \"{{item.label}}\",\n \"operation\": \"eq\"\n }\n }'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.fineTuning.alpha.graders.validate({\n grader: { input: 'input', name: 'name', operation: 'eq', reference: 'reference', type: 'string_check' },\n});\n\nconsole.log(response.grader);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.fine_tuning.alpha.graders.validate(\n grader={\n \"input\": \"input\",\n \"name\": \"name\",\n \"operation\": \"eq\",\n \"reference\": \"reference\",\n \"type\": \"string_check\",\n },\n)\nprint(response.grader)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.FineTuning.Alpha.Graders.Validate(context.TODO(), openai.FineTuningAlphaGraderValidateParams{\n Grader: openai.FineTuningAlphaGraderValidateParamsGraderUnion{\n OfStringCheckGrader: &openai.StringCheckGraderParam{\n Input: \"input\",\n Name: \"name\",\n Operation: openai.StringCheckGraderOperationEq,\n Reference: \"reference\",\n },\n },\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.Grader)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.alpha.graders.GraderValidateParams;\nimport com.openai.models.finetuning.alpha.graders.GraderValidateResponse;\nimport com.openai.models.graders.gradermodels.StringCheckGrader;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n GraderValidateParams params = GraderValidateParams.builder()\n .grader(StringCheckGrader.builder()\n .input(\"input\")\n .name(\"name\")\n .operation(StringCheckGrader.Operation.EQ)\n .reference(\"reference\")\n .build())\n .build();\n GraderValidateResponse response = client.fineTuning().alpha().graders().validate(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.fine_tuning.alpha.graders.validate(\n grader: {input: \"input\", name: \"name\", operation: :eq, reference: \"reference\", type: :string_check}\n)\n\nputs(response)" + } + } + }, + "description": "Validate a grader.\n" + } + }, + "/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions": { + "get": { + "operationId": "listFineTuningCheckpointPermissions", + "tags": [ + "Fine-tuning" + ], + "summary": "List checkpoint permissions", + "parameters": [ + { + "in": "path", + "name": "fine_tuned_model_checkpoint", + "required": true, + "schema": { + "type": "string", + "example": "ft-AF1WoRqd3aJAHsqc9NY7iL8F" + }, + "description": "The ID of the fine-tuned model checkpoint to get permissions for.\n" + }, + { + "name": "project_id", + "in": "query", + "description": "The ID of the project to get permissions for.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "after", + "in": "query", + "description": "Identifier for the last permission ID from the previous pagination request.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of permissions to retrieve.", + "required": false, + "schema": { + "type": "integer", + "default": 10 + } + }, + { + "name": "order", + "in": "query", + "description": "The order in which to retrieve permissions.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "ascending", + "descending" + ], + "default": "descending" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListFineTuningCheckpointPermissionResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List checkpoint permissions", + "group": "fine-tuning", + "returns": "A list of fine-tuned model checkpoint [permission objects](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object) for a fine-tuned model checkpoint.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"checkpoint.permission\",\n \"id\": \"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n \"created_at\": 1721764867,\n \"project_id\": \"proj_abGMw1llN8IrBb6SvvY5A1iH\"\n },\n {\n \"object\": \"checkpoint.permission\",\n \"id\": \"cp_enQCFmOTGj3syEpYVhBRLTSy\",\n \"created_at\": 1721764800,\n \"project_id\": \"proj_iqGMw1llN8IrBb6SvvY5A1oF\"\n },\n ],\n \"first_id\": \"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n \"last_id\": \"cp_enQCFmOTGj3syEpYVhBRLTSy\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions \\ -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst permission = await client.fineTuning.checkpoints.permissions.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F');\n\nconsole.log(permission.first_id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npermission = client.fine_tuning.checkpoints.permissions.retrieve(\n fine_tuned_model_checkpoint=\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n)\nprint(permission.first_id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n permission, err := client.FineTuning.Checkpoints.Permissions.Get(\n context.TODO(),\n \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n openai.FineTuningCheckpointPermissionGetParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", permission.FirstID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.checkpoints.permissions.PermissionRetrieveParams;\nimport com.openai.models.finetuning.checkpoints.permissions.PermissionRetrieveResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n PermissionRetrieveResponse permission = client.fineTuning().checkpoints().permissions().retrieve(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npermission = openai.fine_tuning.checkpoints.permissions.retrieve(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\nputs(permission)" + } + } + }, + "description": "**NOTE:** This endpoint requires an [admin API key](../admin-api-keys).\n\nOrganization owners can use this endpoint to view all permissions for a fine-tuned model checkpoint.\n" + }, + "post": { + "operationId": "createFineTuningCheckpointPermission", + "tags": [ + "Fine-tuning" + ], + "summary": "Create checkpoint permissions", + "parameters": [ + { + "in": "path", + "name": "fine_tuned_model_checkpoint", + "required": true, + "schema": { + "type": "string", + "example": "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd" + }, + "description": "The ID of the fine-tuned model checkpoint to create a permission for.\n" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateFineTuningCheckpointPermissionRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListFineTuningCheckpointPermissionResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create checkpoint permissions", + "group": "fine-tuning", + "returns": "A list of fine-tuned model checkpoint [permission objects](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object) for a fine-tuned model checkpoint.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"checkpoint.permission\",\n \"id\": \"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n \"created_at\": 1721764867,\n \"project_id\": \"proj_abGMw1llN8IrBb6SvvY5A1iH\"\n }\n ],\n \"first_id\": \"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n \"last_id\": \"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions \\ -H \"Authorization: Bearer $OPENAI_API_KEY\"\n -d '{\"project_ids\": [\"proj_abGMw1llN8IrBb6SvvY5A1iH\"]}'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create(\n 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',\n { project_ids: ['string'] },\n)) {\n console.log(permissionCreateResponse.id);\n}", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.fine_tuning.checkpoints.permissions.create(\n fine_tuned_model_checkpoint=\"ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd\",\n project_ids=[\"string\"],\n)\npage = page.data[0]\nprint(page.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.FineTuning.Checkpoints.Permissions.New(\n context.TODO(),\n \"ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd\",\n openai.FineTuningCheckpointPermissionNewParams{\n ProjectIDs: []string{\"string\"},\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.checkpoints.permissions.PermissionCreatePage;\nimport com.openai.models.finetuning.checkpoints.permissions.PermissionCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n PermissionCreateParams params = PermissionCreateParams.builder()\n .fineTunedModelCheckpoint(\"ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd\")\n .addProjectId(\"string\")\n .build();\n PermissionCreatePage page = client.fineTuning().checkpoints().permissions().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.fine_tuning.checkpoints.permissions.create(\n \"ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd\",\n project_ids: [\"string\"]\n)\n\nputs(page)" + } + } + }, + "description": "**NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys).\n\nThis enables organization owners to share fine-tuned models with other projects in their organization.\n" + } + }, + "/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}": { + "delete": { + "operationId": "deleteFineTuningCheckpointPermission", + "tags": [ + "Fine-tuning" + ], + "summary": "Delete checkpoint permission", + "parameters": [ + { + "in": "path", + "name": "fine_tuned_model_checkpoint", + "required": true, + "schema": { + "type": "string", + "example": "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd" + }, + "description": "The ID of the fine-tuned model checkpoint to delete a permission for.\n" + }, + { + "in": "path", + "name": "permission_id", + "required": true, + "schema": { + "type": "string", + "example": "cp_zc4Q7MP6XxulcVzj4MZdwsAB" + }, + "description": "The ID of the fine-tuned model checkpoint permission to delete.\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteFineTuningCheckpointPermissionResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete checkpoint permission", + "group": "fine-tuning", + "returns": "The deletion status of the fine-tuned model checkpoint [permission object](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object).", + "examples": { + "response": "{\n \"object\": \"checkpoint.permission\",\n \"id\": \"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions/cp_zc4Q7MP6XxulcVzj4MZdwsAB \\ -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst permission = await client.fineTuning.checkpoints.permissions.delete('cp_zc4Q7MP6XxulcVzj4MZdwsAB', { fine_tuned_model_checkpoint: 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',\n});\n\nconsole.log(permission.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npermission = client.fine_tuning.checkpoints.permissions.delete(\n permission_id=\"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n fine_tuned_model_checkpoint=\"ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd\",\n)\nprint(permission.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n permission, err := client.FineTuning.Checkpoints.Permissions.Delete(\n context.TODO(),\n \"ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd\",\n \"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", permission.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.checkpoints.permissions.PermissionDeleteParams;\nimport com.openai.models.finetuning.checkpoints.permissions.PermissionDeleteResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n PermissionDeleteParams params = PermissionDeleteParams.builder()\n .fineTunedModelCheckpoint(\"ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd\")\n .permissionId(\"cp_zc4Q7MP6XxulcVzj4MZdwsAB\")\n .build();\n PermissionDeleteResponse permission = client.fineTuning().checkpoints().permissions().delete(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npermission = openai.fine_tuning.checkpoints.permissions.delete(\n \"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n fine_tuned_model_checkpoint: \"ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd\"\n)\n\nputs(permission)" + } + } + }, + "description": "**NOTE:** This endpoint requires an [admin API key](../admin-api-keys).\n\nOrganization owners can use this endpoint to delete a permission for a fine-tuned model checkpoint.\n" + } + }, + "/fine_tuning/jobs": { + "post": { + "operationId": "createFineTuningJob", + "tags": [ + "Fine-tuning" + ], + "summary": "Create fine-tuning job", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateFineTuningJobRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FineTuningJob" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create fine-tuning job", + "group": "fine-tuning", + "returns": "A [fine-tuning.job](https://platform.openai.com/docs/api-reference/fine-tuning/object) object.", + "examples": [ + { + "title": "Default", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"training_file\": \"file-BK7bzQj3FfZFXr7DbL6xJwfo\",\n \"model\": \"gpt-4o-mini\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfine_tuning_job = client.fine_tuning.jobs.create(\n model=\"gpt-4o-mini\",\n training_file=\"file-abc123\",\n)\nprint(fine_tuning_job.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fineTuningJob = await client.fineTuning.jobs.create({\n model: 'gpt-4o-mini',\n training_file: 'file-abc123',\n});\n\nconsole.log(fineTuningJob.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n Model: openai.FineTuningJobNewParamsModelBabbage002,\n TrainingFile: \"file-abc123\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.FineTuningJob;\nimport com.openai.models.finetuning.jobs.JobCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n JobCreateParams params = JobCreateParams.builder()\n .model(JobCreateParams.Model.BABBAGE_002)\n .trainingFile(\"file-abc123\")\n .build();\n FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfine_tuning_job = openai.fine_tuning.jobs.create(model: :\"babbage-002\", training_file: \"file-abc123\")\n\nputs(fine_tuning_job)" + }, + "response": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"created_at\": 1721764800,\n \"fine_tuned_model\": null,\n \"organization_id\": \"org-123\",\n \"result_files\": [],\n \"status\": \"queued\",\n \"validation_file\": null,\n \"training_file\": \"file-abc123\",\n \"method\": {\n \"type\": \"supervised\",\n \"supervised\": {\n \"hyperparameters\": {\n \"batch_size\": \"auto\",\n \"learning_rate_multiplier\": \"auto\",\n \"n_epochs\": \"auto\",\n }\n }\n },\n \"metadata\": null\n}\n" + }, + { + "title": "Epochs", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"training_file\": \"file-abc123\",\n \"model\": \"gpt-4o-mini\",\n \"method\": {\n \"type\": \"supervised\",\n \"supervised\": {\n \"hyperparameters\": {\n \"n_epochs\": 2\n }\n }\n }\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfine_tuning_job = client.fine_tuning.jobs.create(\n model=\"gpt-4o-mini\",\n training_file=\"file-abc123\",\n)\nprint(fine_tuning_job.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fineTuningJob = await client.fineTuning.jobs.create({\n model: 'gpt-4o-mini',\n training_file: 'file-abc123',\n});\n\nconsole.log(fineTuningJob.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n Model: openai.FineTuningJobNewParamsModelBabbage002,\n TrainingFile: \"file-abc123\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.FineTuningJob;\nimport com.openai.models.finetuning.jobs.JobCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n JobCreateParams params = JobCreateParams.builder()\n .model(JobCreateParams.Model.BABBAGE_002)\n .trainingFile(\"file-abc123\")\n .build();\n FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfine_tuning_job = openai.fine_tuning.jobs.create(model: :\"babbage-002\", training_file: \"file-abc123\")\n\nputs(fine_tuning_job)" + }, + "response": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"gpt-4o-mini\",\n \"created_at\": 1721764800,\n \"fine_tuned_model\": null,\n \"organization_id\": \"org-123\",\n \"result_files\": [],\n \"status\": \"queued\",\n \"validation_file\": null,\n \"training_file\": \"file-abc123\",\n \"hyperparameters\": {\n \"batch_size\": \"auto\",\n \"learning_rate_multiplier\": \"auto\",\n \"n_epochs\": 2\n },\n \"method\": {\n \"type\": \"supervised\",\n \"supervised\": {\n \"hyperparameters\": {\n \"batch_size\": \"auto\",\n \"learning_rate_multiplier\": \"auto\",\n \"n_epochs\": 2\n }\n }\n },\n \"metadata\": null,\n \"error\": {\n \"code\": null,\n \"message\": null,\n \"param\": null\n },\n \"finished_at\": null,\n \"seed\": 683058546,\n \"trained_tokens\": null,\n \"estimated_finish\": null,\n \"integrations\": [],\n \"user_provided_suffix\": null,\n \"usage_metrics\": null,\n \"shared_with_openai\": false\n}\n" + }, + { + "title": "DPO", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"training_file\": \"file-abc123\",\n \"validation_file\": \"file-abc123\",\n \"model\": \"gpt-4o-mini\",\n \"method\": {\n \"type\": \"dpo\",\n \"dpo\": {\n \"hyperparameters\": {\n \"beta\": 0.1\n }\n }\n }\n }'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fineTuningJob = await client.fineTuning.jobs.create({\n model: 'gpt-4o-mini',\n training_file: 'file-abc123',\n});\n\nconsole.log(fineTuningJob.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfine_tuning_job = client.fine_tuning.jobs.create(\n model=\"gpt-4o-mini\",\n training_file=\"file-abc123\",\n)\nprint(fine_tuning_job.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n Model: openai.FineTuningJobNewParamsModelBabbage002,\n TrainingFile: \"file-abc123\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.FineTuningJob;\nimport com.openai.models.finetuning.jobs.JobCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n JobCreateParams params = JobCreateParams.builder()\n .model(JobCreateParams.Model.BABBAGE_002)\n .trainingFile(\"file-abc123\")\n .build();\n FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfine_tuning_job = openai.fine_tuning.jobs.create(model: :\"babbage-002\", training_file: \"file-abc123\")\n\nputs(fine_tuning_job)" + }, + "python": "from openai import OpenAI\nfrom openai.types.fine_tuning import DpoMethod, DpoHyperparameters\n\nclient = OpenAI()\n\nclient.fine_tuning.jobs.create(\n training_file=\"file-abc\",\n validation_file=\"file-123\",\n model=\"gpt-4o-mini\",\n method={\n \"type\": \"dpo\",\n \"dpo\": DpoMethod(\n hyperparameters=DpoHyperparameters(beta=0.1)\n )\n }\n)\n", + "response": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc\",\n \"model\": \"gpt-4o-mini\",\n \"created_at\": 1746130590,\n \"fine_tuned_model\": null,\n \"organization_id\": \"org-abc\",\n \"result_files\": [],\n \"status\": \"queued\",\n \"validation_file\": \"file-123\",\n \"training_file\": \"file-abc\",\n \"method\": {\n \"type\": \"dpo\",\n \"dpo\": {\n \"hyperparameters\": {\n \"beta\": 0.1,\n \"batch_size\": \"auto\",\n \"learning_rate_multiplier\": \"auto\",\n \"n_epochs\": \"auto\"\n }\n }\n },\n \"metadata\": null,\n \"error\": {\n \"code\": null,\n \"message\": null,\n \"param\": null\n },\n \"finished_at\": null,\n \"hyperparameters\": null,\n \"seed\": 1036326793,\n \"estimated_finish\": null,\n \"integrations\": [],\n \"user_provided_suffix\": null,\n \"usage_metrics\": null,\n \"shared_with_openai\": false\n}\n" + }, + { + "title": "Reinforcement", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"training_file\": \"file-abc\",\n \"validation_file\": \"file-123\",\n \"model\": \"o4-mini\",\n \"method\": {\n \"type\": \"reinforcement\",\n \"reinforcement\": {\n \"grader\": {\n \"type\": \"string_check\",\n \"name\": \"Example string check grader\",\n \"input\": \"{{sample.output_text}}\",\n \"reference\": \"{{item.label}}\",\n \"operation\": \"eq\"\n },\n \"hyperparameters\": {\n \"reasoning_effort\": \"medium\"\n }\n }\n }\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfine_tuning_job = client.fine_tuning.jobs.create(\n model=\"gpt-4o-mini\",\n training_file=\"file-abc123\",\n)\nprint(fine_tuning_job.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fineTuningJob = await client.fineTuning.jobs.create({\n model: 'gpt-4o-mini',\n training_file: 'file-abc123',\n});\n\nconsole.log(fineTuningJob.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n Model: openai.FineTuningJobNewParamsModelBabbage002,\n TrainingFile: \"file-abc123\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.FineTuningJob;\nimport com.openai.models.finetuning.jobs.JobCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n JobCreateParams params = JobCreateParams.builder()\n .model(JobCreateParams.Model.BABBAGE_002)\n .trainingFile(\"file-abc123\")\n .build();\n FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfine_tuning_job = openai.fine_tuning.jobs.create(model: :\"babbage-002\", training_file: \"file-abc123\")\n\nputs(fine_tuning_job)" + }, + "response": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"o4-mini\",\n \"created_at\": 1721764800,\n \"finished_at\": null,\n \"fine_tuned_model\": null,\n \"organization_id\": \"org-123\",\n \"result_files\": [],\n \"status\": \"validating_files\",\n \"validation_file\": \"file-123\",\n \"training_file\": \"file-abc\",\n \"trained_tokens\": null,\n \"error\": {},\n \"user_provided_suffix\": null,\n \"seed\": 950189191,\n \"estimated_finish\": null,\n \"integrations\": [],\n \"method\": {\n \"type\": \"reinforcement\",\n \"reinforcement\": {\n \"hyperparameters\": {\n \"batch_size\": \"auto\",\n \"learning_rate_multiplier\": \"auto\",\n \"n_epochs\": \"auto\",\n \"eval_interval\": \"auto\",\n \"eval_samples\": \"auto\",\n \"compute_multiplier\": \"auto\",\n \"reasoning_effort\": \"medium\"\n },\n \"grader\": {\n \"type\": \"string_check\",\n \"name\": \"Example string check grader\",\n \"input\": \"{{sample.output_text}}\",\n \"reference\": \"{{item.label}}\",\n \"operation\": \"eq\"\n },\n \"response_format\": null\n }\n },\n \"metadata\": null,\n \"usage_metrics\": null,\n \"shared_with_openai\": false\n}\n" + }, + { + "title": "Validation file", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"training_file\": \"file-abc123\",\n \"validation_file\": \"file-abc123\",\n \"model\": \"gpt-4o-mini\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfine_tuning_job = client.fine_tuning.jobs.create(\n model=\"gpt-4o-mini\",\n training_file=\"file-abc123\",\n)\nprint(fine_tuning_job.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fineTuningJob = await client.fineTuning.jobs.create({\n model: 'gpt-4o-mini',\n training_file: 'file-abc123',\n});\n\nconsole.log(fineTuningJob.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n Model: openai.FineTuningJobNewParamsModelBabbage002,\n TrainingFile: \"file-abc123\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.FineTuningJob;\nimport com.openai.models.finetuning.jobs.JobCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n JobCreateParams params = JobCreateParams.builder()\n .model(JobCreateParams.Model.BABBAGE_002)\n .trainingFile(\"file-abc123\")\n .build();\n FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfine_tuning_job = openai.fine_tuning.jobs.create(model: :\"babbage-002\", training_file: \"file-abc123\")\n\nputs(fine_tuning_job)" + }, + "response": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"created_at\": 1721764800,\n \"fine_tuned_model\": null,\n \"organization_id\": \"org-123\",\n \"result_files\": [],\n \"status\": \"queued\",\n \"validation_file\": \"file-abc123\",\n \"training_file\": \"file-abc123\",\n \"method\": {\n \"type\": \"supervised\",\n \"supervised\": {\n \"hyperparameters\": {\n \"batch_size\": \"auto\",\n \"learning_rate_multiplier\": \"auto\",\n \"n_epochs\": \"auto\",\n }\n }\n },\n \"metadata\": null\n}\n" + }, + { + "title": "W&B Integration", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/jobs \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"training_file\": \"file-abc123\",\n \"validation_file\": \"file-abc123\",\n \"model\": \"gpt-4o-mini\",\n \"integrations\": [\n {\n \"type\": \"wandb\",\n \"wandb\": {\n \"project\": \"my-wandb-project\",\n \"name\": \"ft-run-display-name\"\n \"tags\": [\n \"first-experiment\", \"v2\"\n ]\n }\n }\n ]\n }'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fineTuningJob = await client.fineTuning.jobs.create({\n model: 'gpt-4o-mini',\n training_file: 'file-abc123',\n});\n\nconsole.log(fineTuningJob.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfine_tuning_job = client.fine_tuning.jobs.create(\n model=\"gpt-4o-mini\",\n training_file=\"file-abc123\",\n)\nprint(fine_tuning_job.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n Model: openai.FineTuningJobNewParamsModelBabbage002,\n TrainingFile: \"file-abc123\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.FineTuningJob;\nimport com.openai.models.finetuning.jobs.JobCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n JobCreateParams params = JobCreateParams.builder()\n .model(JobCreateParams.Model.BABBAGE_002)\n .trainingFile(\"file-abc123\")\n .build();\n FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfine_tuning_job = openai.fine_tuning.jobs.create(model: :\"babbage-002\", training_file: \"file-abc123\")\n\nputs(fine_tuning_job)" + }, + "response": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"created_at\": 1721764800,\n \"fine_tuned_model\": null,\n \"organization_id\": \"org-123\",\n \"result_files\": [],\n \"status\": \"queued\",\n \"validation_file\": \"file-abc123\",\n \"training_file\": \"file-abc123\",\n \"integrations\": [\n {\n \"type\": \"wandb\",\n \"wandb\": {\n \"project\": \"my-wandb-project\",\n \"entity\": None,\n \"run_id\": \"ftjob-abc123\"\n }\n }\n ],\n \"method\": {\n \"type\": \"supervised\",\n \"supervised\": {\n \"hyperparameters\": {\n \"batch_size\": \"auto\",\n \"learning_rate_multiplier\": \"auto\",\n \"n_epochs\": \"auto\",\n }\n }\n },\n \"metadata\": null\n}\n" + } + ] + }, + "description": "Creates a fine-tuning job which begins the process of creating a new model from a given dataset.\n\nResponse includes details of the enqueued job including job status and the name of the fine-tuned models once complete.\n\n[Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)\n" + }, + "get": { + "operationId": "listPaginatedFineTuningJobs", + "tags": [ + "Fine-tuning" + ], + "summary": "List fine-tuning jobs", + "parameters": [ + { + "name": "after", + "in": "query", + "description": "Identifier for the last job from the previous pagination request.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of fine-tuning jobs to retrieve.", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "in": "query", + "name": "metadata", + "required": false, + "schema": { + "type": "object", + "nullable": true, + "additionalProperties": { + "type": "string" + } + }, + "style": "deepObject", + "explode": true, + "description": "Optional metadata filter. To filter, use the syntax `metadata[k]=v`. Alternatively, set `metadata=null` to indicate no metadata.\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListPaginatedFineTuningJobsResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List fine-tuning jobs", + "group": "fine-tuning", + "returns": "A list of paginated [fine-tuning job](https://platform.openai.com/docs/api-reference/fine-tuning/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"created_at\": 1721764800,\n \"fine_tuned_model\": null,\n \"organization_id\": \"org-123\",\n \"result_files\": [],\n \"status\": \"queued\",\n \"validation_file\": null,\n \"training_file\": \"file-abc123\",\n \"metadata\": {\n \"key\": \"value\"\n }\n },\n { ... },\n { ... }\n ], \"has_more\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/jobs?limit=2&metadata[key]=value \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.fine_tuning.jobs.list()\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const fineTuningJob of client.fineTuning.jobs.list()) {\n console.log(fineTuningJob.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.FineTuning.Jobs.List(context.TODO(), openai.FineTuningJobListParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.JobListPage;\nimport com.openai.models.finetuning.jobs.JobListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n JobListPage page = client.fineTuning().jobs().list();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.fine_tuning.jobs.list\n\nputs(page)" + } + } + }, + "description": "List your organization's fine-tuning jobs\n" + } + }, + "/fine_tuning/jobs/{fine_tuning_job_id}": { + "get": { + "operationId": "retrieveFineTuningJob", + "tags": [ + "Fine-tuning" + ], + "summary": "Retrieve fine-tuning job", + "parameters": [ + { + "in": "path", + "name": "fine_tuning_job_id", + "required": true, + "schema": { + "type": "string", + "example": "ft-AF1WoRqd3aJAHsqc9NY7iL8F" + }, + "description": "The ID of the fine-tuning job.\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FineTuningJob" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve fine-tuning job", + "group": "fine-tuning", + "returns": "The [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object with the given ID.", + "examples": { + "response": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"davinci-002\",\n \"created_at\": 1692661014,\n \"finished_at\": 1692661190,\n \"fine_tuned_model\": \"ft:davinci-002:my-org:custom_suffix:7q8mpxmy\",\n \"organization_id\": \"org-123\",\n \"result_files\": [\n \"file-abc123\"\n ],\n \"status\": \"succeeded\",\n \"validation_file\": null,\n \"training_file\": \"file-abc123\",\n \"hyperparameters\": {\n \"n_epochs\": 4,\n \"batch_size\": 1,\n \"learning_rate_multiplier\": 1.0\n },\n \"trained_tokens\": 5768,\n \"integrations\": [],\n \"seed\": 0,\n \"estimated_finish\": 0,\n \"method\": {\n \"type\": \"supervised\",\n \"supervised\": {\n \"hyperparameters\": {\n \"n_epochs\": 4,\n \"batch_size\": 1,\n \"learning_rate_multiplier\": 1.0\n }\n }\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/jobs/ft-AF1WoRqd3aJAHsqc9NY7iL8F \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfine_tuning_job = client.fine_tuning.jobs.retrieve(\n \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n)\nprint(fine_tuning_job.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fineTuningJob = await client.fineTuning.jobs.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F');\n\nconsole.log(fineTuningJob.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fineTuningJob, err := client.FineTuning.Jobs.Get(context.TODO(), \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.FineTuningJob;\nimport com.openai.models.finetuning.jobs.JobRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FineTuningJob fineTuningJob = client.fineTuning().jobs().retrieve(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfine_tuning_job = openai.fine_tuning.jobs.retrieve(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\nputs(fine_tuning_job)" + } + } + }, + "description": "Get info about a fine-tuning job.\n\n[Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)\n" + } + }, + "/fine_tuning/jobs/{fine_tuning_job_id}/cancel": { + "post": { + "operationId": "cancelFineTuningJob", + "tags": [ + "Fine-tuning" + ], + "summary": "Cancel fine-tuning", + "parameters": [ + { + "in": "path", + "name": "fine_tuning_job_id", + "required": true, + "schema": { + "type": "string", + "example": "ft-AF1WoRqd3aJAHsqc9NY7iL8F" + }, + "description": "The ID of the fine-tuning job to cancel.\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FineTuningJob" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Cancel fine-tuning", + "group": "fine-tuning", + "returns": "The cancelled [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object.", + "examples": { + "response": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"created_at\": 1721764800,\n \"fine_tuned_model\": null,\n \"organization_id\": \"org-123\",\n \"result_files\": [],\n \"status\": \"cancelled\",\n \"validation_file\": \"file-abc123\",\n \"training_file\": \"file-abc123\"\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/cancel \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfine_tuning_job = client.fine_tuning.jobs.cancel(\n \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n)\nprint(fine_tuning_job.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fineTuningJob = await client.fineTuning.jobs.cancel('ft-AF1WoRqd3aJAHsqc9NY7iL8F');\n\nconsole.log(fineTuningJob.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fineTuningJob, err := client.FineTuning.Jobs.Cancel(context.TODO(), \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.FineTuningJob;\nimport com.openai.models.finetuning.jobs.JobCancelParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FineTuningJob fineTuningJob = client.fineTuning().jobs().cancel(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfine_tuning_job = openai.fine_tuning.jobs.cancel(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\nputs(fine_tuning_job)" + } + } + }, + "description": "Immediately cancel a fine-tune job.\n" + } + }, + "/fine_tuning/jobs/{fine_tuning_job_id}/checkpoints": { + "get": { + "operationId": "listFineTuningJobCheckpoints", + "tags": [ + "Fine-tuning" + ], + "summary": "List fine-tuning checkpoints", + "parameters": [ + { + "in": "path", + "name": "fine_tuning_job_id", + "required": true, + "schema": { + "type": "string", + "example": "ft-AF1WoRqd3aJAHsqc9NY7iL8F" + }, + "description": "The ID of the fine-tuning job to get checkpoints for.\n" + }, + { + "name": "after", + "in": "query", + "description": "Identifier for the last checkpoint ID from the previous pagination request.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of checkpoints to retrieve.", + "required": false, + "schema": { + "type": "integer", + "default": 10 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListFineTuningJobCheckpointsResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List fine-tuning checkpoints", + "group": "fine-tuning", + "returns": "A list of fine-tuning [checkpoint objects](https://platform.openai.com/docs/api-reference/fine-tuning/checkpoint-object) for a fine-tuning job.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"fine_tuning.job.checkpoint\",\n \"id\": \"ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB\",\n \"created_at\": 1721764867,\n \"fine_tuned_model_checkpoint\": \"ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:96olL566:ckpt-step-2000\",\n \"metrics\": {\n \"full_valid_loss\": 0.134,\n \"full_valid_mean_token_accuracy\": 0.874\n },\n \"fine_tuning_job_id\": \"ftjob-abc123\",\n \"step_number\": 2000\n },\n {\n \"object\": \"fine_tuning.job.checkpoint\",\n \"id\": \"ftckpt_enQCFmOTGj3syEpYVhBRLTSy\",\n \"created_at\": 1721764800,\n \"fine_tuned_model_checkpoint\": \"ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:7q8mpxmy:ckpt-step-1000\",\n \"metrics\": {\n \"full_valid_loss\": 0.167,\n \"full_valid_mean_token_accuracy\": 0.781\n },\n \"fine_tuning_job_id\": \"ftjob-abc123\",\n \"step_number\": 1000\n }\n ],\n \"first_id\": \"ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB\",\n \"last_id\": \"ftckpt_enQCFmOTGj3syEpYVhBRLTSy\",\n \"has_more\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/checkpoints \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list(\n 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',\n)) {\n console.log(fineTuningJobCheckpoint.id);\n}", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.fine_tuning.jobs.checkpoints.list(\n fine_tuning_job_id=\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n)\npage = page.data[0]\nprint(page.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.FineTuning.Jobs.Checkpoints.List(\n context.TODO(),\n \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n openai.FineTuningJobCheckpointListParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.checkpoints.CheckpointListPage;\nimport com.openai.models.finetuning.jobs.checkpoints.CheckpointListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n CheckpointListPage page = client.fineTuning().jobs().checkpoints().list(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.fine_tuning.jobs.checkpoints.list(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\nputs(page)" + } + } + }, + "description": "List checkpoints for a fine-tuning job.\n" + } + }, + "/fine_tuning/jobs/{fine_tuning_job_id}/events": { + "get": { + "operationId": "listFineTuningEvents", + "tags": [ + "Fine-tuning" + ], + "summary": "List fine-tuning events", + "parameters": [ + { + "in": "path", + "name": "fine_tuning_job_id", + "required": true, + "schema": { + "type": "string", + "example": "ft-AF1WoRqd3aJAHsqc9NY7iL8F" + }, + "description": "The ID of the fine-tuning job to get events for.\n" + }, + { + "name": "after", + "in": "query", + "description": "Identifier for the last event from the previous pagination request.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of events to retrieve.", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListFineTuningJobEventsResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List fine-tuning events", + "group": "fine-tuning", + "returns": "A list of fine-tuning event objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"fine_tuning.job.event\",\n \"id\": \"ft-event-ddTJfwuMVpfLXseO0Am0Gqjm\",\n \"created_at\": 1721764800,\n \"level\": \"info\",\n \"message\": \"Fine tuning job successfully completed\",\n \"data\": null,\n \"type\": \"message\"\n },\n {\n \"object\": \"fine_tuning.job.event\",\n \"id\": \"ft-event-tyiGuB72evQncpH87xe505Sv\",\n \"created_at\": 1721764800,\n \"level\": \"info\",\n \"message\": \"New fine-tuned model created: ft:gpt-4o-mini:openai::7p4lURel\",\n \"data\": null,\n \"type\": \"message\"\n }\n ],\n \"has_more\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/events \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.fine_tuning.jobs.list_events(\n fine_tuning_job_id=\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n)\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents('ft-AF1WoRqd3aJAHsqc9NY7iL8F')) { console.log(fineTuningJobEvent.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.FineTuning.Jobs.ListEvents(\n context.TODO(),\n \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n openai.FineTuningJobListEventsParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.JobListEventsPage;\nimport com.openai.models.finetuning.jobs.JobListEventsParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n JobListEventsPage page = client.fineTuning().jobs().listEvents(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.fine_tuning.jobs.list_events(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\nputs(page)" + } + } + }, + "description": "Get status updates for a fine-tuning job.\n" + } + }, + "/fine_tuning/jobs/{fine_tuning_job_id}/pause": { + "post": { + "operationId": "pauseFineTuningJob", + "tags": [ + "Fine-tuning" + ], + "summary": "Pause fine-tuning", + "parameters": [ + { + "in": "path", + "name": "fine_tuning_job_id", + "required": true, + "schema": { + "type": "string", + "example": "ft-AF1WoRqd3aJAHsqc9NY7iL8F" + }, + "description": "The ID of the fine-tuning job to pause.\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FineTuningJob" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Pause fine-tuning", + "group": "fine-tuning", + "returns": "The paused [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object.", + "examples": { + "response": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"created_at\": 1721764800,\n \"fine_tuned_model\": null,\n \"organization_id\": \"org-123\",\n \"result_files\": [],\n \"status\": \"paused\",\n \"validation_file\": \"file-abc123\",\n \"training_file\": \"file-abc123\"\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/pause \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfine_tuning_job = client.fine_tuning.jobs.pause(\n \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n)\nprint(fine_tuning_job.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fineTuningJob = await client.fineTuning.jobs.pause('ft-AF1WoRqd3aJAHsqc9NY7iL8F');\n\nconsole.log(fineTuningJob.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fineTuningJob, err := client.FineTuning.Jobs.Pause(context.TODO(), \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.FineTuningJob;\nimport com.openai.models.finetuning.jobs.JobPauseParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FineTuningJob fineTuningJob = client.fineTuning().jobs().pause(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfine_tuning_job = openai.fine_tuning.jobs.pause(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\nputs(fine_tuning_job)" + } + } + }, + "description": "Pause a fine-tune job.\n" + } + }, + "/fine_tuning/jobs/{fine_tuning_job_id}/resume": { + "post": { + "operationId": "resumeFineTuningJob", + "tags": [ + "Fine-tuning" + ], + "summary": "Resume fine-tuning", + "parameters": [ + { + "in": "path", + "name": "fine_tuning_job_id", + "required": true, + "schema": { + "type": "string", + "example": "ft-AF1WoRqd3aJAHsqc9NY7iL8F" + }, + "description": "The ID of the fine-tuning job to resume.\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FineTuningJob" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Resume fine-tuning", + "group": "fine-tuning", + "returns": "The resumed [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object.", + "examples": { + "response": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"created_at\": 1721764800,\n \"fine_tuned_model\": null,\n \"organization_id\": \"org-123\",\n \"result_files\": [],\n \"status\": \"queued\",\n \"validation_file\": \"file-abc123\",\n \"training_file\": \"file-abc123\"\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/resume \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nfine_tuning_job = client.fine_tuning.jobs.resume(\n \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n)\nprint(fine_tuning_job.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst fineTuningJob = await client.fineTuning.jobs.resume('ft-AF1WoRqd3aJAHsqc9NY7iL8F');\n\nconsole.log(fineTuningJob.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n fineTuningJob, err := client.FineTuning.Jobs.Resume(context.TODO(), \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.finetuning.jobs.FineTuningJob;\nimport com.openai.models.finetuning.jobs.JobResumeParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FineTuningJob fineTuningJob = client.fineTuning().jobs().resume(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nfine_tuning_job = openai.fine_tuning.jobs.resume(\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\nputs(fine_tuning_job)" + } + } + }, + "description": "Resume a fine-tune job.\n" + } + }, + "/images/edits": { + "post": { + "operationId": "createImageEdit", + "tags": [ + "Images" + ], + "summary": "Create image edit", + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/CreateImageEditRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ImagesResponse" + } + }, + "text/event-stream": { + "schema": { + "$ref": "#/components/schemas/ImageEditStreamEvent" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create image edit", + "group": "images", + "returns": "Returns an [image](https://platform.openai.com/docs/api-reference/images/object) object.", + "examples": [ + { + "title": "Edit image", + "request": { + "curl": "curl -s -D >(grep -i x-request-id >&2) \\\n -o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \\\n -X POST \"https://api.openai.com/v1/images/edits\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -F \"model=gpt-image-1\" \\\n -F \"image[]=@body-lotion.png\" \\\n -F \"image[]=@bath-bomb.png\" \\\n -F \"image[]=@incense-kit.png\" \\\n -F \"image[]=@soap.png\" \\\n -F 'prompt=Create a lovely gift basket with these four items in it'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nimages_response = client.images.edit(\n image=b\"raw file contents\",\n prompt=\"A cute baby sea otter wearing a beret\",\n)\nprint(images_response)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst imagesResponse = await client.images.edit({\n image: fs.createReadStream('path/to/file'),\n prompt: 'A cute baby sea otter wearing a beret',\n});\n\nconsole.log(imagesResponse);", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n imagesResponse, err := client.Images.Edit(context.TODO(), openai.ImageEditParams{\n Image: openai.ImageEditParamsImageUnion{\n OfFile: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n },\n Prompt: \"A cute baby sea otter wearing a beret\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", imagesResponse)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.images.ImageEditParams;\nimport com.openai.models.images.ImagesResponse;\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ImageEditParams params = ImageEditParams.builder()\n .image(ByteArrayInputStream(\"some content\".getBytes()))\n .prompt(\"A cute baby sea otter wearing a beret\")\n .build();\n ImagesResponse imagesResponse = client.images().edit(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nimages_response = openai.images.edit(image: Pathname(__FILE__), prompt: \"A cute baby sea otter wearing a beret\")\n\nputs(images_response)" + } + }, + { + "title": "Streaming", + "request": { + "curl": "curl -s -N -X POST \"https://api.openai.com/v1/images/edits\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -F \"model=gpt-image-1\" \\\n -F \"image[]=@body-lotion.png\" \\\n -F \"image[]=@bath-bomb.png\" \\\n -F \"image[]=@incense-kit.png\" \\\n -F \"image[]=@soap.png\" \\\n -F 'prompt=Create a lovely gift basket with these four items in it' \\\n -F \"stream=true\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nimages_response = client.images.edit(\n image=b\"raw file contents\",\n prompt=\"A cute baby sea otter wearing a beret\",\n)\nprint(images_response)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst imagesResponse = await client.images.edit({\n image: fs.createReadStream('path/to/file'),\n prompt: 'A cute baby sea otter wearing a beret',\n});\n\nconsole.log(imagesResponse);", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n imagesResponse, err := client.Images.Edit(context.TODO(), openai.ImageEditParams{\n Image: openai.ImageEditParamsImageUnion{\n OfFile: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n },\n Prompt: \"A cute baby sea otter wearing a beret\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", imagesResponse)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.images.ImageEditParams;\nimport com.openai.models.images.ImagesResponse;\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ImageEditParams params = ImageEditParams.builder()\n .image(ByteArrayInputStream(\"some content\".getBytes()))\n .prompt(\"A cute baby sea otter wearing a beret\")\n .build();\n ImagesResponse imagesResponse = client.images().edit(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nimages_response = openai.images.edit(image: Pathname(__FILE__), prompt: \"A cute baby sea otter wearing a beret\")\n\nputs(images_response)" + }, + "response": "event: image_edit.partial_image\ndata: {\"type\":\"image_edit.partial_image\",\"b64_json\":\"...\",\"partial_image_index\":0}\n\nevent: image_edit.completed\ndata: {\"type\":\"image_edit.completed\",\"b64_json\":\"...\",\"usage\":{\"total_tokens\":100,\"input_tokens\":50,\"output_tokens\":50,\"input_tokens_details\":{\"text_tokens\":10,\"image_tokens\":40}}}\n" + } + ] + }, + "description": "Creates an edited or extended image given one or more source images and a prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`." + } + }, + "/images/generations": { + "post": { + "operationId": "createImage", + "tags": [ + "Images" + ], + "summary": "Create image", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateImageRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ImagesResponse" + } + }, + "text/event-stream": { + "schema": { + "$ref": "#/components/schemas/ImageGenStreamEvent" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create image", + "group": "images", + "returns": "Returns an [image](https://platform.openai.com/docs/api-reference/images/object) object.", + "examples": [ + { + "title": "Generate image", + "request": { + "curl": "curl https://api.openai.com/v1/images/generations \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"gpt-image-1\",\n \"prompt\": \"A cute baby sea otter\",\n \"n\": 1,\n \"size\": \"1024x1024\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nimages_response = client.images.generate(\n prompt=\"A cute baby sea otter\",\n)\nprint(images_response)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst imagesResponse = await client.images.generate({ prompt: 'A cute baby sea otter' });\n\nconsole.log(imagesResponse);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n imagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{\n Prompt: \"A cute baby sea otter\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", imagesResponse)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.images.ImageGenerateParams;\nimport com.openai.models.images.ImagesResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ImageGenerateParams params = ImageGenerateParams.builder()\n .prompt(\"A cute baby sea otter\")\n .build();\n ImagesResponse imagesResponse = client.images().generate(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nimages_response = openai.images.generate(prompt: \"A cute baby sea otter\")\n\nputs(images_response)" + }, + "response": "{\n \"created\": 1713833628,\n \"data\": [\n {\n \"b64_json\": \"...\"\n }\n ],\n \"usage\": {\n \"total_tokens\": 100,\n \"input_tokens\": 50,\n \"output_tokens\": 50,\n \"input_tokens_details\": {\n \"text_tokens\": 10,\n \"image_tokens\": 40\n }\n }\n}\n" + }, + { + "title": "Streaming", + "request": { + "curl": "curl https://api.openai.com/v1/images/generations \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"gpt-image-1\",\n \"prompt\": \"A cute baby sea otter\",\n \"n\": 1,\n \"size\": \"1024x1024\",\n \"stream\": true\n }' \\\n --no-buffer\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nimages_response = client.images.generate(\n prompt=\"A cute baby sea otter\",\n)\nprint(images_response)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst imagesResponse = await client.images.generate({ prompt: 'A cute baby sea otter' });\n\nconsole.log(imagesResponse);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n imagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{\n Prompt: \"A cute baby sea otter\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", imagesResponse)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.images.ImageGenerateParams;\nimport com.openai.models.images.ImagesResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ImageGenerateParams params = ImageGenerateParams.builder()\n .prompt(\"A cute baby sea otter\")\n .build();\n ImagesResponse imagesResponse = client.images().generate(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nimages_response = openai.images.generate(prompt: \"A cute baby sea otter\")\n\nputs(images_response)" + }, + "response": "event: image_generation.partial_image\ndata: {\"type\":\"image_generation.partial_image\",\"b64_json\":\"...\",\"partial_image_index\":0}\n\nevent: image_generation.completed\ndata: {\"type\":\"image_generation.completed\",\"b64_json\":\"...\",\"usage\":{\"total_tokens\":100,\"input_tokens\":50,\"output_tokens\":50,\"input_tokens_details\":{\"text_tokens\":10,\"image_tokens\":40}}}\n" + } + ] + }, + "description": "Creates an image given a prompt. [Learn more](https://platform.openai.com/docs/guides/images).\n" + } + }, + "/images/variations": { + "post": { + "operationId": "createImageVariation", + "tags": [ + "Images" + ], + "summary": "Create image variation", + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/CreateImageVariationRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ImagesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create image variation", + "group": "images", + "returns": "Returns a list of [image](https://platform.openai.com/docs/api-reference/images/object) objects.", + "examples": { + "response": "{\n \"created\": 1589478378,\n \"data\": [\n {\n \"url\": \"https://...\"\n },\n {\n \"url\": \"https://...\"\n }\n ]\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/images/variations \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -F image=\"@otter.png\" \\\n -F n=2 \\\n -F size=\"1024x1024\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nimages_response = client.images.create_variation(\n image=b\"raw file contents\",\n)\nprint(images_response.created)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst imagesResponse = await client.images.createVariation({ image: fs.createReadStream('otter.png') });\n\nconsole.log(imagesResponse.created);", + "csharp": "using System;\n\nusing OpenAI.Images;\n\nImageClient client = new(\n model: \"dall-e-2\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nGeneratedImage image = client.GenerateImageVariation(imageFilePath: \"otter.png\");\n\nConsole.WriteLine(image.ImageUri);\n", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n imagesResponse, err := client.Images.NewVariation(context.TODO(), openai.ImageNewVariationParams{\n Image: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", imagesResponse.Created)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.images.ImageCreateVariationParams;\nimport com.openai.models.images.ImagesResponse;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ImageCreateVariationParams params = ImageCreateVariationParams.builder()\n .image(ByteArrayInputStream(\"some content\".getBytes()))\n .build();\n ImagesResponse imagesResponse = client.images().createVariation(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nimages_response = openai.images.create_variation(image: Pathname(__FILE__))\n\nputs(images_response)" + } + } + }, + "description": "Creates a variation of a given image. This endpoint only supports `dall-e-2`." + } + }, + "/models": { + "get": { + "operationId": "listModels", + "tags": [ + "Models" + ], + "summary": "List models", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListModelsResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List models", + "group": "models", + "returns": "A list of [model](https://platform.openai.com/docs/api-reference/models/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"model-id-0\",\n \"object\": \"model\",\n \"created\": 1686935002,\n \"owned_by\": \"organization-owner\"\n },\n {\n \"id\": \"model-id-1\",\n \"object\": \"model\",\n \"created\": 1686935002,\n \"owned_by\": \"organization-owner\",\n },\n {\n \"id\": \"model-id-2\",\n \"object\": \"model\",\n \"created\": 1686935002,\n \"owned_by\": \"openai\"\n },\n ],\n \"object\": \"list\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/models \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.models.list()\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const model of client.models.list()) {\n console.log(model.id);\n}", + "csharp": "using System;\n\nusing OpenAI.Models;\n\nOpenAIModelClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nforeach (var model in client.GetModels().Value)\n{\n Console.WriteLine(model.Id);\n}\n", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Models.List(context.TODO())\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.models.ModelListPage;\nimport com.openai.models.models.ModelListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ModelListPage page = client.models().list();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.models.list\n\nputs(page)" + } + } + }, + "description": "Lists the currently available models, and provides basic information about each one such as the owner and availability." + } + }, + "/models/{model}": { + "get": { + "operationId": "retrieveModel", + "tags": [ + "Models" + ], + "summary": "Retrieve model", + "parameters": [ + { + "in": "path", + "name": "model", + "required": true, + "schema": { + "type": "string", + "example": "gpt-4o-mini" + }, + "description": "The ID of the model to use for this request" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Model" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve model", + "group": "models", + "returns": "The [model](https://platform.openai.com/docs/api-reference/models/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"VAR_chat_model_id\",\n \"object\": \"model\",\n \"created\": 1686935002,\n \"owned_by\": \"openai\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/models/VAR_chat_model_id \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nmodel = client.models.retrieve(\n \"gpt-4o-mini\",\n)\nprint(model.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst model = await client.models.retrieve('gpt-4o-mini');\n\nconsole.log(model.id);", + "csharp": "using System;\nusing System.ClientModel;\n\nusing OpenAI.Models;\n\n OpenAIModelClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nClientResult model = client.GetModel(\"babbage-002\");\nConsole.WriteLine(model.Value.Id);\n", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n model, err := client.Models.Get(context.TODO(), \"gpt-4o-mini\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", model.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.models.Model;\nimport com.openai.models.models.ModelRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Model model = client.models().retrieve(\"gpt-4o-mini\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nmodel = openai.models.retrieve(\"gpt-4o-mini\")\n\nputs(model)" + } + } + }, + "description": "Retrieves a model instance, providing basic information about the model such as the owner and permissioning." + }, + "delete": { + "operationId": "deleteModel", + "tags": [ + "Models" + ], + "summary": "Delete a fine-tuned model", + "parameters": [ + { + "in": "path", + "name": "model", + "required": true, + "schema": { + "type": "string", + "example": "ft:gpt-4o-mini:acemeco:suffix:abc123" + }, + "description": "The model to delete" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteModelResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete a fine-tuned model", + "group": "models", + "returns": "Deletion status.", + "examples": { + "response": "{\n \"id\": \"ft:gpt-4o-mini:acemeco:suffix:abc123\",\n \"object\": \"model\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/models/ft:gpt-4o-mini:acemeco:suffix:abc123 \\\n -X DELETE \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nmodel_deleted = client.models.delete(\n \"ft:gpt-4o-mini:acemeco:suffix:abc123\",\n)\nprint(model_deleted.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst modelDeleted = await client.models.delete('ft:gpt-4o-mini:acemeco:suffix:abc123');\n\nconsole.log(modelDeleted.id);", + "csharp": "using System;\nusing System.ClientModel;\n\nusing OpenAI.Models;\n\nOpenAIModelClient client = new(\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nClientResult success = client.DeleteModel(\"ft:gpt-4o-mini:acemeco:suffix:abc123\");\nConsole.WriteLine(success);\n", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n modelDeleted, err := client.Models.Delete(context.TODO(), \"ft:gpt-4o-mini:acemeco:suffix:abc123\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", modelDeleted.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.models.ModelDeleteParams;\nimport com.openai.models.models.ModelDeleted;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ModelDeleted modelDeleted = client.models().delete(\"ft:gpt-4o-mini:acemeco:suffix:abc123\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nmodel_deleted = openai.models.delete(\"ft:gpt-4o-mini:acemeco:suffix:abc123\")\n\nputs(model_deleted)" + } + } + }, + "description": "Delete a fine-tuned model. You must have the Owner role in your organization to delete a model." + } + }, + "/moderations": { + "post": { + "operationId": "createModeration", + "tags": [ + "Moderations" + ], + "summary": "Create moderation", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateModerationRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateModerationResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create moderation", + "group": "moderations", + "returns": "A [moderation](https://platform.openai.com/docs/api-reference/moderations/object) object.", + "examples": [ + { + "title": "Single string", + "request": { + "curl": "curl https://api.openai.com/v1/moderations \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"input\": \"I want to kill them.\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nmoderation = client.moderations.create(\n input=\"I want to kill them.\",\n)\nprint(moderation.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst moderation = await client.moderations.create({ input: 'I want to kill them.' });\n\nconsole.log(moderation.id);", + "csharp": "using System;\nusing System.ClientModel;\n\nusing OpenAI.Moderations;\n\nModerationClient client = new(\n model: \"omni-moderation-latest\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nClientResult moderation = client.ClassifyText(\"I want to kill them.\");\n", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n moderation, err := client.Moderations.New(context.TODO(), openai.ModerationNewParams{\n Input: openai.ModerationNewParamsInputUnion{\n OfString: openai.String(\"I want to kill them.\"),\n },\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", moderation.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.moderations.ModerationCreateParams;\nimport com.openai.models.moderations.ModerationCreateResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ModerationCreateParams params = ModerationCreateParams.builder()\n .input(\"I want to kill them.\")\n .build();\n ModerationCreateResponse moderation = client.moderations().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nmoderation = openai.moderations.create(input: \"I want to kill them.\")\n\nputs(moderation)" + }, + "response": "{\n \"id\": \"modr-AB8CjOTu2jiq12hp1AQPfeqFWaORR\",\n \"model\": \"text-moderation-007\",\n \"results\": [\n {\n \"flagged\": true,\n \"categories\": {\n \"sexual\": false,\n \"hate\": false,\n \"harassment\": true,\n \"self-harm\": false,\n \"sexual/minors\": false,\n \"hate/threatening\": false,\n \"violence/graphic\": false,\n \"self-harm/intent\": false,\n \"self-harm/instructions\": false,\n \"harassment/threatening\": true,\n \"violence\": true\n },\n \"category_scores\": {\n \"sexual\": 0.000011726012417057063,\n \"hate\": 0.22706663608551025,\n \"harassment\": 0.5215635299682617,\n \"self-harm\": 2.227119921371923e-6,\n \"sexual/minors\": 7.107352217872176e-8,\n \"hate/threatening\": 0.023547329008579254,\n \"violence/graphic\": 0.00003391829886822961,\n \"self-harm/intent\": 1.646940972932498e-6,\n \"self-harm/instructions\": 1.1198755256458526e-9,\n \"harassment/threatening\": 0.5694745779037476,\n \"violence\": 0.9971134662628174\n }\n }\n ]\n}\n" + }, + { + "title": "Image and text", + "request": { + "curl": "curl https://api.openai.com/v1/moderations \\\n -X POST \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"omni-moderation-latest\",\n \"input\": [\n { \"type\": \"text\", \"text\": \"...text to classify goes here...\" },\n {\n \"type\": \"image_url\",\n \"image_url\": {\n \"url\": \"https://example.com/image.png\"\n }\n }\n ]\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nmoderation = client.moderations.create(\n input=\"I want to kill them.\",\n)\nprint(moderation.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst moderation = await client.moderations.create({ input: 'I want to kill them.' });\n\nconsole.log(moderation.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n moderation, err := client.Moderations.New(context.TODO(), openai.ModerationNewParams{\n Input: openai.ModerationNewParamsInputUnion{\n OfString: openai.String(\"I want to kill them.\"),\n },\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", moderation.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.moderations.ModerationCreateParams;\nimport com.openai.models.moderations.ModerationCreateResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ModerationCreateParams params = ModerationCreateParams.builder()\n .input(\"I want to kill them.\")\n .build();\n ModerationCreateResponse moderation = client.moderations().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nmoderation = openai.moderations.create(input: \"I want to kill them.\")\n\nputs(moderation)" + }, + "response": "{\n \"id\": \"modr-0d9740456c391e43c445bf0f010940c7\",\n \"model\": \"omni-moderation-latest\",\n \"results\": [\n {\n \"flagged\": true,\n \"categories\": {\n \"harassment\": true,\n \"harassment/threatening\": true,\n \"sexual\": false,\n \"hate\": false,\n \"hate/threatening\": false,\n \"illicit\": false,\n \"illicit/violent\": false,\n \"self-harm/intent\": false,\n \"self-harm/instructions\": false,\n \"self-harm\": false,\n \"sexual/minors\": false,\n \"violence\": true,\n \"violence/graphic\": true\n },\n \"category_scores\": {\n \"harassment\": 0.8189693396524255,\n \"harassment/threatening\": 0.804985420696006,\n \"sexual\": 1.573112165348997e-6,\n \"hate\": 0.007562942636942845,\n \"hate/threatening\": 0.004208854591835476,\n \"illicit\": 0.030535955153511665,\n \"illicit/violent\": 0.008925306722380033,\n \"self-harm/intent\": 0.00023023930975076432,\n \"self-harm/instructions\": 0.0002293869201073356,\n \"self-harm\": 0.012598046106750154,\n \"sexual/minors\": 2.212566909570261e-8,\n \"violence\": 0.9999992735124786,\n \"violence/graphic\": 0.843064871157054\n },\n \"category_applied_input_types\": {\n \"harassment\": [\n \"text\"\n ],\n \"harassment/threatening\": [\n \"text\"\n ],\n \"sexual\": [\n \"text\",\n \"image\"\n ],\n \"hate\": [\n \"text\"\n ],\n \"hate/threatening\": [\n \"text\"\n ],\n \"illicit\": [\n \"text\"\n ],\n \"illicit/violent\": [\n \"text\"\n ],\n \"self-harm/intent\": [\n \"text\",\n \"image\"\n ],\n \"self-harm/instructions\": [\n \"text\",\n \"image\"\n ],\n \"self-harm\": [\n \"text\",\n \"image\"\n ],\n \"sexual/minors\": [\n \"text\"\n ],\n \"violence\": [\n \"text\",\n \"image\"\n ],\n \"violence/graphic\": [\n \"text\",\n \"image\"\n ]\n }\n }\n ]\n}\n" + } + ] + }, + "description": "Classifies if text and/or image inputs are potentially harmful. Learn\nmore in the [moderation guide](https://platform.openai.com/docs/guides/moderation).\n" + } + }, + "/organization/admin_api_keys": { + "get": { + "summary": "List all organization and project API keys.", + "operationId": "admin-api-keys-list", + "description": "List organization API keys", + "parameters": [ + { + "in": "query", + "name": "after", + "required": false, + "schema": { + "type": "string", + "nullable": true, + "description": "Return keys with IDs that come after this ID in the pagination order." + } + }, + { + "in": "query", + "name": "order", + "required": false, + "schema": { + "type": "string", + "enum": [ + "asc", + "desc" + ], + "default": "asc", + "description": "Order results by creation time, ascending or descending." + } + }, + { + "in": "query", + "name": "limit", + "required": false, + "schema": { + "type": "integer", + "default": 20, + "description": "Maximum number of keys to return." + } + } + ], + "responses": { + "200": { + "description": "A list of organization API keys.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiKeyList" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List all organization and project API keys.", + "group": "administration", + "returns": "A list of admin and project API key objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"organization.admin_api_key\",\n \"id\": \"key_abc\",\n \"name\": \"Main Admin Key\",\n \"redacted_value\": \"sk-admin...def\",\n \"created_at\": 1711471533,\n \"last_used_at\": 1711471534,\n \"owner\": {\n \"type\": \"service_account\",\n \"object\": \"organization.service_account\",\n \"id\": \"sa_456\",\n \"name\": \"My Service Account\",\n \"created_at\": 1711471533,\n \"role\": \"member\"\n }\n }\n ],\n \"first_id\": \"key_abc\",\n \"last_id\": \"key_abc\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/admin_api_keys?after=key_abc&limit=20 \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + } + }, + "post": { + "summary": "Create admin API key", + "operationId": "admin-api-keys-create", + "description": "Create an organization admin API key", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "example": "New Admin Key" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The newly created admin API key.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdminApiKey" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create admin API key", + "group": "administration", + "returns": "The created [AdminApiKey](https://platform.openai.com/docs/api-reference/admin-api-keys/object) object.", + "examples": { + "response": "{\n \"object\": \"organization.admin_api_key\",\n \"id\": \"key_xyz\",\n \"name\": \"New Admin Key\",\n \"redacted_value\": \"sk-admin...xyz\",\n \"created_at\": 1711471533,\n \"last_used_at\": 1711471534,\n \"owner\": {\n \"type\": \"user\",\n \"object\": \"organization.user\",\n \"id\": \"user_123\",\n \"name\": \"John Doe\",\n \"created_at\": 1711471533,\n \"role\": \"owner\"\n },\n \"value\": \"sk-admin-1234abcd\"\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/admin_api_keys \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"New Admin Key\"\n }'\n" + } + } + } + } + }, + "/organization/admin_api_keys/{key_id}": { + "get": { + "summary": "Retrieve admin API key", + "operationId": "admin-api-keys-get", + "description": "Retrieve a single organization API key", + "parameters": [ + { + "in": "path", + "name": "key_id", + "required": true, + "schema": { + "type": "string", + "description": "The ID of the API key." + } + } + ], + "responses": { + "200": { + "description": "Details of the requested API key.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdminApiKey" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve admin API key", + "group": "administration", + "returns": "The requested [AdminApiKey](https://platform.openai.com/docs/api-reference/admin-api-keys/object) object.", + "examples": { + "response": "{\n \"object\": \"organization.admin_api_key\",\n \"id\": \"key_abc\",\n \"name\": \"Main Admin Key\",\n \"redacted_value\": \"sk-admin...xyz\",\n \"created_at\": 1711471533,\n \"last_used_at\": 1711471534,\n \"owner\": {\n \"type\": \"user\",\n \"object\": \"organization.user\",\n \"id\": \"user_123\",\n \"name\": \"John Doe\",\n \"created_at\": 1711471533,\n \"role\": \"owner\"\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/admin_api_keys/key_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + } + }, + "delete": { + "summary": "Delete admin API key", + "operationId": "admin-api-keys-delete", + "description": "Delete an organization admin API key", + "parameters": [ + { + "in": "path", + "name": "key_id", + "required": true, + "schema": { + "type": "string", + "description": "The ID of the API key to be deleted." + } + } + ], + "responses": { + "200": { + "description": "Confirmation that the API key was deleted.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string", + "example": "key_abc" + }, + "object": { + "type": "string", + "example": "organization.admin_api_key.deleted" + }, + "deleted": { + "type": "boolean", + "example": true + } + } + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete admin API key", + "group": "administration", + "returns": "A confirmation object indicating the key was deleted.", + "examples": { + "response": "{\n \"id\": \"key_abc\",\n \"object\": \"organization.admin_api_key.deleted\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/organization/admin_api_keys/key_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + } + } + }, + "/organization/audit_logs": { + "get": { + "summary": "List audit logs", + "operationId": "list-audit-logs", + "tags": [ + "Audit Logs" + ], + "parameters": [ + { + "name": "effective_at", + "in": "query", + "description": "Return only events whose `effective_at` (Unix seconds) is in this range.", + "required": false, + "schema": { + "type": "object", + "properties": { + "gt": { + "type": "integer", + "description": "Return only events whose `effective_at` (Unix seconds) is greater than this value." + }, + "gte": { + "type": "integer", + "description": "Return only events whose `effective_at` (Unix seconds) is greater than or equal to this value." + }, + "lt": { + "type": "integer", + "description": "Return only events whose `effective_at` (Unix seconds) is less than this value." + }, + "lte": { + "type": "integer", + "description": "Return only events whose `effective_at` (Unix seconds) is less than or equal to this value." + } + } + } + }, + { + "name": "project_ids[]", + "in": "query", + "description": "Return only events for these projects.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "event_types[]", + "in": "query", + "description": "Return only events with a `type` in one of these values. For example, `project.created`. For all options, see the documentation for the [audit log object](https://platform.openai.com/docs/api-reference/audit-logs/object).", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AuditLogEventType" + } + } + }, + { + "name": "actor_ids[]", + "in": "query", + "description": "Return only events performed by these actors. Can be a user ID, a service account ID, or an api key tracking ID.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "actor_emails[]", + "in": "query", + "description": "Return only events performed by users with these emails.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "resource_ids[]", + "in": "query", + "description": "Return only events performed on these targets. For example, a project ID updated.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "before", + "in": "query", + "description": "A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.\n", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Audit logs listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListAuditLogsResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List audit logs", + "group": "audit-logs", + "returns": "A list of paginated [Audit Log](https://platform.openai.com/docs/api-reference/audit-logs/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"audit_log-xxx_yyyymmdd\",\n \"type\": \"project.archived\",\n \"effective_at\": 1722461446,\n \"actor\": {\n \"type\": \"api_key\",\n \"api_key\": {\n \"type\": \"user\",\n \"user\": {\n \"id\": \"user-xxx\",\n \"email\": \"user@example.com\"\n }\n }\n },\n \"project.archived\": {\n \"id\": \"proj_abc\"\n },\n },\n {\n \"id\": \"audit_log-yyy__20240101\",\n \"type\": \"api_key.updated\",\n \"effective_at\": 1720804190,\n \"actor\": {\n \"type\": \"session\",\n \"session\": {\n \"user\": {\n \"id\": \"user-xxx\",\n \"email\": \"user@example.com\"\n },\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\",\n \"ja3\": \"a497151ce4338a12c4418c44d375173e\",\n \"ja4\": \"q13d0313h3_55b375c5d22e_c7319ce65786\",\n \"ip_address_details\": {\n \"country\": \"US\",\n \"city\": \"San Francisco\",\n \"region\": \"California\",\n \"region_code\": \"CA\",\n \"asn\": \"1234\",\n \"latitude\": \"37.77490\",\n \"longitude\": \"-122.41940\"\n }\n }\n },\n \"api_key.updated\": {\n \"id\": \"key_xxxx\",\n \"data\": {\n \"scopes\": [\"resource_2.operation_2\"]\n }\n },\n }\n ],\n \"first_id\": \"audit_log-xxx__20240101\",\n \"last_id\": \"audit_log_yyy__20240101\",\n \"has_more\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/audit_logs \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\"\n" + } + } + }, + "description": "List user actions and configuration changes within this organization." + } + }, + "/organization/certificates": { + "get": { + "summary": "List organization certificates", + "operationId": "listOrganizationCertificates", + "tags": [ + "Certificates" + ], + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + } + ], + "responses": { + "200": { + "description": "Certificates listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListCertificatesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List organization certificates", + "group": "administration", + "returns": "A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects.", + "examples": { + "request": { + "curl": "curl https://api.openai.com/v1/organization/certificates \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\"\n" + }, + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"organization.certificate\",\n \"id\": \"cert_abc\",\n \"name\": \"My Example Certificate\",\n \"active\": true,\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n },\n ],\n \"first_id\": \"cert_abc\",\n \"last_id\": \"cert_abc\",\n \"has_more\": false\n}\n" + } + }, + "description": "List uploaded certificates for this organization." + }, + "post": { + "summary": "Upload certificate", + "operationId": "uploadCertificate", + "tags": [ + "Certificates" + ], + "requestBody": { + "description": "The certificate upload payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UploadCertificateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Certificate uploaded successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Certificate" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Upload certificate", + "group": "administration", + "returns": "A single [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object.", + "examples": { + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/certificates \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\" \\\n-d '{\n \"name\": \"My Example Certificate\",\n \"certificate\": \"-----BEGIN CERTIFICATE-----\\\\nMIIDeT...\\\\n-----END CERTIFICATE-----\"\n}'\n" + }, + "response": "{\n \"object\": \"certificate\",\n \"id\": \"cert_abc\",\n \"name\": \"My Example Certificate\",\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n}\n" + } + }, + "description": "Upload a certificate to the organization. This does **not** automatically activate the certificate.\n\nOrganizations can upload up to 50 certificates.\n" + } + }, + "/organization/certificates/activate": { + "post": { + "summary": "Activate certificates for organization", + "operationId": "activateOrganizationCertificates", + "tags": [ + "Certificates" + ], + "requestBody": { + "description": "The certificate activation payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ToggleCertificatesRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Certificates activated successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListCertificatesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Activate certificates for organization", + "group": "administration", + "returns": "A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were activated.", + "examples": { + "request": { + "curl": "curl https://api.openai.com/v1/organization/certificates/activate \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\" \\\n-d '{\n \"data\": [\"cert_abc\", \"cert_def\"]\n}'\n" + }, + "response": "{\n \"object\": \"organization.certificate.activation\",\n \"data\": [\n {\n \"object\": \"organization.certificate\",\n \"id\": \"cert_abc\",\n \"name\": \"My Example Certificate\",\n \"active\": true,\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n },\n {\n \"object\": \"organization.certificate\",\n \"id\": \"cert_def\",\n \"name\": \"My Example Certificate 2\",\n \"active\": true,\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n },\n ],\n}\n" + } + }, + "description": "Activate certificates at the organization level.\n\nYou can atomically and idempotently activate up to 10 certificates at a time.\n" + } + }, + "/organization/certificates/deactivate": { + "post": { + "summary": "Deactivate certificates for organization", + "operationId": "deactivateOrganizationCertificates", + "tags": [ + "Certificates" + ], + "requestBody": { + "description": "The certificate deactivation payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ToggleCertificatesRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Certificates deactivated successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListCertificatesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Deactivate certificates for organization", + "group": "administration", + "returns": "A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were deactivated.", + "examples": { + "request": { + "curl": "curl https://api.openai.com/v1/organization/certificates/deactivate \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\" \\\n-d '{\n \"data\": [\"cert_abc\", \"cert_def\"]\n}'\n" + }, + "response": "{\n \"object\": \"organization.certificate.deactivation\",\n \"data\": [\n {\n \"object\": \"organization.certificate\",\n \"id\": \"cert_abc\",\n \"name\": \"My Example Certificate\",\n \"active\": false,\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n },\n {\n \"object\": \"organization.certificate\",\n \"id\": \"cert_def\",\n \"name\": \"My Example Certificate 2\",\n \"active\": false,\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n },\n ],\n}\n" + } + }, + "description": "Deactivate certificates at the organization level.\n\nYou can atomically and idempotently deactivate up to 10 certificates at a time.\n" + } + }, + "/organization/certificates/{certificate_id}": { + "get": { + "summary": "Get certificate", + "operationId": "getCertificate", + "tags": [ + "Certificates" + ], + "parameters": [ + { + "name": "certificate_id", + "in": "path", + "description": "Unique ID of the certificate to retrieve.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "include", + "in": "query", + "description": "A list of additional fields to include in the response. Currently the only supported value is `content` to fetch the PEM content of the certificate.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "content" + ] + } + } + } + ], + "responses": { + "200": { + "description": "Certificate retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Certificate" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Get certificate", + "group": "administration", + "returns": "A single [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object.", + "examples": { + "request": { + "curl": "curl \"https://api.openai.com/v1/organization/certificates/cert_abc?include[]=content\" \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\"\n" + }, + "response": "{\n \"object\": \"certificate\",\n \"id\": \"cert_abc\",\n \"name\": \"My Example Certificate\",\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 1234567,\n \"expires_at\": 12345678,\n \"content\": \"-----BEGIN CERTIFICATE-----MIIDeT...-----END CERTIFICATE-----\"\n }\n}\n" + } + }, + "description": "Get a certificate that has been uploaded to the organization.\n\nYou can get a certificate regardless of whether it is active or not.\n" + }, + "post": { + "summary": "Modify certificate", + "operationId": "modifyCertificate", + "tags": [ + "Certificates" + ], + "requestBody": { + "description": "The certificate modification payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ModifyCertificateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Certificate modified successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Certificate" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Modify certificate", + "group": "administration", + "returns": "The updated [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object.", + "examples": { + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/certificates/cert_abc \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\" \\\n-d '{\n \"name\": \"Renamed Certificate\"\n}'\n" + }, + "response": "{\n \"object\": \"certificate\",\n \"id\": \"cert_abc\",\n \"name\": \"Renamed Certificate\",\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n}\n" + } + }, + "description": "Modify a certificate. Note that only the name can be modified.\n" + }, + "delete": { + "summary": "Delete certificate", + "operationId": "deleteCertificate", + "tags": [ + "Certificates" + ], + "responses": { + "200": { + "description": "Certificate deleted successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteCertificateResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete certificate", + "group": "administration", + "returns": "A confirmation object indicating the certificate was deleted.", + "examples": { + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/organization/certificates/cert_abc \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\"\n" + }, + "response": "{\n \"object\": \"certificate.deleted\",\n \"id\": \"cert_abc\"\n}\n" + } + }, + "description": "Delete a certificate from the organization.\n\nThe certificate must be inactive for the organization and all projects.\n" + } + }, + "/organization/costs": { + "get": { + "summary": "Costs", + "operationId": "usage-costs", + "tags": [ + "Usage" + ], + "parameters": [ + { + "name": "start_time", + "in": "query", + "description": "Start time (Unix seconds) of the query time range, inclusive.", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "end_time", + "in": "query", + "description": "End time (Unix seconds) of the query time range, exclusive.", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "bucket_width", + "in": "query", + "description": "Width of each time bucket in response. Currently only `1d` is supported, default to `1d`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "1d" + ], + "default": "1d" + } + }, + { + "name": "project_ids", + "in": "query", + "description": "Return only costs for these projects.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "group_by", + "in": "query", + "description": "Group the costs by the specified fields. Support fields include `project_id`, `line_item` and any combination of them.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "project_id", + "line_item" + ] + } + } + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of buckets to be returned. Limit can range between 1 and 180, and the default is 7.\n", + "required": false, + "schema": { + "type": "integer", + "default": 7 + } + }, + { + "name": "page", + "in": "query", + "description": "A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Costs data retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UsageResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Costs", + "group": "usage-costs", + "returns": "A list of paginated, time bucketed [Costs](https://platform.openai.com/docs/api-reference/usage/costs_object) objects.", + "examples": { + "response": "{\n \"object\": \"page\",\n \"data\": [\n {\n \"object\": \"bucket\",\n \"start_time\": 1730419200,\n \"end_time\": 1730505600,\n \"results\": [\n {\n \"object\": \"organization.costs.result\",\n \"amount\": {\n \"value\": 0.06,\n \"currency\": \"usd\"\n },\n \"line_item\": null,\n \"project_id\": null\n }\n ]\n }\n ],\n \"has_more\": false,\n \"next_page\": null\n}\n", + "request": { + "curl": "curl \"https://api.openai.com/v1/organization/costs?start_time=1730419200&limit=1\" \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Get costs details for the organization." + } + }, + "/organization/invites": { + "get": { + "summary": "List invites", + "operationId": "list-invites", + "tags": [ + "Invites" + ], + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Invites listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InviteListResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List invites", + "group": "administration", + "returns": "A list of [Invite](https://platform.openai.com/docs/api-reference/invite/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"organization.invite\",\n \"id\": \"invite-abc\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"status\": \"accepted\",\n \"invited_at\": 1711471533,\n \"expires_at\": 1711471533,\n \"accepted_at\": 1711471533\n }\n ],\n \"first_id\": \"invite-abc\",\n \"last_id\": \"invite-abc\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/invites?after=invite-abc&limit=20 \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Returns a list of invites in the organization." + }, + "post": { + "summary": "Create invite", + "operationId": "inviteUser", + "tags": [ + "Invites" + ], + "requestBody": { + "description": "The invite request payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InviteRequest" + } + } + } + }, + "responses": { + "200": { + "description": "User invited successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Invite" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create invite", + "group": "administration", + "returns": "The created [Invite](https://platform.openai.com/docs/api-reference/invite/object) object.", + "examples": { + "response": "{\n \"object\": \"organization.invite\",\n \"id\": \"invite-def\",\n \"email\": \"anotheruser@example.com\",\n \"role\": \"reader\",\n \"status\": \"pending\",\n \"invited_at\": 1711471533,\n \"expires_at\": 1711471533,\n \"accepted_at\": null,\n \"projects\": [\n {\n \"id\": \"project-xyz\",\n \"role\": \"member\"\n },\n {\n \"id\": \"project-abc\",\n \"role\": \"owner\"\n }\n ]\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/invites \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"email\": \"anotheruser@example.com\",\n \"role\": \"reader\",\n \"projects\": [\n {\n \"id\": \"project-xyz\",\n \"role\": \"member\"\n },\n {\n \"id\": \"project-abc\",\n \"role\": \"owner\"\n }\n ]\n }'\n" + } + } + }, + "description": "Create an invite for a user to the organization. The invite must be accepted by the user before they have access to the organization." + } + }, + "/organization/invites/{invite_id}": { + "get": { + "summary": "Retrieve invite", + "operationId": "retrieve-invite", + "tags": [ + "Invites" + ], + "parameters": [ + { + "in": "path", + "name": "invite_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the invite to retrieve." + } + ], + "responses": { + "200": { + "description": "Invite retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Invite" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve invite", + "group": "administration", + "returns": "The [Invite](https://platform.openai.com/docs/api-reference/invite/object) object matching the specified ID.", + "examples": { + "response": "{\n \"object\": \"organization.invite\",\n \"id\": \"invite-abc\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"status\": \"accepted\",\n \"invited_at\": 1711471533,\n \"expires_at\": 1711471533,\n \"accepted_at\": 1711471533\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/invites/invite-abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Retrieves an invite." + }, + "delete": { + "summary": "Delete invite", + "operationId": "delete-invite", + "tags": [ + "Invites" + ], + "parameters": [ + { + "in": "path", + "name": "invite_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the invite to delete." + } + ], + "responses": { + "200": { + "description": "Invite deleted successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InviteDeleteResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete invite", + "group": "administration", + "returns": "Confirmation that the invite has been deleted", + "examples": { + "response": "{\n \"object\": \"organization.invite.deleted\",\n \"id\": \"invite-abc\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/organization/invites/invite-abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Delete an invite. If the invite has already been accepted, it cannot be deleted." + } + }, + "/organization/projects": { + "get": { + "summary": "List projects", + "operationId": "list-projects", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "include_archived", + "in": "query", + "schema": { + "type": "boolean", + "default": false + }, + "description": "If `true` returns all projects including those that have been `archived`. Archived projects are not included by default." + } + ], + "responses": { + "200": { + "description": "Projects listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectListResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List projects", + "group": "administration", + "returns": "A list of [Project](https://platform.openai.com/docs/api-reference/projects/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"proj_abc\",\n \"object\": \"organization.project\",\n \"name\": \"Project example\",\n \"created_at\": 1711471533,\n \"archived_at\": null,\n \"status\": \"active\"\n }\n ],\n \"first_id\": \"proj-abc\",\n \"last_id\": \"proj-xyz\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects?after=proj_abc&limit=20&include_archived=false \\ -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Returns a list of projects." + }, + "post": { + "summary": "Create project", + "operationId": "create-project", + "tags": [ + "Projects" + ], + "requestBody": { + "description": "The project create request payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectCreateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Project created successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Project" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create project", + "group": "administration", + "returns": "The created [Project](https://platform.openai.com/docs/api-reference/projects/object) object.", + "examples": { + "response": "{\n \"id\": \"proj_abc\",\n \"object\": \"organization.project\",\n \"name\": \"Project ABC\",\n \"created_at\": 1711471533,\n \"archived_at\": null,\n \"status\": \"active\"\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/projects \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"Project ABC\"\n }'\n" + } + } + }, + "description": "Create a new project in the organization. Projects can be created and archived, but cannot be deleted." + } + }, + "/organization/projects/{project_id}": { + "get": { + "summary": "Retrieve project", + "operationId": "retrieve-project", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Project" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve project", + "group": "administration", + "description": "Retrieve a project.", + "returns": "The [Project](https://platform.openai.com/docs/api-reference/projects/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"proj_abc\",\n \"object\": \"organization.project\",\n \"name\": \"Project example\",\n \"created_at\": 1711471533,\n \"archived_at\": null,\n \"status\": \"active\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Retrieves a project." + }, + "post": { + "summary": "Modify project", + "operationId": "modify-project", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "The project update request payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectUpdateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Project updated successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Project" + } + } + } + }, + "400": { + "description": "Error response when updating the default project.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Modify project", + "group": "administration", + "returns": "The updated [Project](https://platform.openai.com/docs/api-reference/projects/object) object.", + "examples": { + "response": "", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/projects/proj_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"Project DEF\"\n }'\n" + } + } + }, + "description": "Modifies a project in the organization." + } + }, + "/organization/projects/{project_id}/api_keys": { + "get": { + "summary": "List project API keys", + "operationId": "list-project-api-keys", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project API keys listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectApiKeyListResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List project API keys", + "group": "administration", + "returns": "A list of [ProjectApiKey](https://platform.openai.com/docs/api-reference/project-api-keys/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"organization.project.api_key\",\n \"redacted_value\": \"sk-abc...def\",\n \"name\": \"My API Key\",\n \"created_at\": 1711471533,\n \"last_used_at\": 1711471534,\n \"id\": \"key_abc\",\n \"owner\": {\n \"type\": \"user\",\n \"user\": {\n \"object\": \"organization.project.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n }\n }\n }\n ],\n \"first_id\": \"key_abc\",\n \"last_id\": \"key_xyz\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys?after=key_abc&limit=20 \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Returns a list of API keys in the project." + } + }, + "/organization/projects/{project_id}/api_keys/{key_id}": { + "get": { + "summary": "Retrieve project API key", + "operationId": "retrieve-project-api-key", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "key_id", + "in": "path", + "description": "The ID of the API key.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project API key retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectApiKey" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve project API key", + "group": "administration", + "returns": "The [ProjectApiKey](https://platform.openai.com/docs/api-reference/project-api-keys/object) object matching the specified ID.", + "examples": { + "response": "{\n \"object\": \"organization.project.api_key\",\n \"redacted_value\": \"sk-abc...def\",\n \"name\": \"My API Key\",\n \"created_at\": 1711471533,\n \"last_used_at\": 1711471534,\n \"id\": \"key_abc\",\n \"owner\": {\n \"type\": \"user\",\n \"user\": {\n \"object\": \"organization.project.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n }\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Retrieves an API key in the project." + }, + "delete": { + "summary": "Delete project API key", + "operationId": "delete-project-api-key", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "key_id", + "in": "path", + "description": "The ID of the API key.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project API key deleted successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectApiKeyDeleteResponse" + } + } + } + }, + "400": { + "description": "Error response for various conditions.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete project API key", + "group": "administration", + "returns": "Confirmation of the key's deletion or an error if the key belonged to a service account", + "examples": { + "response": "{\n \"object\": \"organization.project.api_key.deleted\",\n \"id\": \"key_abc\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Deletes an API key from the project." + } + }, + "/organization/projects/{project_id}/archive": { + "post": { + "summary": "Archive project", + "operationId": "archive-project", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project archived successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Project" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Archive project", + "group": "administration", + "returns": "The archived [Project](https://platform.openai.com/docs/api-reference/projects/object) object.", + "examples": { + "response": "{\n \"id\": \"proj_abc\",\n \"object\": \"organization.project\",\n \"name\": \"Project DEF\",\n \"created_at\": 1711471533,\n \"archived_at\": 1711471533,\n \"status\": \"archived\"\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/archive \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Archives a project in the organization. Archived projects cannot be used or updated." + } + }, + "/organization/projects/{project_id}/certificates": { + "get": { + "summary": "List project certificates", + "operationId": "listProjectCertificates", + "tags": [ + "Certificates" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + } + ], + "responses": { + "200": { + "description": "Certificates listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListCertificatesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List project certificates", + "group": "administration", + "returns": "A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects.", + "examples": { + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc/certificates \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\"\n" + }, + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"organization.project.certificate\",\n \"id\": \"cert_abc\",\n \"name\": \"My Example Certificate\",\n \"active\": true,\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n },\n ],\n \"first_id\": \"cert_abc\",\n \"last_id\": \"cert_abc\",\n \"has_more\": false\n}\n" + } + }, + "description": "List certificates for this project." + } + }, + "/organization/projects/{project_id}/certificates/activate": { + "post": { + "summary": "Activate certificates for project", + "operationId": "activateProjectCertificates", + "tags": [ + "Certificates" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "The certificate activation payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ToggleCertificatesRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Certificates activated successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListCertificatesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Activate certificates for project", + "group": "administration", + "returns": "A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were activated.", + "examples": { + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc/certificates/activate \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\" \\\n-d '{\n \"data\": [\"cert_abc\", \"cert_def\"]\n}'\n" + }, + "response": "{\n \"object\": \"organization.project.certificate.activation\",\n \"data\": [\n {\n \"object\": \"organization.project.certificate\",\n \"id\": \"cert_abc\",\n \"name\": \"My Example Certificate\",\n \"active\": true,\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n },\n {\n \"object\": \"organization.project.certificate\",\n \"id\": \"cert_def\",\n \"name\": \"My Example Certificate 2\",\n \"active\": true,\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n },\n ],\n}\n" + } + }, + "description": "Activate certificates at the project level.\n\nYou can atomically and idempotently activate up to 10 certificates at a time.\n" + } + }, + "/organization/projects/{project_id}/certificates/deactivate": { + "post": { + "summary": "Deactivate certificates for project", + "operationId": "deactivateProjectCertificates", + "tags": [ + "Certificates" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "The certificate deactivation payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ToggleCertificatesRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Certificates deactivated successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListCertificatesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Deactivate certificates for project", + "group": "administration", + "returns": "A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were deactivated.", + "examples": { + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc/certificates/deactivate \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\" \\\n-d '{\n \"data\": [\"cert_abc\", \"cert_def\"]\n}'\n" + }, + "response": "{\n \"object\": \"organization.project.certificate.deactivation\",\n \"data\": [\n {\n \"object\": \"organization.project.certificate\",\n \"id\": \"cert_abc\",\n \"name\": \"My Example Certificate\",\n \"active\": false,\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n },\n {\n \"object\": \"organization.project.certificate\",\n \"id\": \"cert_def\",\n \"name\": \"My Example Certificate 2\",\n \"active\": false,\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 12345667,\n \"expires_at\": 12345678\n }\n },\n ],\n}\n" + } + }, + "description": "Deactivate certificates at the project level. You can atomically and \nidempotently deactivate up to 10 certificates at a time.\n" + } + }, + "/organization/projects/{project_id}/rate_limits": { + "get": { + "summary": "List project rate limits", + "operationId": "list-project-rate-limits", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. The default is 100.\n", + "required": false, + "schema": { + "type": "integer", + "default": 100 + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "before", + "in": "query", + "description": "A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, beginning with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.\n", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project rate limits listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectRateLimitListResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List project rate limits", + "group": "administration", + "returns": "A list of [ProjectRateLimit](https://platform.openai.com/docs/api-reference/project-rate-limits/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"project.rate_limit\",\n \"id\": \"rl-ada\",\n \"model\": \"ada\",\n \"max_requests_per_1_minute\": 600,\n \"max_tokens_per_1_minute\": 150000,\n \"max_images_per_1_minute\": 10\n }\n ],\n \"first_id\": \"rl-ada\",\n \"last_id\": \"rl-ada\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc/rate_limits?after=rl_xxx&limit=20 \\ -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + }, + "error_response": "{\n \"code\": 404,\n \"message\": \"The project {project_id} was not found\"\n}\n" + } + }, + "description": "Returns the rate limits per model for a project." + } + }, + "/organization/projects/{project_id}/rate_limits/{rate_limit_id}": { + "post": { + "summary": "Modify project rate limit", + "operationId": "update-project-rate-limits", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "rate_limit_id", + "in": "path", + "description": "The ID of the rate limit.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "The project rate limit update request payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectRateLimitUpdateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Project rate limit updated successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectRateLimit" + } + } + } + }, + "400": { + "description": "Error response for various conditions.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Modify project rate limit", + "group": "administration", + "returns": "The updated [ProjectRateLimit](https://platform.openai.com/docs/api-reference/project-rate-limits/object) object.", + "examples": { + "response": "{\n \"object\": \"project.rate_limit\",\n \"id\": \"rl-ada\",\n \"model\": \"ada\",\n \"max_requests_per_1_minute\": 600,\n \"max_tokens_per_1_minute\": 150000,\n \"max_images_per_1_minute\": 10\n }\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/rate_limits/rl_xxx \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"max_requests_per_1_minute\": 500\n }'\n" + }, + "error_response": "{\n \"code\": 404,\n \"message\": \"The project {project_id} was not found\"\n}\n" + } + }, + "description": "Updates a project rate limit." + } + }, + "/organization/projects/{project_id}/service_accounts": { + "get": { + "summary": "List project service accounts", + "operationId": "list-project-service-accounts", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project service accounts listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectServiceAccountListResponse" + } + } + } + }, + "400": { + "description": "Error response when project is archived.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List project service accounts", + "group": "administration", + "returns": "A list of [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"organization.project.service_account\",\n \"id\": \"svc_acct_abc\",\n \"name\": \"Service Account\",\n \"role\": \"owner\",\n \"created_at\": 1711471533\n }\n ],\n \"first_id\": \"svc_acct_abc\",\n \"last_id\": \"svc_acct_xyz\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts?after=custom_id&limit=20 \\ -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Returns a list of service accounts in the project." + }, + "post": { + "summary": "Create project service account", + "operationId": "create-project-service-account", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "The project service account create request payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectServiceAccountCreateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Project service account created successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectServiceAccountCreateResponse" + } + } + } + }, + "400": { + "description": "Error response when project is archived.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create project service account", + "group": "administration", + "returns": "The created [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) object.", + "examples": { + "response": "{\n \"object\": \"organization.project.service_account\",\n \"id\": \"svc_acct_abc\",\n \"name\": \"Production App\",\n \"role\": \"member\",\n \"created_at\": 1711471533,\n \"api_key\": {\n \"object\": \"organization.project.service_account.api_key\",\n \"value\": \"sk-abcdefghijklmnop123\",\n \"name\": \"Secret Key\",\n \"created_at\": 1711471533,\n \"id\": \"key_abc\"\n }\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/service_accounts \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"name\": \"Production App\"\n }'\n" + } + } + }, + "description": "Creates a new service account in the project. This also returns an unredacted API key for the service account." + } + }, + "/organization/projects/{project_id}/service_accounts/{service_account_id}": { + "get": { + "summary": "Retrieve project service account", + "operationId": "retrieve-project-service-account", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "service_account_id", + "in": "path", + "description": "The ID of the service account.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project service account retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectServiceAccount" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve project service account", + "group": "administration", + "returns": "The [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) object matching the specified ID.", + "examples": { + "response": "{\n \"object\": \"organization.project.service_account\",\n \"id\": \"svc_acct_abc\",\n \"name\": \"Service Account\",\n \"role\": \"owner\",\n \"created_at\": 1711471533\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Retrieves a service account in the project." + }, + "delete": { + "summary": "Delete project service account", + "operationId": "delete-project-service-account", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "service_account_id", + "in": "path", + "description": "The ID of the service account.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project service account deleted successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectServiceAccountDeleteResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete project service account", + "group": "administration", + "returns": "Confirmation of service account being deleted, or an error in case of an archived project, which has no service accounts", + "examples": { + "response": "{\n \"object\": \"organization.project.service_account.deleted\",\n \"id\": \"svc_acct_abc\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \\ -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Deletes a service account from the project." + } + }, + "/organization/projects/{project_id}/users": { + "get": { + "summary": "List project users", + "operationId": "list-project-users", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project users listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectUserListResponse" + } + } + } + }, + "400": { + "description": "Error response when project is archived.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List project users", + "group": "administration", + "returns": "A list of [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"organization.project.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n }\n ],\n \"first_id\": \"user-abc\",\n \"last_id\": \"user-xyz\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc/users?after=user_abc&limit=20 \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Returns a list of users in the project." + }, + "post": { + "summary": "Create project user", + "operationId": "create-project-user", + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "tags": [ + "Projects" + ], + "requestBody": { + "description": "The project user create request payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectUserCreateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "User added to project successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectUser" + } + } + } + }, + "400": { + "description": "Error response for various conditions.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create project user", + "group": "administration", + "returns": "The created [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) object.", + "examples": { + "response": "{\n \"object\": \"organization.project.user\",\n \"id\": \"user_abc\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"user_id\": \"user_abc\",\n \"role\": \"member\"\n }'\n" + } + } + }, + "description": "Adds a user to the project. Users must already be members of the organization to be added to a project." + } + }, + "/organization/projects/{project_id}/users/{user_id}": { + "get": { + "summary": "Retrieve project user", + "operationId": "retrieve-project-user", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "user_id", + "in": "path", + "description": "The ID of the user.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project user retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectUser" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve project user", + "group": "administration", + "returns": "The [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) object matching the specified ID.", + "examples": { + "response": "{\n \"object\": \"organization.project.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Retrieves a user in the project." + }, + "post": { + "summary": "Modify project user", + "operationId": "modify-project-user", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "user_id", + "in": "path", + "description": "The ID of the user.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "The project user update request payload.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectUserUpdateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Project user's role updated successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectUser" + } + } + } + }, + "400": { + "description": "Error response for various conditions.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Modify project user", + "group": "administration", + "returns": "The updated [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) object.", + "examples": { + "response": "{\n \"object\": \"organization.project.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"role\": \"owner\"\n }'\n" + } + } + }, + "description": "Modifies a user's role in the project." + }, + "delete": { + "summary": "Delete project user", + "operationId": "delete-project-user", + "tags": [ + "Projects" + ], + "parameters": [ + { + "name": "project_id", + "in": "path", + "description": "The ID of the project.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "user_id", + "in": "path", + "description": "The ID of the user.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Project user deleted successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectUserDeleteResponse" + } + } + } + }, + "400": { + "description": "Error response for various conditions.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete project user", + "group": "administration", + "returns": "Confirmation that project has been deleted or an error in case of an archived project, which has no users", + "examples": { + "response": "{\n \"object\": \"organization.project.user.deleted\",\n \"id\": \"user_abc\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Deletes a user from the project." + } + }, + "/organization/usage/audio_speeches": { + "get": { + "summary": "Audio speeches", + "operationId": "usage-audio-speeches", + "tags": [ + "Usage" + ], + "parameters": [ + { + "name": "start_time", + "in": "query", + "description": "Start time (Unix seconds) of the query time range, inclusive.", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "end_time", + "in": "query", + "description": "End time (Unix seconds) of the query time range, exclusive.", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "bucket_width", + "in": "query", + "description": "Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "1m", + "1h", + "1d" + ], + "default": "1d" + } + }, + { + "name": "project_ids", + "in": "query", + "description": "Return only usage for these projects.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "user_ids", + "in": "query", + "description": "Return only usage for these users.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "api_key_ids", + "in": "query", + "description": "Return only usage for these API keys.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "models", + "in": "query", + "description": "Return only usage for these models.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "group_by", + "in": "query", + "description": "Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "project_id", + "user_id", + "api_key_id", + "model" + ] + } + } + }, + { + "name": "limit", + "in": "query", + "description": "Specifies the number of buckets to return.\n- `bucket_width=1d`: default: 7, max: 31\n- `bucket_width=1h`: default: 24, max: 168\n- `bucket_width=1m`: default: 60, max: 1440\n", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "description": "A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Usage data retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UsageResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Audio speeches", + "group": "usage-audio-speeches", + "returns": "A list of paginated, time bucketed [Audio speeches usage](https://platform.openai.com/docs/api-reference/usage/audio_speeches_object) objects.", + "examples": { + "response": "{\n \"object\": \"page\",\n \"data\": [\n {\n \"object\": \"bucket\",\n \"start_time\": 1730419200,\n \"end_time\": 1730505600,\n \"results\": [\n {\n \"object\": \"organization.usage.audio_speeches.result\",\n \"characters\": 45,\n \"num_model_requests\": 1,\n \"project_id\": null,\n \"user_id\": null,\n \"api_key_id\": null,\n \"model\": null\n }\n ]\n }\n ],\n \"has_more\": false,\n \"next_page\": null\n}\n", + "request": { + "curl": "curl \"https://api.openai.com/v1/organization/usage/audio_speeches?start_time=1730419200&limit=1\" \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Get audio speeches usage details for the organization." + } + }, + "/organization/usage/audio_transcriptions": { + "get": { + "summary": "Audio transcriptions", + "operationId": "usage-audio-transcriptions", + "tags": [ + "Usage" + ], + "parameters": [ + { + "name": "start_time", + "in": "query", + "description": "Start time (Unix seconds) of the query time range, inclusive.", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "end_time", + "in": "query", + "description": "End time (Unix seconds) of the query time range, exclusive.", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "bucket_width", + "in": "query", + "description": "Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "1m", + "1h", + "1d" + ], + "default": "1d" + } + }, + { + "name": "project_ids", + "in": "query", + "description": "Return only usage for these projects.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "user_ids", + "in": "query", + "description": "Return only usage for these users.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "api_key_ids", + "in": "query", + "description": "Return only usage for these API keys.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "models", + "in": "query", + "description": "Return only usage for these models.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "group_by", + "in": "query", + "description": "Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "project_id", + "user_id", + "api_key_id", + "model" + ] + } + } + }, + { + "name": "limit", + "in": "query", + "description": "Specifies the number of buckets to return.\n- `bucket_width=1d`: default: 7, max: 31\n- `bucket_width=1h`: default: 24, max: 168\n- `bucket_width=1m`: default: 60, max: 1440\n", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "description": "A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Usage data retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UsageResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Audio transcriptions", + "group": "usage-audio-transcriptions", + "returns": "A list of paginated, time bucketed [Audio transcriptions usage](https://platform.openai.com/docs/api-reference/usage/audio_transcriptions_object) objects.", + "examples": { + "response": "{\n \"object\": \"page\",\n \"data\": [\n {\n \"object\": \"bucket\",\n \"start_time\": 1730419200,\n \"end_time\": 1730505600,\n \"results\": [\n {\n \"object\": \"organization.usage.audio_transcriptions.result\",\n \"seconds\": 20,\n \"num_model_requests\": 1,\n \"project_id\": null,\n \"user_id\": null,\n \"api_key_id\": null,\n \"model\": null\n }\n ]\n }\n ],\n \"has_more\": false,\n \"next_page\": null\n}\n", + "request": { + "curl": "curl \"https://api.openai.com/v1/organization/usage/audio_transcriptions?start_time=1730419200&limit=1\" \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Get audio transcriptions usage details for the organization." + } + }, + "/organization/usage/code_interpreter_sessions": { + "get": { + "summary": "Code interpreter sessions", + "operationId": "usage-code-interpreter-sessions", + "tags": [ + "Usage" + ], + "parameters": [ + { + "name": "start_time", + "in": "query", + "description": "Start time (Unix seconds) of the query time range, inclusive.", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "end_time", + "in": "query", + "description": "End time (Unix seconds) of the query time range, exclusive.", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "bucket_width", + "in": "query", + "description": "Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "1m", + "1h", + "1d" + ], + "default": "1d" + } + }, + { + "name": "project_ids", + "in": "query", + "description": "Return only usage for these projects.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "group_by", + "in": "query", + "description": "Group the usage data by the specified fields. Support fields include `project_id`.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "project_id" + ] + } + } + }, + { + "name": "limit", + "in": "query", + "description": "Specifies the number of buckets to return.\n- `bucket_width=1d`: default: 7, max: 31\n- `bucket_width=1h`: default: 24, max: 168\n- `bucket_width=1m`: default: 60, max: 1440\n", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "description": "A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Usage data retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UsageResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Code interpreter sessions", + "group": "usage-code-interpreter-sessions", + "returns": "A list of paginated, time bucketed [Code interpreter sessions usage](https://platform.openai.com/docs/api-reference/usage/code_interpreter_sessions_object) objects.", + "examples": { + "response": "{\n \"object\": \"page\",\n \"data\": [\n {\n \"object\": \"bucket\",\n \"start_time\": 1730419200,\n \"end_time\": 1730505600,\n \"results\": [\n {\n \"object\": \"organization.usage.code_interpreter_sessions.result\",\n \"num_sessions\": 1,\n \"project_id\": null\n }\n ]\n }\n ],\n \"has_more\": false,\n \"next_page\": null\n}\n", + "request": { + "curl": "curl \"https://api.openai.com/v1/organization/usage/code_interpreter_sessions?start_time=1730419200&limit=1\" \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Get code interpreter sessions usage details for the organization." + } + }, + "/organization/usage/completions": { + "get": { + "summary": "Completions", + "operationId": "usage-completions", + "tags": [ + "Usage" + ], + "parameters": [ + { + "name": "start_time", + "in": "query", + "description": "Start time (Unix seconds) of the query time range, inclusive.", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "end_time", + "in": "query", + "description": "End time (Unix seconds) of the query time range, exclusive.", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "bucket_width", + "in": "query", + "description": "Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "1m", + "1h", + "1d" + ], + "default": "1d" + } + }, + { + "name": "project_ids", + "in": "query", + "description": "Return only usage for these projects.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "user_ids", + "in": "query", + "description": "Return only usage for these users.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "api_key_ids", + "in": "query", + "description": "Return only usage for these API keys.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "models", + "in": "query", + "description": "Return only usage for these models.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "batch", + "in": "query", + "description": "If `true`, return batch jobs only. If `false`, return non-batch jobs only. By default, return both.\n", + "required": false, + "schema": { + "type": "boolean" + } + }, + { + "name": "group_by", + "in": "query", + "description": "Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model`, `batch` or any combination of them.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "project_id", + "user_id", + "api_key_id", + "model", + "batch" + ] + } + } + }, + { + "name": "limit", + "in": "query", + "description": "Specifies the number of buckets to return.\n- `bucket_width=1d`: default: 7, max: 31\n- `bucket_width=1h`: default: 24, max: 168\n- `bucket_width=1m`: default: 60, max: 1440\n", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "description": "A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Usage data retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UsageResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Completions", + "group": "usage-completions", + "returns": "A list of paginated, time bucketed [Completions usage](https://platform.openai.com/docs/api-reference/usage/completions_object) objects.", + "examples": { + "response": "{\n \"object\": \"page\",\n \"data\": [\n {\n \"object\": \"bucket\",\n \"start_time\": 1730419200,\n \"end_time\": 1730505600,\n \"results\": [\n {\n \"object\": \"organization.usage.completions.result\",\n \"input_tokens\": 1000,\n \"output_tokens\": 500,\n \"input_cached_tokens\": 800,\n \"input_audio_tokens\": 0,\n \"output_audio_tokens\": 0,\n \"num_model_requests\": 5,\n \"project_id\": null,\n \"user_id\": null,\n \"api_key_id\": null,\n \"model\": null,\n \"batch\": null\n }\n ]\n }\n ],\n \"has_more\": true,\n \"next_page\": \"page_AAAAAGdGxdEiJdKOAAAAAGcqsYA=\"\n}\n", + "request": { + "curl": "curl \"https://api.openai.com/v1/organization/usage/completions?start_time=1730419200&limit=1\" \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Get completions usage details for the organization." + } + }, + "/organization/usage/embeddings": { + "get": { + "summary": "Embeddings", + "operationId": "usage-embeddings", + "tags": [ + "Usage" + ], + "parameters": [ + { + "name": "start_time", + "in": "query", + "description": "Start time (Unix seconds) of the query time range, inclusive.", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "end_time", + "in": "query", + "description": "End time (Unix seconds) of the query time range, exclusive.", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "bucket_width", + "in": "query", + "description": "Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "1m", + "1h", + "1d" + ], + "default": "1d" + } + }, + { + "name": "project_ids", + "in": "query", + "description": "Return only usage for these projects.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "user_ids", + "in": "query", + "description": "Return only usage for these users.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "api_key_ids", + "in": "query", + "description": "Return only usage for these API keys.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "models", + "in": "query", + "description": "Return only usage for these models.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "group_by", + "in": "query", + "description": "Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "project_id", + "user_id", + "api_key_id", + "model" + ] + } + } + }, + { + "name": "limit", + "in": "query", + "description": "Specifies the number of buckets to return.\n- `bucket_width=1d`: default: 7, max: 31\n- `bucket_width=1h`: default: 24, max: 168\n- `bucket_width=1m`: default: 60, max: 1440\n", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "description": "A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Usage data retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UsageResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Embeddings", + "group": "usage-embeddings", + "returns": "A list of paginated, time bucketed [Embeddings usage](https://platform.openai.com/docs/api-reference/usage/embeddings_object) objects.", + "examples": { + "response": "{\n \"object\": \"page\",\n \"data\": [\n {\n \"object\": \"bucket\",\n \"start_time\": 1730419200,\n \"end_time\": 1730505600,\n \"results\": [\n {\n \"object\": \"organization.usage.embeddings.result\",\n \"input_tokens\": 16,\n \"num_model_requests\": 2,\n \"project_id\": null,\n \"user_id\": null,\n \"api_key_id\": null,\n \"model\": null\n }\n ]\n }\n ],\n \"has_more\": false,\n \"next_page\": null\n}\n", + "request": { + "curl": "curl \"https://api.openai.com/v1/organization/usage/embeddings?start_time=1730419200&limit=1\" \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Get embeddings usage details for the organization." + } + }, + "/organization/usage/images": { + "get": { + "summary": "Images", + "operationId": "usage-images", + "tags": [ + "Usage" + ], + "parameters": [ + { + "name": "start_time", + "in": "query", + "description": "Start time (Unix seconds) of the query time range, inclusive.", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "end_time", + "in": "query", + "description": "End time (Unix seconds) of the query time range, exclusive.", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "bucket_width", + "in": "query", + "description": "Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "1m", + "1h", + "1d" + ], + "default": "1d" + } + }, + { + "name": "sources", + "in": "query", + "description": "Return only usages for these sources. Possible values are `image.generation`, `image.edit`, `image.variation` or any combination of them.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "image.generation", + "image.edit", + "image.variation" + ] + } + } + }, + { + "name": "sizes", + "in": "query", + "description": "Return only usages for these image sizes. Possible values are `256x256`, `512x512`, `1024x1024`, `1792x1792`, `1024x1792` or any combination of them.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "256x256", + "512x512", + "1024x1024", + "1792x1792", + "1024x1792" + ] + } + } + }, + { + "name": "project_ids", + "in": "query", + "description": "Return only usage for these projects.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "user_ids", + "in": "query", + "description": "Return only usage for these users.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "api_key_ids", + "in": "query", + "description": "Return only usage for these API keys.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "models", + "in": "query", + "description": "Return only usage for these models.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "group_by", + "in": "query", + "description": "Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model`, `size`, `source` or any combination of them.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "project_id", + "user_id", + "api_key_id", + "model", + "size", + "source" + ] + } + } + }, + { + "name": "limit", + "in": "query", + "description": "Specifies the number of buckets to return.\n- `bucket_width=1d`: default: 7, max: 31\n- `bucket_width=1h`: default: 24, max: 168\n- `bucket_width=1m`: default: 60, max: 1440\n", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "description": "A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Usage data retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UsageResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Images", + "group": "usage-images", + "returns": "A list of paginated, time bucketed [Images usage](https://platform.openai.com/docs/api-reference/usage/images_object) objects.", + "examples": { + "response": "{\n \"object\": \"page\",\n \"data\": [\n {\n \"object\": \"bucket\",\n \"start_time\": 1730419200,\n \"end_time\": 1730505600,\n \"results\": [\n {\n \"object\": \"organization.usage.images.result\",\n \"images\": 2,\n \"num_model_requests\": 2,\n \"size\": null,\n \"source\": null,\n \"project_id\": null,\n \"user_id\": null,\n \"api_key_id\": null,\n \"model\": null\n }\n ]\n }\n ],\n \"has_more\": false,\n \"next_page\": null\n}\n", + "request": { + "curl": "curl \"https://api.openai.com/v1/organization/usage/images?start_time=1730419200&limit=1\" \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Get images usage details for the organization." + } + }, + "/organization/usage/moderations": { + "get": { + "summary": "Moderations", + "operationId": "usage-moderations", + "tags": [ + "Usage" + ], + "parameters": [ + { + "name": "start_time", + "in": "query", + "description": "Start time (Unix seconds) of the query time range, inclusive.", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "end_time", + "in": "query", + "description": "End time (Unix seconds) of the query time range, exclusive.", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "bucket_width", + "in": "query", + "description": "Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "1m", + "1h", + "1d" + ], + "default": "1d" + } + }, + { + "name": "project_ids", + "in": "query", + "description": "Return only usage for these projects.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "user_ids", + "in": "query", + "description": "Return only usage for these users.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "api_key_ids", + "in": "query", + "description": "Return only usage for these API keys.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "models", + "in": "query", + "description": "Return only usage for these models.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "group_by", + "in": "query", + "description": "Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "project_id", + "user_id", + "api_key_id", + "model" + ] + } + } + }, + { + "name": "limit", + "in": "query", + "description": "Specifies the number of buckets to return.\n- `bucket_width=1d`: default: 7, max: 31\n- `bucket_width=1h`: default: 24, max: 168\n- `bucket_width=1m`: default: 60, max: 1440\n", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "description": "A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Usage data retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UsageResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Moderations", + "group": "usage-moderations", + "returns": "A list of paginated, time bucketed [Moderations usage](https://platform.openai.com/docs/api-reference/usage/moderations_object) objects.", + "examples": { + "response": "{\n \"object\": \"page\",\n \"data\": [\n {\n \"object\": \"bucket\",\n \"start_time\": 1730419200,\n \"end_time\": 1730505600,\n \"results\": [\n {\n \"object\": \"organization.usage.moderations.result\",\n \"input_tokens\": 16,\n \"num_model_requests\": 2,\n \"project_id\": null,\n \"user_id\": null,\n \"api_key_id\": null,\n \"model\": null\n }\n ]\n }\n ],\n \"has_more\": false,\n \"next_page\": null\n}\n", + "request": { + "curl": "curl \"https://api.openai.com/v1/organization/usage/moderations?start_time=1730419200&limit=1\" \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Get moderations usage details for the organization." + } + }, + "/organization/usage/vector_stores": { + "get": { + "summary": "Vector stores", + "operationId": "usage-vector-stores", + "tags": [ + "Usage" + ], + "parameters": [ + { + "name": "start_time", + "in": "query", + "description": "Start time (Unix seconds) of the query time range, inclusive.", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "name": "end_time", + "in": "query", + "description": "End time (Unix seconds) of the query time range, exclusive.", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "bucket_width", + "in": "query", + "description": "Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "1m", + "1h", + "1d" + ], + "default": "1d" + } + }, + { + "name": "project_ids", + "in": "query", + "description": "Return only usage for these projects.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "group_by", + "in": "query", + "description": "Group the usage data by the specified fields. Support fields include `project_id`.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "project_id" + ] + } + } + }, + { + "name": "limit", + "in": "query", + "description": "Specifies the number of buckets to return.\n- `bucket_width=1d`: default: 7, max: 31\n- `bucket_width=1h`: default: 24, max: 168\n- `bucket_width=1m`: default: 60, max: 1440\n", + "required": false, + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "description": "A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Usage data retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UsageResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Vector stores", + "group": "usage-vector-stores", + "returns": "A list of paginated, time bucketed [Vector stores usage](https://platform.openai.com/docs/api-reference/usage/vector_stores_object) objects.", + "examples": { + "response": "{\n \"object\": \"page\",\n \"data\": [\n {\n \"object\": \"bucket\",\n \"start_time\": 1730419200,\n \"end_time\": 1730505600,\n \"results\": [\n {\n \"object\": \"organization.usage.vector_stores.result\",\n \"usage_bytes\": 1024,\n \"project_id\": null\n }\n ]\n }\n ],\n \"has_more\": false,\n \"next_page\": null\n}\n", + "request": { + "curl": "curl \"https://api.openai.com/v1/organization/usage/vector_stores?start_time=1730419200&limit=1\" \\\n-H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n-H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Get vector stores usage details for the organization." + } + }, + "/organization/users": { + "get": { + "summary": "List users", + "operationId": "list-users", + "tags": [ + "Users" + ], + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "emails", + "in": "query", + "description": "Filter by the email address of users.", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + ], + "responses": { + "200": { + "description": "Users listed successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserListResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List users", + "group": "administration", + "returns": "A list of [User](https://platform.openai.com/docs/api-reference/users/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"organization.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n }\n ],\n \"first_id\": \"user-abc\",\n \"last_id\": \"user-xyz\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/users?after=user_abc&limit=20 \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Lists all of the users in the organization." + } + }, + "/organization/users/{user_id}": { + "get": { + "summary": "Retrieve user", + "operationId": "retrieve-user", + "tags": [ + "Users" + ], + "parameters": [ + { + "name": "user_id", + "in": "path", + "description": "The ID of the user.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "User retrieved successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve user", + "group": "administration", + "returns": "The [User](https://platform.openai.com/docs/api-reference/users/object) object matching the specified ID.", + "examples": { + "response": "{\n \"object\": \"organization.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/organization/users/user_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Retrieves a user by their identifier." + }, + "post": { + "summary": "Modify user", + "operationId": "modify-user", + "tags": [ + "Users" + ], + "parameters": [ + { + "name": "user_id", + "in": "path", + "description": "The ID of the user.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "The new user role to modify. This must be one of `owner` or `member`.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserRoleUpdateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "User role updated successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Modify user", + "group": "administration", + "returns": "The updated [User](https://platform.openai.com/docs/api-reference/users/object) object.", + "examples": { + "response": "{\n \"object\": \"organization.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/organization/users/user_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"role\": \"owner\"\n }'\n" + } + } + }, + "description": "Modifies a user's role in the organization." + }, + "delete": { + "summary": "Delete user", + "operationId": "delete-user", + "tags": [ + "Users" + ], + "parameters": [ + { + "name": "user_id", + "in": "path", + "description": "The ID of the user.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "User deleted successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserDeleteResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete user", + "group": "administration", + "returns": "Confirmation of the deleted user", + "examples": { + "response": "{\n \"object\": \"organization.user.deleted\",\n \"id\": \"user_abc\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/organization/users/user_abc \\\n -H \"Authorization: Bearer $OPENAI_ADMIN_KEY\" \\\n -H \"Content-Type: application/json\"\n" + } + } + }, + "description": "Deletes a user from the organization." + } + }, + "/realtime/client_secrets": { + "post": { + "summary": "Create realtime session", + "operationId": "create-realtime-client-secret", + "tags": [ + "Realtime" + ], + "requestBody": { + "description": "Create a client secret with the given session configuration.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RealtimeCreateClientSecretRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Client secret created successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RealtimeCreateClientSecretResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create realtime session", + "group": "realtime", + "returns": "The created client secret and the effective session object", + "examples": { + "response": "{\n \"value\": \"ek_68af296e8e408191a1120ab6383263c2\",\n \"expires_at\": 1756310470,\n \"session\": {\n \"type\": \"realtime\",\n \"object\": \"realtime.session\",\n \"id\": \"sess_C9CiUVUzUzYIssh3ELY1d\",\n \"model\": \"gpt-realtime\",\n \"output_modalities\": [\n \"audio\"\n ],\n \"instructions\": \"You are a friendly assistant.\",\n \"tools\": [],\n \"tool_choice\": \"auto\",\n \"max_output_tokens\": \"inf\",\n \"tracing\": null,\n \"truncation\": \"auto\",\n \"prompt\": null,\n \"expires_at\": 0,\n \"audio\": {\n \"input\": {\n \"format\": {\n \"type\": \"audio/pcm\",\n \"rate\": 24000\n },\n \"transcription\": null,\n \"noise_reduction\": null,\n \"turn_detection\": {\n \"type\": \"server_vad\",\n \"threshold\": 0.5,\n \"prefix_padding_ms\": 300,\n \"silence_duration_ms\": 200,\n \"idle_timeout_ms\": null,\n \"create_response\": true,\n \"interrupt_response\": true\n }\n },\n \"output\": {\n \"format\": {\n \"type\": \"audio/pcm\",\n \"rate\": 24000\n },\n \"voice\": \"alloy\",\n \"speed\": 1.0\n }\n },\n \"include\": null\n }\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/realtime/client_secrets \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"expires_after\": { \"anchor\": \"created_at\", \"seconds\": 600 },\n \"session\": {\n \"type\": \"realtime\",\n \"model\": \"gpt-realtime\",\n \"instructions\": \"You are a friendly assistant.\"\n }\n }'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst clientSecret = await client.realtime.clientSecrets.create();\n\nconsole.log(clientSecret.expires_at);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nclient_secret = client.realtime.client_secrets.create()\nprint(client_secret.expires_at)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/realtime\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n clientSecret, err := client.Realtime.ClientSecrets.New(context.TODO(), realtime.ClientSecretNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", clientSecret.ExpiresAt)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.realtime.clientsecrets.ClientSecretCreateParams;\nimport com.openai.models.realtime.clientsecrets.ClientSecretCreateResponse;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ClientSecretCreateResponse clientSecret = client.realtime().clientSecrets().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nclient_secret = openai.realtime.client_secrets.create\n\nputs(client_secret)" + } + } + }, + "description": "Create a Realtime session and client secret for either realtime or transcription.\n" + } + }, + "/realtime/sessions": { + "post": { + "summary": "Create session", + "operationId": "create-realtime-session", + "tags": [ + "Realtime" + ], + "requestBody": { + "description": "Create an ephemeral API key with the given session configuration.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RealtimeSessionCreateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Session created successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RealtimeSessionCreateResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create session", + "group": "realtime", + "returns": "The created Realtime session object, plus an ephemeral key", + "examples": { + "request": { + "curl": "curl -X POST https://api.openai.com/v1/realtime/sessions \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"gpt-4o-realtime-preview\",\n \"modalities\": [\"audio\", \"text\"],\n \"instructions\": \"You are a friendly assistant.\"\n }'\n" + }, + "response": "{\n \"id\": \"sess_001\",\n \"object\": \"realtime.session\",\n \"model\": \"gpt-4o-realtime-preview\",\n \"modalities\": [\"audio\", \"text\"],\n \"instructions\": \"You are a friendly assistant.\",\n \"voice\": \"alloy\",\n \"input_audio_format\": \"pcm16\",\n \"output_audio_format\": \"pcm16\",\n \"input_audio_transcription\": {\n \"model\": \"whisper-1\"\n },\n \"turn_detection\": null,\n \"tools\": [],\n \"tool_choice\": \"none\",\n \"temperature\": 0.7,\n \"max_response_output_tokens\": 200,\n \"speed\": 1.1,\n \"tracing\": \"auto\",\n \"client_secret\": {\n \"value\": \"ek_abc123\", \n \"expires_at\": 1234567890\n }\n}\n" + } + }, + "description": "Create an ephemeral API token for use in client-side applications with the\nRealtime API. Can be configured with the same session parameters as the\n`session.update` client event.\n\nIt responds with a session object, plus a `client_secret` key which contains\na usable ephemeral API token that can be used to authenticate browser clients\nfor the Realtime API.\n" + } + }, + "/realtime/transcription_sessions": { + "post": { + "summary": "Create transcription session", + "operationId": "create-realtime-transcription-session", + "tags": [ + "Realtime" + ], + "requestBody": { + "description": "Create an ephemeral API key with the given session configuration.", + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RealtimeTranscriptionSessionCreateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Session created successfully.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RealtimeTranscriptionSessionCreateResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create transcription session", + "group": "realtime", + "returns": "The created [Realtime transcription session object](https://platform.openai.com/docs/api-reference/realtime-sessions/transcription_session_object), plus an ephemeral key", + "examples": { + "request": { + "curl": "curl -X POST https://api.openai.com/v1/realtime/transcription_sessions \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{}'\n" + }, + "response": "{\n \"id\": \"sess_BBwZc7cFV3XizEyKGDCGL\",\n \"object\": \"realtime.transcription_session\",\n \"modalities\": [\"audio\", \"text\"],\n \"turn_detection\": {\n \"type\": \"server_vad\",\n \"threshold\": 0.5,\n \"prefix_padding_ms\": 300,\n \"silence_duration_ms\": 200\n },\n \"input_audio_format\": \"pcm16\",\n \"input_audio_transcription\": {\n \"model\": \"gpt-4o-transcribe\",\n \"language\": null,\n \"prompt\": \"\"\n },\n \"client_secret\": null\n}\n" + } + }, + "description": "Create an ephemeral API token for use in client-side applications with the\nRealtime API specifically for realtime transcriptions. \nCan be configured with the same session parameters as the `transcription_session.update` client event.\n\nIt responds with a session object, plus a `client_secret` key which contains\na usable ephemeral API token that can be used to authenticate browser clients\nfor the Realtime API.\n" + } + }, + "/responses": { + "post": { + "operationId": "createResponse", + "tags": [ + "Responses" + ], + "summary": "Create a model response", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateResponse" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Response" + } + }, + "text/event-stream": { + "schema": { + "$ref": "#/components/schemas/ResponseStreamEvent" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create a model response", + "group": "responses", + "returns": "Returns a [Response](https://platform.openai.com/docs/api-reference/responses/object) object.\n", + "path": "create", + "examples": [ + { + "title": "Text input", + "request": { + "curl": "curl https://api.openai.com/v1/responses \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"gpt-4.1\",\n \"input\": \"Tell me a three sentence bedtime story about a unicorn.\"\n }'\n", + "javascript": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nconst response = await openai.responses.create({\n model: \"gpt-4.1\",\n input: \"Tell me a three sentence bedtime story about a unicorn.\"\n});\n\nconsole.log(response);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.responses.create()\nprint(response.id)", + "csharp": "using System;\nusing OpenAI.Responses;\n\nOpenAIResponseClient client = new( model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nOpenAIResponse response = client.CreateResponse(\"Tell me a three sentence bedtime story about a unicorn.\");\n\nConsole.WriteLine(response.GetOutputText());\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.responses.create();\n\nconsole.log(response.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.Response;\nimport com.openai.models.responses.ResponseCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Response response = client.responses().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.responses.create\n\nputs(response)" + }, + "response": "{\n \"id\": \"resp_67ccd2bed1ec8190b14f964abc0542670bb6a6b452d3795b\",\n \"object\": \"response\",\n \"created_at\": 1741476542,\n \"status\": \"completed\",\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4.1-2025-04-14\",\n \"output\": [\n {\n \"type\": \"message\",\n \"id\": \"msg_67ccd2bf17f0819081ff3bb2cf6508e60bb6a6b452d3795b\",\n \"status\": \"completed\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"output_text\",\n \"text\": \"In a peaceful grove beneath a silver moon, a unicorn named Lumina discovered a hidden pool that reflected the stars. As she dipped her horn into the water, the pool began to shimmer, revealing a pathway to a magical realm of endless night skies. Filled with wonder, Lumina whispered a wish for all who dream to find their own hidden magic, and as she glanced back, her hoofprints sparkled like stardust.\",\n \"annotations\": []\n }\n ]\n }\n ],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": null,\n \"summary\": null\n },\n \"store\": true,\n \"temperature\": 1.0,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_p\": 1.0,\n \"truncation\": \"disabled\",\n \"usage\": {\n \"input_tokens\": 36,\n \"input_tokens_details\": {\n \"cached_tokens\": 0\n },\n \"output_tokens\": 87,\n \"output_tokens_details\": {\n \"reasoning_tokens\": 0\n },\n \"total_tokens\": 123\n },\n \"user\": null,\n \"metadata\": {}\n}\n" + }, + { + "title": "Image input", + "request": { + "curl": "curl https://api.openai.com/v1/responses \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"gpt-4.1\",\n \"input\": [\n {\n \"role\": \"user\",\n \"content\": [\n {\"type\": \"input_text\", \"text\": \"what is in this image?\"},\n {\n \"type\": \"input_image\",\n \"image_url\": \"https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg\"\n }\n ]\n }\n ]\n }'\n", + "javascript": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nconst response = await openai.responses.create({\n model: \"gpt-4.1\",\n input: [\n {\n role: \"user\",\n content: [\n { type: \"input_text\", text: \"what is in this image?\" },\n {\n type: \"input_image\",\n image_url:\n \"https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg\",\n },\n ],\n },\n ],\n});\n\nconsole.log(response);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.responses.create()\nprint(response.id)", + "csharp": "using System;\nusing System.Collections.Generic;\n\nusing OpenAI.Responses;\n\nOpenAIResponseClient client = new(\n model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nList inputItems =\n[\n ResponseItem.CreateUserMessageItem(\n [\n ResponseContentPart.CreateInputTextPart(\"What is in this image?\"),\n ResponseContentPart.CreateInputImagePart(new Uri(\"https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg\"))\n ]\n )\n];\n\nOpenAIResponse response = client.CreateResponse(inputItems);\n\nConsole.WriteLine(response.GetOutputText());\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.responses.create();\n\nconsole.log(response.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.Response;\nimport com.openai.models.responses.ResponseCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Response response = client.responses().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.responses.create\n\nputs(response)" + }, + "response": "{\n \"id\": \"resp_67ccd3a9da748190baa7f1570fe91ac604becb25c45c1d41\",\n \"object\": \"response\",\n \"created_at\": 1741476777,\n \"status\": \"completed\",\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4.1-2025-04-14\",\n \"output\": [\n {\n \"type\": \"message\",\n \"id\": \"msg_67ccd3acc8d48190a77525dc6de64b4104becb25c45c1d41\",\n \"status\": \"completed\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"output_text\",\n \"text\": \"The image depicts a scenic landscape with a wooden boardwalk or pathway leading through lush, green grass under a blue sky with some clouds. The setting suggests a peaceful natural area, possibly a park or nature reserve. There are trees and shrubs in the background.\",\n \"annotations\": []\n }\n ]\n }\n ],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": null,\n \"summary\": null\n },\n \"store\": true,\n \"temperature\": 1.0,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_p\": 1.0,\n \"truncation\": \"disabled\",\n \"usage\": {\n \"input_tokens\": 328,\n \"input_tokens_details\": {\n \"cached_tokens\": 0\n },\n \"output_tokens\": 52,\n \"output_tokens_details\": {\n \"reasoning_tokens\": 0\n },\n \"total_tokens\": 380\n },\n \"user\": null,\n \"metadata\": {}\n}\n" + }, + { + "title": "File input", + "request": { + "curl": "curl https://api.openai.com/v1/responses \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"gpt-4.1\",\n \"input\": [\n {\n \"role\": \"user\",\n \"content\": [\n {\"type\": \"input_text\", \"text\": \"what is in this file?\"},\n {\n \"type\": \"input_file\",\n \"file_url\": \"https://www.berkshirehathaway.com/letters/2024ltr.pdf\"\n }\n ]\n }\n ]\n }'\n", + "javascript": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nconst response = await openai.responses.create({\n model: \"gpt-4.1\",\n input: [\n {\n role: \"user\",\n content: [\n { type: \"input_text\", text: \"what is in this file?\" },\n {\n type: \"input_file\",\n file_url: \"https://www.berkshirehathaway.com/letters/2024ltr.pdf\",\n },\n ],\n },\n ],\n});\n\nconsole.log(response);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.responses.create()\nprint(response.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.responses.create();\n\nconsole.log(response.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.Response;\nimport com.openai.models.responses.ResponseCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Response response = client.responses().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.responses.create\n\nputs(response)" + }, + "response": "{\n \"id\": \"resp_686eef60237881a2bd1180bb8b13de430e34c516d176ff86\",\n \"object\": \"response\",\n \"created_at\": 1752100704,\n \"status\": \"completed\",\n \"background\": false,\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"max_tool_calls\": null,\n \"model\": \"gpt-4.1-2025-04-14\",\n \"output\": [\n {\n \"id\": \"msg_686eef60d3e081a29283bdcbc4322fd90e34c516d176ff86\",\n \"type\": \"message\",\n \"status\": \"completed\",\n \"content\": [\n {\n \"type\": \"output_text\",\n \"annotations\": [],\n \"logprobs\": [],\n \"text\": \"The file seems to contain excerpts from a letter to the shareholders of Berkshire Hathaway Inc., likely written by Warren Buffett. It covers several topics:\\n\\n1. **Communication Philosophy**: Buffett emphasizes the importance of transparency and candidness in reporting mistakes and successes to shareholders.\\n\\n2. **Mistakes and Learnings**: The letter acknowledges past mistakes in business assessments and management hires, highlighting the importance of correcting errors promptly.\\n\\n3. **CEO Succession**: Mention of Greg Abel stepping in as the new CEO and continuing the tradition of honest communication.\\n\\n4. **Pete Liegl Story**: A detailed account of acquiring Forest River and the relationship with its founder, highlighting trust and effective business decisions.\\n\\n5. **2024 Performance**: Overview of business performance, particularly in insurance and investment activities, with a focus on GEICO's improvement.\\n\\n6. **Tax Contributions**: Discussion of significant tax payments to the U.S. Treasury, credited to shareholders' reinvestments.\\n\\n7. **Investment Strategy**: A breakdown of Berkshire\\u2019s investments in both controlled subsidiaries and marketable equities, along with a focus on long-term holding strategies.\\n\\n8. **American Capitalism**: Reflections on America\\u2019s economic development and Berkshire\\u2019s role within it.\\n\\n9. **Property-Casualty Insurance**: Insights into the P/C insurance business model and its challenges and benefits.\\n\\n10. **Japanese Investments**: Information about Berkshire\\u2019s investments in Japanese companies and future plans.\\n\\n11. **Annual Meeting**: Details about the upcoming annual gathering in Omaha, including schedule changes and new book releases.\\n\\n12. **Personal Anecdotes**: Light-hearted stories about family and interactions, conveying Buffett's personable approach.\\n\\n13. **Financial Performance Data**: Tables comparing Berkshire\\u2019s annual performance to the S&P 500, showing impressive long-term gains.\\n\\nOverall, the letter reinforces Berkshire Hathaway's commitment to transparency, investment in both its businesses and the wider economy, and emphasizes strong leadership and prudent financial management.\"\n }\n ],\n \"role\": \"assistant\"\n }\n ],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": null,\n \"summary\": null\n },\n \"service_tier\": \"default\",\n \"store\": true,\n \"temperature\": 1.0,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_logprobs\": 0,\n \"top_p\": 1.0,\n \"truncation\": \"disabled\",\n \"usage\": {\n \"input_tokens\": 8438,\n \"input_tokens_details\": {\n \"cached_tokens\": 0\n },\n \"output_tokens\": 398,\n \"output_tokens_details\": {\n \"reasoning_tokens\": 0\n },\n \"total_tokens\": 8836\n },\n \"user\": null,\n \"metadata\": {}\n}\n" + }, + { + "title": "Web search", + "request": { + "curl": "curl https://api.openai.com/v1/responses \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"gpt-4.1\",\n \"tools\": [{ \"type\": \"web_search_preview\" }],\n \"input\": \"What was a positive news story from today?\"\n }'\n", + "javascript": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nconst response = await openai.responses.create({\n model: \"gpt-4.1\",\n tools: [{ type: \"web_search_preview\" }],\n input: \"What was a positive news story from today?\",\n});\n\nconsole.log(response);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.responses.create()\nprint(response.id)", + "csharp": "using System;\n\nusing OpenAI.Responses;\n\nOpenAIResponseClient client = new(\n model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nstring userInputText = \"What was a positive news story from today?\";\n\nResponseCreationOptions options = new()\n{\n Tools =\n {\n ResponseTool.CreateWebSearchTool()\n },\n};\n\nOpenAIResponse response = client.CreateResponse(userInputText, options);\n\nConsole.WriteLine(response.GetOutputText());\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.responses.create();\n\nconsole.log(response.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.Response;\nimport com.openai.models.responses.ResponseCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Response response = client.responses().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.responses.create\n\nputs(response)" + }, + "response": "{\n \"id\": \"resp_67ccf18ef5fc8190b16dbee19bc54e5f087bb177ab789d5c\",\n \"object\": \"response\",\n \"created_at\": 1741484430,\n \"status\": \"completed\",\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4.1-2025-04-14\",\n \"output\": [\n {\n \"type\": \"web_search_call\",\n \"id\": \"ws_67ccf18f64008190a39b619f4c8455ef087bb177ab789d5c\",\n \"status\": \"completed\"\n },\n {\n \"type\": \"message\",\n \"id\": \"msg_67ccf190ca3881909d433c50b1f6357e087bb177ab789d5c\",\n \"status\": \"completed\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"output_text\",\n \"text\": \"As of today, March 9, 2025, one notable positive news story...\",\n \"annotations\": [\n {\n \"type\": \"url_citation\",\n \"start_index\": 442,\n \"end_index\": 557,\n \"url\": \"https://.../?utm_source=chatgpt.com\",\n \"title\": \"...\"\n },\n {\n \"type\": \"url_citation\",\n \"start_index\": 962,\n \"end_index\": 1077,\n \"url\": \"https://.../?utm_source=chatgpt.com\",\n \"title\": \"...\"\n },\n {\n \"type\": \"url_citation\",\n \"start_index\": 1336,\n \"end_index\": 1451,\n \"url\": \"https://.../?utm_source=chatgpt.com\",\n \"title\": \"...\"\n }\n ]\n }\n ]\n }\n ],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": null,\n \"summary\": null\n },\n \"store\": true,\n \"temperature\": 1.0,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [\n {\n \"type\": \"web_search_preview\",\n \"domains\": [],\n \"search_context_size\": \"medium\",\n \"user_location\": {\n \"type\": \"approximate\",\n \"city\": null,\n \"country\": \"US\",\n \"region\": null,\n \"timezone\": null\n }\n }\n ],\n \"top_p\": 1.0,\n \"truncation\": \"disabled\",\n \"usage\": {\n \"input_tokens\": 328,\n \"input_tokens_details\": {\n \"cached_tokens\": 0\n },\n \"output_tokens\": 356,\n \"output_tokens_details\": {\n \"reasoning_tokens\": 0\n },\n \"total_tokens\": 684\n },\n \"user\": null,\n \"metadata\": {}\n}\n" + }, + { + "title": "File search", + "request": { + "curl": "curl https://api.openai.com/v1/responses \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"gpt-4.1\",\n \"tools\": [{\n \"type\": \"file_search\",\n \"vector_store_ids\": [\"vs_1234567890\"],\n \"max_num_results\": 20\n }],\n \"input\": \"What are the attributes of an ancient brown dragon?\"\n }'\n", + "javascript": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nconst response = await openai.responses.create({\n model: \"gpt-4.1\",\n tools: [{\n type: \"file_search\",\n vector_store_ids: [\"vs_1234567890\"],\n max_num_results: 20\n }],\n input: \"What are the attributes of an ancient brown dragon?\",\n});\n\nconsole.log(response);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.responses.create()\nprint(response.id)", + "csharp": "using System;\n\nusing OpenAI.Responses;\n\nOpenAIResponseClient client = new(\n model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nstring userInputText = \"What are the attributes of an ancient brown dragon?\";\n\nResponseCreationOptions options = new()\n{\n Tools =\n {\n ResponseTool.CreateFileSearchTool(\n vectorStoreIds: [\"vs_1234567890\"],\n maxResultCount: 20\n )\n },\n};\n\nOpenAIResponse response = client.CreateResponse(userInputText, options);\n\nConsole.WriteLine(response.GetOutputText());\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.responses.create();\n\nconsole.log(response.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.Response;\nimport com.openai.models.responses.ResponseCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Response response = client.responses().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.responses.create\n\nputs(response)" + }, + "response": "{\n \"id\": \"resp_67ccf4c55fc48190b71bd0463ad3306d09504fb6872380d7\",\n \"object\": \"response\",\n \"created_at\": 1741485253,\n \"status\": \"completed\",\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4.1-2025-04-14\",\n \"output\": [\n {\n \"type\": \"file_search_call\",\n \"id\": \"fs_67ccf4c63cd08190887ef6464ba5681609504fb6872380d7\",\n \"status\": \"completed\",\n \"queries\": [\n \"attributes of an ancient brown dragon\"\n ],\n \"results\": null\n },\n {\n \"type\": \"message\",\n \"id\": \"msg_67ccf4c93e5c81909d595b369351a9d309504fb6872380d7\",\n \"status\": \"completed\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"output_text\",\n \"text\": \"The attributes of an ancient brown dragon include...\",\n \"annotations\": [\n {\n \"type\": \"file_citation\",\n \"index\": 320,\n \"file_id\": \"file-4wDz5b167pAf72nx1h9eiN\",\n \"filename\": \"dragons.pdf\"\n },\n {\n \"type\": \"file_citation\",\n \"index\": 576,\n \"file_id\": \"file-4wDz5b167pAf72nx1h9eiN\",\n \"filename\": \"dragons.pdf\"\n },\n {\n \"type\": \"file_citation\",\n \"index\": 815,\n \"file_id\": \"file-4wDz5b167pAf72nx1h9eiN\",\n \"filename\": \"dragons.pdf\"\n },\n {\n \"type\": \"file_citation\",\n \"index\": 815,\n \"file_id\": \"file-4wDz5b167pAf72nx1h9eiN\",\n \"filename\": \"dragons.pdf\"\n },\n {\n \"type\": \"file_citation\",\n \"index\": 1030,\n \"file_id\": \"file-4wDz5b167pAf72nx1h9eiN\",\n \"filename\": \"dragons.pdf\"\n },\n {\n \"type\": \"file_citation\",\n \"index\": 1030,\n \"file_id\": \"file-4wDz5b167pAf72nx1h9eiN\",\n \"filename\": \"dragons.pdf\"\n },\n {\n \"type\": \"file_citation\",\n \"index\": 1156,\n \"file_id\": \"file-4wDz5b167pAf72nx1h9eiN\",\n \"filename\": \"dragons.pdf\"\n },\n {\n \"type\": \"file_citation\",\n \"index\": 1225,\n \"file_id\": \"file-4wDz5b167pAf72nx1h9eiN\",\n \"filename\": \"dragons.pdf\"\n }\n ]\n }\n ]\n }\n ],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": null,\n \"summary\": null\n },\n \"store\": true,\n \"temperature\": 1.0,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [\n {\n \"type\": \"file_search\",\n \"filters\": null,\n \"max_num_results\": 20,\n \"ranking_options\": {\n \"ranker\": \"auto\",\n \"score_threshold\": 0.0\n },\n \"vector_store_ids\": [\n \"vs_1234567890\"\n ]\n }\n ],\n \"top_p\": 1.0,\n \"truncation\": \"disabled\",\n \"usage\": {\n \"input_tokens\": 18307,\n \"input_tokens_details\": {\n \"cached_tokens\": 0\n },\n \"output_tokens\": 348,\n \"output_tokens_details\": {\n \"reasoning_tokens\": 0\n },\n \"total_tokens\": 18655\n },\n \"user\": null,\n \"metadata\": {}\n}\n" + }, + { + "title": "Streaming", + "request": { + "curl": "curl https://api.openai.com/v1/responses \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"gpt-4.1\",\n \"instructions\": \"You are a helpful assistant.\",\n \"input\": \"Hello!\",\n \"stream\": true\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.responses.create()\nprint(response.id)", + "javascript": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nconst response = await openai.responses.create({\n model: \"gpt-4.1\",\n instructions: \"You are a helpful assistant.\",\n input: \"Hello!\",\n stream: true,\n});\n\nfor await (const event of response) {\n console.log(event);\n}\n", + "csharp": "using System;\nusing System.ClientModel;\nusing System.Threading.Tasks;\n\nusing OpenAI.Responses;\n\nOpenAIResponseClient client = new( model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nstring userInputText = \"Hello!\";\n\nResponseCreationOptions options = new()\n{ Instructions = \"You are a helpful assistant.\",\n};\n\nAsyncCollectionResult responseUpdates = client.CreateResponseStreamingAsync(userInputText, options);\n\nawait foreach (StreamingResponseUpdate responseUpdate in responseUpdates)\n{ if (responseUpdate is StreamingResponseOutputTextDeltaUpdate outputTextDeltaUpdate)\n {\n Console.Write(outputTextDeltaUpdate.Delta);\n }\n}\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.responses.create();\n\nconsole.log(response.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.Response;\nimport com.openai.models.responses.ResponseCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Response response = client.responses().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.responses.create\n\nputs(response)" + }, + "response": "event: response.created\ndata: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654\",\"object\":\"response\",\"created_at\":1741290958,\"status\":\"in_progress\",\"error\":null,\"incomplete_details\":null,\"instructions\":\"You are a helpful assistant.\",\"max_output_tokens\":null,\"model\":\"gpt-4.1-2025-04-14\",\"output\":[],\"parallel_tool_calls\":true,\"previous_response_id\":null,\"reasoning\":{\"effort\":null,\"summary\":null},\"store\":true,\"temperature\":1.0,\"text\":{\"format\":{\"type\":\"text\"}},\"tool_choice\":\"auto\",\"tools\":[],\"top_p\":1.0,\"truncation\":\"disabled\",\"usage\":null,\"user\":null,\"metadata\":{}}}\n\nevent: response.in_progress\ndata: {\"type\":\"response.in_progress\",\"response\":{\"id\":\"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654\",\"object\":\"response\",\"created_at\":1741290958,\"status\":\"in_progress\",\"error\":null,\"incomplete_details\":null,\"instructions\":\"You are a helpful assistant.\",\"max_output_tokens\":null,\"model\":\"gpt-4.1-2025-04-14\",\"output\":[],\"parallel_tool_calls\":true,\"previous_response_id\":null,\"reasoning\":{\"effort\":null,\"summary\":null},\"store\":true,\"temperature\":1.0,\"text\":{\"format\":{\"type\":\"text\"}},\"tool_choice\":\"auto\",\"tools\":[],\"top_p\":1.0,\"truncation\":\"disabled\",\"usage\":null,\"user\":null,\"metadata\":{}}}\n\nevent: response.output_item.added\ndata: {\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"id\":\"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654\",\"type\":\"message\",\"status\":\"in_progress\",\"role\":\"assistant\",\"content\":[]}}\n\nevent: response.content_part.added\ndata: {\"type\":\"response.content_part.added\",\"item_id\":\"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654\",\"output_index\":0,\"content_index\":0,\"part\":{\"type\":\"output_text\",\"text\":\"\",\"annotations\":[]}}\n\nevent: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"item_id\":\"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654\",\"output_index\":0,\"content_index\":0,\"delta\":\"Hi\"}\n\n...\n\nevent: response.output_text.done\ndata: {\"type\":\"response.output_text.done\",\"item_id\":\"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654\",\"output_index\":0,\"content_index\":0,\"text\":\"Hi there! How can I assist you today?\"}\n\nevent: response.content_part.done\ndata: {\"type\":\"response.content_part.done\",\"item_id\":\"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654\",\"output_index\":0,\"content_index\":0,\"part\":{\"type\":\"output_text\",\"text\":\"Hi there! How can I assist you today?\",\"annotations\":[]}}\n\nevent: response.output_item.done\ndata: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654\",\"type\":\"message\",\"status\":\"completed\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Hi there! How can I assist you today?\",\"annotations\":[]}]}}\n\nevent: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654\",\"object\":\"response\",\"created_at\":1741290958,\"status\":\"completed\",\"error\":null,\"incomplete_details\":null,\"instructions\":\"You are a helpful assistant.\",\"max_output_tokens\":null,\"model\":\"gpt-4.1-2025-04-14\",\"output\":[{\"id\":\"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654\",\"type\":\"message\",\"status\":\"completed\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Hi there! How can I assist you today?\",\"annotations\":[]}]}],\"parallel_tool_calls\":true,\"previous_response_id\":null,\"reasoning\":{\"effort\":null,\"summary\":null},\"store\":true,\"temperature\":1.0,\"text\":{\"format\":{\"type\":\"text\"}},\"tool_choice\":\"auto\",\"tools\":[],\"top_p\":1.0,\"truncation\":\"disabled\",\"usage\":{\"input_tokens\":37,\"output_tokens\":11,\"output_tokens_details\":{\"reasoning_tokens\":0},\"total_tokens\":48},\"user\":null,\"metadata\":{}}}\n" + }, + { + "title": "Functions", + "request": { + "curl": "curl https://api.openai.com/v1/responses \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"gpt-4.1\",\n \"input\": \"What is the weather like in Boston today?\",\n \"tools\": [\n {\n \"type\": \"function\",\n \"name\": \"get_current_weather\",\n \"description\": \"Get the current weather in a given location\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and state, e.g. San Francisco, CA\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\"celsius\", \"fahrenheit\"]\n }\n },\n \"required\": [\"location\", \"unit\"]\n }\n }\n ],\n \"tool_choice\": \"auto\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.responses.create()\nprint(response.id)", + "javascript": "import OpenAI from \"openai\";\n\nconst openai = new OpenAI();\n\nconst tools = [\n {\n type: \"function\",\n name: \"get_current_weather\",\n description: \"Get the current weather in a given location\",\n parameters: {\n type: \"object\",\n properties: {\n location: {\n type: \"string\",\n description: \"The city and state, e.g. San Francisco, CA\",\n },\n unit: { type: \"string\", enum: [\"celsius\", \"fahrenheit\"] },\n },\n required: [\"location\", \"unit\"],\n },\n },\n];\n\nconst response = await openai.responses.create({\n model: \"gpt-4.1\",\n tools: tools,\n input: \"What is the weather like in Boston today?\",\n tool_choice: \"auto\",\n});\n\nconsole.log(response);\n", + "csharp": "using System;\nusing OpenAI.Responses;\n\nOpenAIResponseClient client = new(\n model: \"gpt-4.1\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nResponseTool getCurrentWeatherFunctionTool = ResponseTool.CreateFunctionTool(\n functionName: \"get_current_weather\",\n functionDescription: \"Get the current weather in a given location\",\n functionParameters: BinaryData.FromString(\"\"\"\n {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and state, e.g. San Francisco, CA\"\n },\n \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"]}\n },\n \"required\": [\"location\", \"unit\"]\n }\n \"\"\"\n )\n);\n\nstring userInputText = \"What is the weather like in Boston today?\";\n\nResponseCreationOptions options = new()\n{\n Tools =\n {\n getCurrentWeatherFunctionTool\n },\n ToolChoice = ResponseToolChoice.CreateAutoChoice(),\n};\n\nOpenAIResponse response = client.CreateResponse(userInputText, options);\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.responses.create();\n\nconsole.log(response.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.Response;\nimport com.openai.models.responses.ResponseCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Response response = client.responses().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.responses.create\n\nputs(response)" + }, + "response": "{\n \"id\": \"resp_67ca09c5efe0819096d0511c92b8c890096610f474011cc0\",\n \"object\": \"response\",\n \"created_at\": 1741294021,\n \"status\": \"completed\",\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4.1-2025-04-14\",\n \"output\": [\n {\n \"type\": \"function_call\",\n \"id\": \"fc_67ca09c6bedc8190a7abfec07b1a1332096610f474011cc0\",\n \"call_id\": \"call_unLAR8MvFNptuiZK6K6HCy5k\",\n \"name\": \"get_current_weather\",\n \"arguments\": \"{\\\"location\\\":\\\"Boston, MA\\\",\\\"unit\\\":\\\"celsius\\\"}\",\n \"status\": \"completed\"\n }\n ],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": null,\n \"summary\": null\n },\n \"store\": true,\n \"temperature\": 1.0,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [\n {\n \"type\": \"function\",\n \"description\": \"Get the current weather in a given location\",\n \"name\": \"get_current_weather\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and state, e.g. San Francisco, CA\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"celsius\",\n \"fahrenheit\"\n ]\n }\n },\n \"required\": [\n \"location\",\n \"unit\"\n ]\n },\n \"strict\": true\n }\n ],\n \"top_p\": 1.0,\n \"truncation\": \"disabled\",\n \"usage\": {\n \"input_tokens\": 291,\n \"output_tokens\": 23,\n \"output_tokens_details\": {\n \"reasoning_tokens\": 0\n },\n \"total_tokens\": 314\n },\n \"user\": null,\n \"metadata\": {}\n}\n" + }, + { + "title": "Reasoning", + "request": { + "curl": "curl https://api.openai.com/v1/responses \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"model\": \"o3-mini\",\n \"input\": \"How much wood would a woodchuck chuck?\",\n \"reasoning\": {\n \"effort\": \"high\"\n }\n }'\n", + "javascript": "import OpenAI from \"openai\";\nconst openai = new OpenAI();\n\nconst response = await openai.responses.create({\n model: \"o3-mini\",\n input: \"How much wood would a woodchuck chuck?\",\n reasoning: {\n effort: \"high\"\n }\n});\n\nconsole.log(response);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.responses.create()\nprint(response.id)", + "csharp": "using System;\nusing OpenAI.Responses;\n\nOpenAIResponseClient client = new(\n model: \"o3-mini\",\n apiKey: Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n);\n\nstring userInputText = \"How much wood would a woodchuck chuck?\";\n\nResponseCreationOptions options = new()\n{\n ReasoningOptions = new()\n {\n ReasoningEffortLevel = ResponseReasoningEffortLevel.High,\n },\n};\n\nOpenAIResponse response = client.CreateResponse(userInputText, options);\n\nConsole.WriteLine(response.GetOutputText());\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.responses.create();\n\nconsole.log(response.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.Response;\nimport com.openai.models.responses.ResponseCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Response response = client.responses().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.responses.create\n\nputs(response)" + }, + "response": "{\n \"id\": \"resp_67ccd7eca01881908ff0b5146584e408072912b2993db808\",\n \"object\": \"response\",\n \"created_at\": 1741477868,\n \"status\": \"completed\",\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"o1-2024-12-17\",\n \"output\": [\n {\n \"type\": \"message\",\n \"id\": \"msg_67ccd7f7b5848190a6f3e95d809f6b44072912b2993db808\",\n \"status\": \"completed\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"output_text\",\n \"text\": \"The classic tongue twister...\",\n \"annotations\": []\n }\n ]\n }\n ],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": \"high\",\n \"summary\": null\n },\n \"store\": true,\n \"temperature\": 1.0,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_p\": 1.0,\n \"truncation\": \"disabled\",\n \"usage\": {\n \"input_tokens\": 81,\n \"input_tokens_details\": {\n \"cached_tokens\": 0\n },\n \"output_tokens\": 1035,\n \"output_tokens_details\": {\n \"reasoning_tokens\": 832\n },\n \"total_tokens\": 1116\n },\n \"user\": null,\n \"metadata\": {}\n}\n" + } + ] + }, + "description": "Creates a model response. Provide [text](https://platform.openai.com/docs/guides/text) or\n[image](https://platform.openai.com/docs/guides/images) inputs to generate [text](https://platform.openai.com/docs/guides/text)\nor [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have the model call\nyour own [custom code](https://platform.openai.com/docs/guides/function-calling) or use built-in\n[tools](https://platform.openai.com/docs/guides/tools) like [web search](https://platform.openai.com/docs/guides/tools-web-search)\nor [file search](https://platform.openai.com/docs/guides/tools-file-search) to use your own data\nas input for the model's response.\n" + } + }, + "/responses/{response_id}": { + "get": { + "operationId": "getResponse", + "tags": [ + "Responses" + ], + "summary": "Get a model response", + "parameters": [ + { + "in": "path", + "name": "response_id", + "required": true, + "schema": { + "type": "string", + "example": "resp_677efb5139a88190b512bc3fef8e535d" + }, + "description": "The ID of the response to retrieve." + }, + { + "in": "query", + "name": "include", + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Includable" + } + }, + "description": "Additional fields to include in the response. See the `include`\nparameter for Response creation above for more information.\n" + }, + { + "in": "query", + "name": "stream", + "schema": { + "type": "boolean" + }, + "description": "If set to true, the model response data will be streamed to the client\nas it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\nSee the [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)\nfor more information.\n" + }, + { + "in": "query", + "name": "starting_after", + "schema": { + "type": "integer" + }, + "description": "The sequence number of the event after which to start streaming.\n" + }, + { + "in": "query", + "name": "include_obfuscation", + "schema": { + "type": "boolean" + }, + "description": "When true, stream obfuscation will be enabled. Stream obfuscation adds\nrandom characters to an `obfuscation` field on streaming delta events\nto normalize payload sizes as a mitigation to certain side-channel\nattacks. These obfuscation fields are included by default, but add a\nsmall amount of overhead to the data stream. You can set\n`include_obfuscation` to false to optimize for bandwidth if you trust\nthe network links between your application and the OpenAI API.\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Response" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Get a model response", + "group": "responses", + "returns": "The [Response](https://platform.openai.com/docs/api-reference/responses/object) object matching the\nspecified ID.\n", + "examples": { + "response": "{\n \"id\": \"resp_67cb71b351908190a308f3859487620d06981a8637e6bc44\",\n \"object\": \"response\",\n \"created_at\": 1741386163,\n \"status\": \"completed\",\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4o-2024-08-06\",\n \"output\": [\n {\n \"type\": \"message\",\n \"id\": \"msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44\",\n \"status\": \"completed\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"output_text\",\n \"text\": \"Silent circuits hum, \\nThoughts emerge in data streams— \\nDigital dawn breaks.\",\n \"annotations\": []\n }\n ]\n }\n ],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": null,\n \"summary\": null\n },\n \"store\": true,\n \"temperature\": 1.0,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_p\": 1.0,\n \"truncation\": \"disabled\",\n \"usage\": {\n \"input_tokens\": 32,\n \"input_tokens_details\": {\n \"cached_tokens\": 0\n },\n \"output_tokens\": 18,\n \"output_tokens_details\": {\n \"reasoning_tokens\": 0\n },\n \"total_tokens\": 50\n },\n \"user\": null,\n \"metadata\": {}\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/responses/resp_123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst response = await client.responses.retrieve(\"resp_123\");\nconsole.log(response);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.responses.retrieve(\n response_id=\"resp_677efb5139a88190b512bc3fef8e535d\",\n)\nprint(response.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.responses.retrieve('resp_677efb5139a88190b512bc3fef8e535d');\n\nconsole.log(response.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Responses.Get(\n context.TODO(),\n \"resp_677efb5139a88190b512bc3fef8e535d\",\n responses.ResponseGetParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.Response;\nimport com.openai.models.responses.ResponseRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Response response = client.responses().retrieve(\"resp_677efb5139a88190b512bc3fef8e535d\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.responses.retrieve(\"resp_677efb5139a88190b512bc3fef8e535d\")\n\nputs(response)" + } + } + }, + "description": "Retrieves a model response with the given ID.\n" + }, + "delete": { + "operationId": "deleteResponse", + "tags": [ + "Responses" + ], + "summary": "Delete a model response", + "parameters": [ + { + "in": "path", + "name": "response_id", + "required": true, + "schema": { + "type": "string", + "example": "resp_677efb5139a88190b512bc3fef8e535d" + }, + "description": "The ID of the response to delete." + } + ], + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete a model response", + "group": "responses", + "returns": "A success message.\n", + "examples": { + "response": "{\n \"id\": \"resp_6786a1bec27481909a17d673315b29f6\",\n \"object\": \"response\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/responses/resp_123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst response = await client.responses.delete(\"resp_123\");\nconsole.log(response);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nclient.responses.delete(\n \"resp_677efb5139a88190b512bc3fef8e535d\",\n)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nawait client.responses.delete('resp_677efb5139a88190b512bc3fef8e535d');", + "go": "package main\n\nimport (\n \"context\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n err := client.Responses.Delete(context.TODO(), \"resp_677efb5139a88190b512bc3fef8e535d\")\n if err != nil {\n panic(err.Error())\n }\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.ResponseDeleteParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n client.responses().delete(\"resp_677efb5139a88190b512bc3fef8e535d\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresult = openai.responses.delete(\"resp_677efb5139a88190b512bc3fef8e535d\")\n\nputs(result)" + } + } + }, + "description": "Deletes a model response with the given ID.\n" + } + }, + "/responses/{response_id}/cancel": { + "post": { + "operationId": "cancelResponse", + "tags": [ + "Responses" + ], + "summary": "Cancel a response", + "parameters": [ + { + "in": "path", + "name": "response_id", + "required": true, + "schema": { + "type": "string", + "example": "resp_677efb5139a88190b512bc3fef8e535d" + }, + "description": "The ID of the response to cancel." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Response" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Cancel a response", + "group": "responses", + "returns": "A [Response](https://platform.openai.com/docs/api-reference/responses/object) object.\n", + "examples": { + "response": "{\n \"id\": \"resp_67cb71b351908190a308f3859487620d06981a8637e6bc44\",\n \"object\": \"response\",\n \"created_at\": 1741386163,\n \"status\": \"completed\",\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4o-2024-08-06\",\n \"output\": [\n {\n \"type\": \"message\",\n \"id\": \"msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44\",\n \"status\": \"completed\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"output_text\",\n \"text\": \"Silent circuits hum, \\nThoughts emerge in data streams— \\nDigital dawn breaks.\",\n \"annotations\": []\n }\n ]\n }\n ],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": null,\n \"summary\": null\n },\n \"store\": true,\n \"temperature\": 1.0,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_p\": 1.0,\n \"truncation\": \"disabled\",\n \"usage\": {\n \"input_tokens\": 32,\n \"input_tokens_details\": {\n \"cached_tokens\": 0\n },\n \"output_tokens\": 18,\n \"output_tokens_details\": {\n \"reasoning_tokens\": 0\n },\n \"total_tokens\": 50\n },\n \"user\": null,\n \"metadata\": {}\n}\n", + "request": { + "curl": "curl -X POST https://api.openai.com/v1/responses/resp_123/cancel \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst response = await client.responses.cancel(\"resp_123\");\nconsole.log(response);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nresponse = client.responses.cancel(\n \"resp_677efb5139a88190b512bc3fef8e535d\",\n)\nprint(response.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst response = await client.responses.cancel('resp_677efb5139a88190b512bc3fef8e535d');\n\nconsole.log(response.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n response, err := client.Responses.Cancel(context.TODO(), \"resp_677efb5139a88190b512bc3fef8e535d\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", response.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.Response;\nimport com.openai.models.responses.ResponseCancelParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Response response = client.responses().cancel(\"resp_677efb5139a88190b512bc3fef8e535d\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nresponse = openai.responses.cancel(\"resp_677efb5139a88190b512bc3fef8e535d\")\n\nputs(response)" + } + } + }, + "description": "Cancels a model response with the given ID. Only responses created with\nthe `background` parameter set to `true` can be cancelled. \n[Learn more](https://platform.openai.com/docs/guides/background).\n" + } + }, + "/responses/{response_id}/input_items": { + "get": { + "operationId": "listInputItems", + "tags": [ + "Responses" + ], + "summary": "List input items", + "parameters": [ + { + "in": "path", + "name": "response_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the response to retrieve input items for." + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between\n1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "in": "query", + "name": "order", + "schema": { + "type": "string", + "enum": [ + "asc", + "desc" + ] + }, + "description": "The order to return the input items in. Default is `desc`.\n- `asc`: Return the input items in ascending order.\n- `desc`: Return the input items in descending order.\n" + }, + { + "in": "query", + "name": "after", + "schema": { + "type": "string" + }, + "description": "An item ID to list items after, used in pagination.\n" + }, + { + "in": "query", + "name": "include", + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Includable" + } + }, + "description": "Additional fields to include in the response. See the `include`\nparameter for Response creation above for more information.\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResponseItemList" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List input items", + "group": "responses", + "returns": "A list of input item objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"msg_abc123\",\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"input_text\",\n \"text\": \"Tell me a three sentence bedtime story about a unicorn.\"\n }\n ]\n }\n ],\n \"first_id\": \"msg_abc123\",\n \"last_id\": \"msg_abc123\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/responses/resp_abc123/input_items \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "javascript": "import OpenAI from \"openai\";\nconst client = new OpenAI();\n\nconst response = await client.responses.inputItems.list(\"resp_123\");\nconsole.log(response.data);\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.responses.input_items.list(\n response_id=\"response_id\",\n)\npage = page.data[0]\nprint(page)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const responseItem of client.responses.inputItems.list('response_id')) {\n console.log(responseItem);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n \"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Responses.InputItems.List(\n context.TODO(),\n \"response_id\",\n responses.InputItemListParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.responses.inputitems.InputItemListPage;\nimport com.openai.models.responses.inputitems.InputItemListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n InputItemListPage page = client.responses().inputItems().list(\"response_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.responses.input_items.list(\"response_id\")\n\nputs(page)" + } + } + }, + "description": "Returns a list of input items for a given response." + } + }, + "/threads": { + "post": { + "operationId": "createThread", + "tags": [ + "Assistants" + ], + "summary": "Create thread", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateThreadRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ThreadObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create thread", + "group": "threads", + "beta": true, + "returns": "A [thread](https://platform.openai.com/docs/api-reference/threads) object.", + "examples": [ + { + "title": "Empty", + "request": { + "curl": "curl https://api.openai.com/v1/threads \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d ''\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nthread = client.beta.threads.create()\nprint(thread.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst thread = await client.beta.threads.create();\n\nconsole.log(thread.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n thread, err := client.Beta.Threads.New(context.TODO(), openai.BetaThreadNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", thread.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.Thread;\nimport com.openai.models.beta.threads.ThreadCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Thread thread = client.beta().threads().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nthread = openai.beta.threads.create\n\nputs(thread)" + }, + "response": "{\n \"id\": \"thread_abc123\",\n \"object\": \"thread\",\n \"created_at\": 1699012949,\n \"metadata\": {},\n \"tool_resources\": {}\n}\n" + }, + { + "title": "Messages", + "request": { + "curl": "curl https://api.openai.com/v1/threads \\\n-H \"Content-Type: application/json\" \\\n-H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n-H \"OpenAI-Beta: assistants=v2\" \\\n-d '{\n \"messages\": [{\n \"role\": \"user\",\n \"content\": \"Hello, what is AI?\"\n }, {\n \"role\": \"user\",\n \"content\": \"How does AI work? Explain it in simple terms.\"\n }]\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nthread = client.beta.threads.create()\nprint(thread.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst thread = await client.beta.threads.create();\n\nconsole.log(thread.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n thread, err := client.Beta.Threads.New(context.TODO(), openai.BetaThreadNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", thread.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.Thread;\nimport com.openai.models.beta.threads.ThreadCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Thread thread = client.beta().threads().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nthread = openai.beta.threads.create\n\nputs(thread)" + }, + "response": "{\n \"id\": \"thread_abc123\",\n \"object\": \"thread\",\n \"created_at\": 1699014083,\n \"metadata\": {},\n \"tool_resources\": {}\n}\n" + } + ] + }, + "description": "Create a thread." + } + }, + "/threads/runs": { + "post": { + "operationId": "createThreadAndRun", + "tags": [ + "Assistants" + ], + "summary": "Create thread and run", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateThreadAndRunRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create thread and run", + "group": "threads", + "beta": true, + "returns": "A [run](https://platform.openai.com/docs/api-reference/runs/object) object.", + "examples": [ + { + "title": "Default", + "request": { + "curl": "curl https://api.openai.com/v1/threads/runs \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"assistant_id\": \"asst_abc123\",\n \"thread\": {\n \"messages\": [\n {\"role\": \"user\", \"content\": \"Explain deep learning to a 5 year old.\"}\n ]\n }\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.create_and_run(\n assistant_id=\"assistant_id\",\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' });\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{\n AssistantID: \"assistant_id\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.ThreadCreateAndRunParams;\nimport com.openai.models.beta.threads.runs.Run;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder()\n .assistantId(\"assistant_id\")\n .build();\n Run run = client.beta().threads().createAndRun(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.create_and_run(assistant_id: \"assistant_id\")\n\nputs(run)" + }, + "response": "{\n \"id\": \"run_abc123\",\n \"object\": \"thread.run\",\n \"created_at\": 1699076792,\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"status\": \"queued\",\n \"started_at\": null,\n \"expires_at\": 1699077392,\n \"cancelled_at\": null,\n \"failed_at\": null,\n \"completed_at\": null,\n \"required_action\": null,\n \"last_error\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You are a helpful assistant.\",\n \"tools\": [],\n \"tool_resources\": {},\n \"metadata\": {},\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_completion_tokens\": null,\n \"max_prompt_tokens\": null,\n \"truncation_strategy\": {\n \"type\": \"auto\",\n \"last_messages\": null\n },\n \"incomplete_details\": null,\n \"usage\": null,\n \"response_format\": \"auto\",\n \"tool_choice\": \"auto\",\n \"parallel_tool_calls\": true\n}\n" + }, + { + "title": "Streaming", + "request": { + "curl": "curl https://api.openai.com/v1/threads/runs \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"assistant_id\": \"asst_123\",\n \"thread\": {\n \"messages\": [\n {\"role\": \"user\", \"content\": \"Hello\"}\n ]\n },\n \"stream\": true\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.create_and_run(\n assistant_id=\"assistant_id\",\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' });\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{\n AssistantID: \"assistant_id\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.ThreadCreateAndRunParams;\nimport com.openai.models.beta.threads.runs.Run;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder()\n .assistantId(\"assistant_id\")\n .build();\n Run run = client.beta().threads().createAndRun(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.create_and_run(assistant_id: \"assistant_id\")\n\nputs(run)" + }, + "response": "event: thread.created\ndata: {\"id\":\"thread_123\",\"object\":\"thread\",\"created_at\":1710348075,\"metadata\":{}}\n\nevent: thread.run.created\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710348075,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"queued\",\"started_at\":null,\"expires_at\":1710348675,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"tool_resources\":{},\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}\n\nevent: thread.run.queued\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710348075,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"queued\",\"started_at\":null,\"expires_at\":1710348675,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"tool_resources\":{},\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}\n\nevent: thread.run.in_progress\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710348075,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"in_progress\",\"started_at\":null,\"expires_at\":1710348675,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"tool_resources\":{},\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}\n\nevent: thread.run.step.created\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710348076,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"in_progress\",\"cancelled_at\":null,\"completed_at\":null,\"expires_at\":1710348675,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_001\"}},\"usage\":null}\n\nevent: thread.run.step.in_progress\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710348076,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"in_progress\",\"cancelled_at\":null,\"completed_at\":null,\"expires_at\":1710348675,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_001\"}},\"usage\":null}\n\nevent: thread.message.created\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message\",\"created_at\":1710348076,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"in_progress\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":null,\"role\":\"assistant\",\"content\":[], \"metadata\":{}}\n\nevent: thread.message.in_progress\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message\",\"created_at\":1710348076,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"in_progress\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":null,\"role\":\"assistant\",\"content\":[], \"metadata\":{}}\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\"Hello\",\"annotations\":[]}}]}}\n\n...\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\" today\"}}]}}\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\"?\"}}]}}\n\nevent: thread.message.completed\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message\",\"created_at\":1710348076,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"completed\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":1710348077,\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":{\"value\":\"Hello! How can I assist you today?\",\"annotations\":[]}}], \"metadata\":{}}\n\nevent: thread.run.step.completed\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710348076,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"completed\",\"cancelled_at\":null,\"completed_at\":1710348077,\"expires_at\":1710348675,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_001\"}},\"usage\":{\"prompt_tokens\":20,\"completion_tokens\":11,\"total_tokens\":31}}\n\nevent: thread.run.completed\n{\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710348076,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"completed\",\"started_at\":1713226836,\"expires_at\":null,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":1713226837,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":{\"prompt_tokens\":345,\"completion_tokens\":11,\"total_tokens\":356},\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}\n\nevent: done\ndata: [DONE]\n" + }, + { + "title": "Streaming with Functions", + "request": { + "curl": "curl https://api.openai.com/v1/threads/runs \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"assistant_id\": \"asst_abc123\",\n \"thread\": {\n \"messages\": [\n {\"role\": \"user\", \"content\": \"What is the weather like in San Francisco?\"}\n ]\n },\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_current_weather\",\n \"description\": \"Get the current weather in a given location\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and state, e.g. San Francisco, CA\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\"celsius\", \"fahrenheit\"]\n }\n },\n \"required\": [\"location\"]\n }\n }\n }\n ],\n \"stream\": true\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.create_and_run(\n assistant_id=\"assistant_id\",\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' });\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{\n AssistantID: \"assistant_id\",\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.ThreadCreateAndRunParams;\nimport com.openai.models.beta.threads.runs.Run;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder()\n .assistantId(\"assistant_id\")\n .build();\n Run run = client.beta().threads().createAndRun(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.create_and_run(assistant_id: \"assistant_id\")\n\nputs(run)" + }, + "response": "event: thread.created\ndata: {\"id\":\"thread_123\",\"object\":\"thread\",\"created_at\":1710351818,\"metadata\":{}}\n\nevent: thread.run.created\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710351818,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"queued\",\"started_at\":null,\"expires_at\":1710352418,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_current_weather\",\"description\":\"Get the current weather in a given location\",\"parameters\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"The city and state, e.g. San Francisco, CA\"},\"unit\":{\"type\":\"string\",\"enum\":[\"celsius\",\"fahrenheit\"]}},\"required\":[\"location\"]}}}],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.queued\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710351818,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"queued\",\"started_at\":null,\"expires_at\":1710352418,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_current_weather\",\"description\":\"Get the current weather in a given location\",\"parameters\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"The city and state, e.g. San Francisco, CA\"},\"unit\":{\"type\":\"string\",\"enum\":[\"celsius\",\"fahrenheit\"]}},\"required\":[\"location\"]}}}],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.in_progress\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710351818,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"in_progress\",\"started_at\":1710351818,\"expires_at\":1710352418,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_current_weather\",\"description\":\"Get the current weather in a given location\",\"parameters\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"The city and state, e.g. San Francisco, CA\"},\"unit\":{\"type\":\"string\",\"enum\":[\"celsius\",\"fahrenheit\"]}},\"required\":[\"location\"]}}}],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.step.created\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710351819,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"tool_calls\",\"status\":\"in_progress\",\"cancelled_at\":null,\"completed_at\":null,\"expires_at\":1710352418,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"tool_calls\",\"tool_calls\":[]},\"usage\":null}\n\nevent: thread.run.step.in_progress\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710351819,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"tool_calls\",\"status\":\"in_progress\",\"cancelled_at\":null,\"completed_at\":null,\"expires_at\":1710352418,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"tool_calls\",\"tool_calls\":[]},\"usage\":null}\n\nevent: thread.run.step.delta\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step.delta\",\"delta\":{\"step_details\":{\"type\":\"tool_calls\",\"tool_calls\":[{\"index\":0,\"id\":\"call_XXNp8YGaFrjrSjgqxtC8JJ1B\",\"type\":\"function\",\"function\":{\"name\":\"get_current_weather\",\"arguments\":\"\",\"output\":null}}]}}}\n\nevent: thread.run.step.delta\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step.delta\",\"delta\":{\"step_details\":{\"type\":\"tool_calls\",\"tool_calls\":[{\"index\":0,\"type\":\"function\",\"function\":{\"arguments\":\"{\\\"\"}}]}}}\n\nevent: thread.run.step.delta\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step.delta\",\"delta\":{\"step_details\":{\"type\":\"tool_calls\",\"tool_calls\":[{\"index\":0,\"type\":\"function\",\"function\":{\"arguments\":\"location\"}}]}}}\n\n...\n\nevent: thread.run.step.delta\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step.delta\",\"delta\":{\"step_details\":{\"type\":\"tool_calls\",\"tool_calls\":[{\"index\":0,\"type\":\"function\",\"function\":{\"arguments\":\"ahrenheit\"}}]}}}\n\nevent: thread.run.step.delta\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step.delta\",\"delta\":{\"step_details\":{\"type\":\"tool_calls\",\"tool_calls\":[{\"index\":0,\"type\":\"function\",\"function\":{\"arguments\":\"\\\"}\"}}]}}}\n\nevent: thread.run.requires_action\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710351818,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"requires_action\",\"started_at\":1710351818,\"expires_at\":1710352418,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":{\"type\":\"submit_tool_outputs\",\"submit_tool_outputs\":{\"tool_calls\":[{\"id\":\"call_XXNp8YGaFrjrSjgqxtC8JJ1B\",\"type\":\"function\",\"function\":{\"name\":\"get_current_weather\",\"arguments\":\"{\\\"location\\\":\\\"San Francisco, CA\\\",\\\"unit\\\":\\\"fahrenheit\\\"}\"}}]}},\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_current_weather\",\"description\":\"Get the current weather in a given location\",\"parameters\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"The city and state, e.g. San Francisco, CA\"},\"unit\":{\"type\":\"string\",\"enum\":[\"celsius\",\"fahrenheit\"]}},\"required\":[\"location\"]}}}],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":{\"prompt_tokens\":345,\"completion_tokens\":11,\"total_tokens\":356},\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: done\ndata: [DONE]\n" + } + ] + }, + "description": "Create a thread and run it in one request." + } + }, + "/threads/{thread_id}": { + "get": { + "operationId": "getThread", + "tags": [ + "Assistants" + ], + "summary": "Retrieve thread", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the thread to retrieve." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ThreadObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve thread", + "group": "threads", + "beta": true, + "returns": "The [thread](https://platform.openai.com/docs/api-reference/threads/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"thread_abc123\",\n \"object\": \"thread\",\n \"created_at\": 1699014083,\n \"metadata\": {},\n \"tool_resources\": {\n \"code_interpreter\": {\n \"file_ids\": []\n }\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nthread = client.beta.threads.retrieve(\n \"thread_id\",\n)\nprint(thread.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst thread = await client.beta.threads.retrieve('thread_id');\n\nconsole.log(thread.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n thread, err := client.Beta.Threads.Get(context.TODO(), \"thread_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", thread.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.Thread;\nimport com.openai.models.beta.threads.ThreadRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Thread thread = client.beta().threads().retrieve(\"thread_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nthread = openai.beta.threads.retrieve(\"thread_id\")\n\nputs(thread)" + } + } + }, + "description": "Retrieves a thread." + }, + "post": { + "operationId": "modifyThread", + "tags": [ + "Assistants" + ], + "summary": "Modify thread", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the thread to modify. Only the `metadata` can be modified." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ModifyThreadRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ThreadObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Modify thread", + "group": "threads", + "beta": true, + "returns": "The modified [thread](https://platform.openai.com/docs/api-reference/threads/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"thread_abc123\",\n \"object\": \"thread\",\n \"created_at\": 1699014083,\n \"metadata\": {\n \"modified\": \"true\",\n \"user\": \"abc123\"\n },\n \"tool_resources\": {}\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"metadata\": {\n \"modified\": \"true\",\n \"user\": \"abc123\"\n }\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nthread = client.beta.threads.update(\n thread_id=\"thread_id\",\n)\nprint(thread.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst thread = await client.beta.threads.update('thread_id');\n\nconsole.log(thread.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n thread, err := client.Beta.Threads.Update(\n context.TODO(),\n \"thread_id\",\n openai.BetaThreadUpdateParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", thread.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.Thread;\nimport com.openai.models.beta.threads.ThreadUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Thread thread = client.beta().threads().update(\"thread_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nthread = openai.beta.threads.update(\"thread_id\")\n\nputs(thread)" + } + } + }, + "description": "Modifies a thread." + }, + "delete": { + "operationId": "deleteThread", + "tags": [ + "Assistants" + ], + "summary": "Delete thread", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the thread to delete." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteThreadResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete thread", + "group": "threads", + "beta": true, + "returns": "Deletion status", + "examples": { + "response": "{\n \"id\": \"thread_abc123\",\n \"object\": \"thread.deleted\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -X DELETE\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nthread_deleted = client.beta.threads.delete(\n \"thread_id\",\n)\nprint(thread_deleted.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst threadDeleted = await client.beta.threads.delete('thread_id');\n\nconsole.log(threadDeleted.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n threadDeleted, err := client.Beta.Threads.Delete(context.TODO(), \"thread_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", threadDeleted.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.ThreadDeleteParams;\nimport com.openai.models.beta.threads.ThreadDeleted;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n ThreadDeleted threadDeleted = client.beta().threads().delete(\"thread_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nthread_deleted = openai.beta.threads.delete(\"thread_id\")\n\nputs(thread_deleted)" + } + } + }, + "description": "Delete a thread." + } + }, + "/threads/{thread_id}/messages": { + "get": { + "operationId": "listMessages", + "tags": [ + "Assistants" + ], + "summary": "List messages", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) the messages belong to." + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "before", + "in": "query", + "description": "A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "run_id", + "in": "query", + "description": "Filter messages by the run ID that generated them.\n", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListMessagesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List messages", + "group": "threads", + "beta": true, + "returns": "A list of [message](https://platform.openai.com/docs/api-reference/messages) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"msg_abc123\",\n \"object\": \"thread.message\",\n \"created_at\": 1699016383,\n \"assistant_id\": null,\n \"thread_id\": \"thread_abc123\",\n \"run_id\": null,\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": {\n \"value\": \"How does AI work? Explain it in simple terms.\",\n \"annotations\": []\n }\n }\n ],\n \"attachments\": [],\n \"metadata\": {}\n },\n {\n \"id\": \"msg_abc456\",\n \"object\": \"thread.message\",\n \"created_at\": 1699016383,\n \"assistant_id\": null,\n \"thread_id\": \"thread_abc123\",\n \"run_id\": null,\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": {\n \"value\": \"Hello, what is AI?\",\n \"annotations\": []\n }\n }\n ],\n \"attachments\": [],\n \"metadata\": {}\n }\n ],\n \"first_id\": \"msg_abc123\",\n \"last_id\": \"msg_abc456\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/messages \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.beta.threads.messages.list(\n thread_id=\"thread_id\",\n)\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const message of client.beta.threads.messages.list('thread_id')) {\n console.log(message.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Beta.Threads.Messages.List(\n context.TODO(),\n \"thread_id\",\n openai.BetaThreadMessageListParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.messages.MessageListPage;\nimport com.openai.models.beta.threads.messages.MessageListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n MessageListPage page = client.beta().threads().messages().list(\"thread_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.beta.threads.messages.list(\"thread_id\")\n\nputs(page)" + } + } + }, + "description": "Returns a list of messages for a given thread." + }, + "post": { + "operationId": "createMessage", + "tags": [ + "Assistants" + ], + "summary": "Create message", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to create a message for." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateMessageRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create message", + "group": "threads", + "beta": true, + "returns": "A [message](https://platform.openai.com/docs/api-reference/messages/object) object.", + "examples": { + "response": "{\n \"id\": \"msg_abc123\",\n \"object\": \"thread.message\",\n \"created_at\": 1713226573,\n \"assistant_id\": null,\n \"thread_id\": \"thread_abc123\",\n \"run_id\": null,\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": {\n \"value\": \"How does AI work? Explain it in simple terms.\",\n \"annotations\": []\n }\n }\n ],\n \"attachments\": [],\n \"metadata\": {}\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/messages \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"role\": \"user\",\n \"content\": \"How does AI work? Explain it in simple terms.\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nmessage = client.beta.threads.messages.create(\n thread_id=\"thread_id\",\n content=\"string\",\n role=\"user\",\n)\nprint(message.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst message = await client.beta.threads.messages.create('thread_id', { content: 'string', role: 'user' });\n\nconsole.log(message.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n message, err := client.Beta.Threads.Messages.New(\n context.TODO(),\n \"thread_id\",\n openai.BetaThreadMessageNewParams{\n Content: openai.BetaThreadMessageNewParamsContentUnion{\n OfString: openai.String(\"string\"),\n },\n Role: openai.BetaThreadMessageNewParamsRoleUser,\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", message.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.messages.Message;\nimport com.openai.models.beta.threads.messages.MessageCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n MessageCreateParams params = MessageCreateParams.builder()\n .threadId(\"thread_id\")\n .content(\"string\")\n .role(MessageCreateParams.Role.USER)\n .build();\n Message message = client.beta().threads().messages().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nmessage = openai.beta.threads.messages.create(\"thread_id\", content: \"string\", role: :user)\n\nputs(message)" + } + } + }, + "description": "Create a message." + } + }, + "/threads/{thread_id}/messages/{message_id}": { + "get": { + "operationId": "getMessage", + "tags": [ + "Assistants" + ], + "summary": "Retrieve message", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to which this message belongs." + }, + { + "in": "path", + "name": "message_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the message to retrieve." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve message", + "group": "threads", + "beta": true, + "returns": "The [message](https://platform.openai.com/docs/api-reference/messages/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"msg_abc123\",\n \"object\": \"thread.message\",\n \"created_at\": 1699017614,\n \"assistant_id\": null,\n \"thread_id\": \"thread_abc123\",\n \"run_id\": null,\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": {\n \"value\": \"How does AI work? Explain it in simple terms.\",\n \"annotations\": []\n }\n }\n ],\n \"attachments\": [],\n \"metadata\": {}\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nmessage = client.beta.threads.messages.retrieve(\n message_id=\"message_id\",\n thread_id=\"thread_id\",\n)\nprint(message.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst message = await client.beta.threads.messages.retrieve('message_id', { thread_id: 'thread_id' });\n\nconsole.log(message.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n message, err := client.Beta.Threads.Messages.Get(\n context.TODO(),\n \"thread_id\",\n \"message_id\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", message.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.messages.Message;\nimport com.openai.models.beta.threads.messages.MessageRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n MessageRetrieveParams params = MessageRetrieveParams.builder()\n .threadId(\"thread_id\")\n .messageId(\"message_id\")\n .build();\n Message message = client.beta().threads().messages().retrieve(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nmessage = openai.beta.threads.messages.retrieve(\"message_id\", thread_id: \"thread_id\")\n\nputs(message)" + } + } + }, + "description": "Retrieve a message." + }, + "post": { + "operationId": "modifyMessage", + "tags": [ + "Assistants" + ], + "summary": "Modify message", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the thread to which this message belongs." + }, + { + "in": "path", + "name": "message_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the message to modify." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ModifyMessageRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Modify message", + "group": "threads", + "beta": true, + "returns": "The modified [message](https://platform.openai.com/docs/api-reference/messages/object) object.", + "examples": { + "response": "{\n \"id\": \"msg_abc123\",\n \"object\": \"thread.message\",\n \"created_at\": 1699017614,\n \"assistant_id\": null,\n \"thread_id\": \"thread_abc123\",\n \"run_id\": null,\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": {\n \"value\": \"How does AI work? Explain it in simple terms.\",\n \"annotations\": []\n }\n }\n ],\n \"file_ids\": [],\n \"metadata\": {\n \"modified\": \"true\",\n \"user\": \"abc123\"\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"metadata\": {\n \"modified\": \"true\",\n \"user\": \"abc123\"\n }\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nmessage = client.beta.threads.messages.update(\n message_id=\"message_id\",\n thread_id=\"thread_id\",\n)\nprint(message.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst message = await client.beta.threads.messages.update('message_id', { thread_id: 'thread_id' });\n\nconsole.log(message.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n message, err := client.Beta.Threads.Messages.Update(\n context.TODO(),\n \"thread_id\",\n \"message_id\",\n openai.BetaThreadMessageUpdateParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", message.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.messages.Message;\nimport com.openai.models.beta.threads.messages.MessageUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n MessageUpdateParams params = MessageUpdateParams.builder()\n .threadId(\"thread_id\")\n .messageId(\"message_id\")\n .build();\n Message message = client.beta().threads().messages().update(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nmessage = openai.beta.threads.messages.update(\"message_id\", thread_id: \"thread_id\")\n\nputs(message)" + } + } + }, + "description": "Modifies a message." + }, + "delete": { + "operationId": "deleteMessage", + "tags": [ + "Assistants" + ], + "summary": "Delete message", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the thread to which this message belongs." + }, + { + "in": "path", + "name": "message_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the message to delete." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteMessageResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete message", + "group": "threads", + "beta": true, + "returns": "Deletion status", + "examples": { + "response": "{\n \"id\": \"msg_abc123\",\n \"object\": \"thread.message.deleted\",\n \"deleted\": true\n}\n", + "request": { + "curl": "curl -X DELETE https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nmessage_deleted = client.beta.threads.messages.delete(\n message_id=\"message_id\",\n thread_id=\"thread_id\",\n)\nprint(message_deleted.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst messageDeleted = await client.beta.threads.messages.delete('message_id', { thread_id: 'thread_id' });\n\nconsole.log(messageDeleted.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n messageDeleted, err := client.Beta.Threads.Messages.Delete(\n context.TODO(),\n \"thread_id\",\n \"message_id\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", messageDeleted.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.messages.MessageDeleteParams;\nimport com.openai.models.beta.threads.messages.MessageDeleted;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n MessageDeleteParams params = MessageDeleteParams.builder()\n .threadId(\"thread_id\")\n .messageId(\"message_id\")\n .build();\n MessageDeleted messageDeleted = client.beta().threads().messages().delete(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nmessage_deleted = openai.beta.threads.messages.delete(\"message_id\", thread_id: \"thread_id\")\n\nputs(message_deleted)" + } + } + }, + "description": "Deletes a message." + } + }, + "/threads/{thread_id}/runs": { + "get": { + "operationId": "listRuns", + "tags": [ + "Assistants" + ], + "summary": "List runs", + "parameters": [ + { + "name": "thread_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the thread the run belongs to." + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "before", + "in": "query", + "description": "A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.\n", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListRunsResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List runs", + "group": "threads", + "beta": true, + "returns": "A list of [run](https://platform.openai.com/docs/api-reference/runs/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"run_abc123\",\n \"object\": \"thread.run\",\n \"created_at\": 1699075072,\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"status\": \"completed\",\n \"started_at\": 1699075072,\n \"expires_at\": null,\n \"cancelled_at\": null,\n \"failed_at\": null,\n \"completed_at\": 1699075073,\n \"last_error\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": null,\n \"incomplete_details\": null,\n \"tools\": [\n {\n \"type\": \"code_interpreter\"\n }\n ],\n \"tool_resources\": {\n \"code_interpreter\": {\n \"file_ids\": [\n \"file-abc123\",\n \"file-abc456\"\n ]\n }\n },\n \"metadata\": {},\n \"usage\": {\n \"prompt_tokens\": 123,\n \"completion_tokens\": 456,\n \"total_tokens\": 579\n },\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_prompt_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"truncation_strategy\": {\n \"type\": \"auto\",\n \"last_messages\": null\n },\n \"response_format\": \"auto\",\n \"tool_choice\": \"auto\",\n \"parallel_tool_calls\": true\n },\n {\n \"id\": \"run_abc456\",\n \"object\": \"thread.run\",\n \"created_at\": 1699063290,\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"status\": \"completed\",\n \"started_at\": 1699063290,\n \"expires_at\": null,\n \"cancelled_at\": null,\n \"failed_at\": null,\n \"completed_at\": 1699063291,\n \"last_error\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": null,\n \"incomplete_details\": null,\n \"tools\": [\n {\n \"type\": \"code_interpreter\"\n }\n ],\n \"tool_resources\": {\n \"code_interpreter\": {\n \"file_ids\": [\n \"file-abc123\",\n \"file-abc456\"\n ]\n }\n },\n \"metadata\": {},\n \"usage\": {\n \"prompt_tokens\": 123,\n \"completion_tokens\": 456,\n \"total_tokens\": 579\n },\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_prompt_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"truncation_strategy\": {\n \"type\": \"auto\",\n \"last_messages\": null\n },\n \"response_format\": \"auto\",\n \"tool_choice\": \"auto\",\n \"parallel_tool_calls\": true\n }\n ],\n \"first_id\": \"run_abc123\",\n \"last_id\": \"run_abc456\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/runs \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.beta.threads.runs.list(\n thread_id=\"thread_id\",\n)\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const run of client.beta.threads.runs.list('thread_id')) {\n console.log(run.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Beta.Threads.Runs.List(\n context.TODO(),\n \"thread_id\",\n openai.BetaThreadRunListParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.RunListPage;\nimport com.openai.models.beta.threads.runs.RunListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunListPage page = client.beta().threads().runs().list(\"thread_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.beta.threads.runs.list(\"thread_id\")\n\nputs(page)" + } + } + }, + "description": "Returns a list of runs belonging to a thread." + }, + "post": { + "operationId": "createRun", + "tags": [ + "Assistants" + ], + "summary": "Create run", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the thread to run." + }, + { + "name": "include[]", + "in": "query", + "description": "A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content.\n\nSee the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n", + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "step_details.tool_calls[*].file_search.results[*].content" + ] + } + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateRunRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create run", + "group": "threads", + "beta": true, + "returns": "A [run](https://platform.openai.com/docs/api-reference/runs/object) object.", + "examples": [ + { + "title": "Default", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/runs \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"assistant_id\": \"asst_abc123\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.runs.create(\n thread_id=\"thread_id\",\n assistant_id=\"assistant_id\",\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' });\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.Runs.New(\n context.TODO(),\n \"thread_id\",\n openai.BetaThreadRunNewParams{\n AssistantID: \"assistant_id\",\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.Run;\nimport com.openai.models.beta.threads.runs.RunCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunCreateParams params = RunCreateParams.builder()\n .threadId(\"thread_id\")\n .assistantId(\"assistant_id\")\n .build();\n Run run = client.beta().threads().runs().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.runs.create(\"thread_id\", assistant_id: \"assistant_id\")\n\nputs(run)" + }, + "response": "{\n \"id\": \"run_abc123\",\n \"object\": \"thread.run\",\n \"created_at\": 1699063290,\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"status\": \"queued\",\n \"started_at\": 1699063290,\n \"expires_at\": null,\n \"cancelled_at\": null,\n \"failed_at\": null,\n \"completed_at\": 1699063291,\n \"last_error\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": null,\n \"incomplete_details\": null,\n \"tools\": [\n {\n \"type\": \"code_interpreter\"\n }\n ],\n \"metadata\": {},\n \"usage\": null,\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_prompt_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"truncation_strategy\": {\n \"type\": \"auto\",\n \"last_messages\": null\n },\n \"response_format\": \"auto\",\n \"tool_choice\": \"auto\",\n \"parallel_tool_calls\": true\n}\n" + }, + { + "title": "Streaming", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_123/runs \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"assistant_id\": \"asst_123\",\n \"stream\": true\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.runs.create(\n thread_id=\"thread_id\",\n assistant_id=\"assistant_id\",\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' });\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.Runs.New(\n context.TODO(),\n \"thread_id\",\n openai.BetaThreadRunNewParams{\n AssistantID: \"assistant_id\",\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.Run;\nimport com.openai.models.beta.threads.runs.RunCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunCreateParams params = RunCreateParams.builder()\n .threadId(\"thread_id\")\n .assistantId(\"assistant_id\")\n .build();\n Run run = client.beta().threads().runs().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.runs.create(\"thread_id\", assistant_id: \"assistant_id\")\n\nputs(run)" + }, + "response": "event: thread.run.created\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710330640,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"queued\",\"started_at\":null,\"expires_at\":1710331240,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.queued\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710330640,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"queued\",\"started_at\":null,\"expires_at\":1710331240,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.in_progress\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710330640,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"in_progress\",\"started_at\":1710330641,\"expires_at\":1710331240,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.step.created\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710330641,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"in_progress\",\"cancelled_at\":null,\"completed_at\":null,\"expires_at\":1710331240,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_001\"}},\"usage\":null}\n\nevent: thread.run.step.in_progress\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710330641,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"in_progress\",\"cancelled_at\":null,\"completed_at\":null,\"expires_at\":1710331240,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_001\"}},\"usage\":null}\n\nevent: thread.message.created\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message\",\"created_at\":1710330641,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"in_progress\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":null,\"role\":\"assistant\",\"content\":[],\"metadata\":{}}\n\nevent: thread.message.in_progress\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message\",\"created_at\":1710330641,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"in_progress\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":null,\"role\":\"assistant\",\"content\":[],\"metadata\":{}}\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\"Hello\",\"annotations\":[]}}]}}\n\n...\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\" today\"}}]}}\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\"?\"}}]}}\n\nevent: thread.message.completed\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message\",\"created_at\":1710330641,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"completed\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":1710330642,\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":{\"value\":\"Hello! How can I assist you today?\",\"annotations\":[]}}],\"metadata\":{}}\n\nevent: thread.run.step.completed\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710330641,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"completed\",\"cancelled_at\":null,\"completed_at\":1710330642,\"expires_at\":1710331240,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_001\"}},\"usage\":{\"prompt_tokens\":20,\"completion_tokens\":11,\"total_tokens\":31}}\n\nevent: thread.run.completed\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710330640,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"completed\",\"started_at\":1710330641,\"expires_at\":null,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":1710330642,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":{\"prompt_tokens\":20,\"completion_tokens\":11,\"total_tokens\":31},\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: done\ndata: [DONE]\n" + }, + { + "title": "Streaming with Functions", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/runs \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"assistant_id\": \"asst_abc123\",\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_current_weather\",\n \"description\": \"Get the current weather in a given location\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and state, e.g. San Francisco, CA\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\"celsius\", \"fahrenheit\"]\n }\n },\n \"required\": [\"location\"]\n }\n }\n }\n ],\n \"stream\": true\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.runs.create(\n thread_id=\"thread_id\",\n assistant_id=\"assistant_id\",\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' });\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.Runs.New(\n context.TODO(),\n \"thread_id\",\n openai.BetaThreadRunNewParams{\n AssistantID: \"assistant_id\",\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.Run;\nimport com.openai.models.beta.threads.runs.RunCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunCreateParams params = RunCreateParams.builder()\n .threadId(\"thread_id\")\n .assistantId(\"assistant_id\")\n .build();\n Run run = client.beta().threads().runs().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.runs.create(\"thread_id\", assistant_id: \"assistant_id\")\n\nputs(run)" + }, + "response": "event: thread.run.created\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710348075,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"queued\",\"started_at\":null,\"expires_at\":1710348675,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.queued\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710348075,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"queued\",\"started_at\":null,\"expires_at\":1710348675,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.in_progress\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710348075,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"in_progress\",\"started_at\":1710348075,\"expires_at\":1710348675,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.step.created\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710348076,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"in_progress\",\"cancelled_at\":null,\"completed_at\":null,\"expires_at\":1710348675,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_001\"}},\"usage\":null}\n\nevent: thread.run.step.in_progress\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710348076,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"in_progress\",\"cancelled_at\":null,\"completed_at\":null,\"expires_at\":1710348675,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_001\"}},\"usage\":null}\n\nevent: thread.message.created\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message\",\"created_at\":1710348076,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"in_progress\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":null,\"role\":\"assistant\",\"content\":[],\"metadata\":{}}\n\nevent: thread.message.in_progress\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message\",\"created_at\":1710348076,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"in_progress\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":null,\"role\":\"assistant\",\"content\":[],\"metadata\":{}}\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\"Hello\",\"annotations\":[]}}]}}\n\n...\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\" today\"}}]}}\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\"?\"}}]}}\n\nevent: thread.message.completed\ndata: {\"id\":\"msg_001\",\"object\":\"thread.message\",\"created_at\":1710348076,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"completed\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":1710348077,\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":{\"value\":\"Hello! How can I assist you today?\",\"annotations\":[]}}],\"metadata\":{}}\n\nevent: thread.run.step.completed\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710348076,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"completed\",\"cancelled_at\":null,\"completed_at\":1710348077,\"expires_at\":1710348675,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_001\"}},\"usage\":{\"prompt_tokens\":20,\"completion_tokens\":11,\"total_tokens\":31}}\n\nevent: thread.run.completed\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710348075,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"completed\",\"started_at\":1710348075,\"expires_at\":null,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":1710348077,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":{\"prompt_tokens\":20,\"completion_tokens\":11,\"total_tokens\":31},\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: done\ndata: [DONE]\n" + } + ] + }, + "description": "Create a run." + } + }, + "/threads/{thread_id}/runs/{run_id}": { + "get": { + "operationId": "getRun", + "tags": [ + "Assistants" + ], + "summary": "Retrieve run", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run." + }, + { + "in": "path", + "name": "run_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run to retrieve." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve run", + "group": "threads", + "beta": true, + "returns": "The [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"run_abc123\",\n \"object\": \"thread.run\",\n \"created_at\": 1699075072,\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"status\": \"completed\",\n \"started_at\": 1699075072,\n \"expires_at\": null,\n \"cancelled_at\": null,\n \"failed_at\": null,\n \"completed_at\": 1699075073,\n \"last_error\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": null,\n \"incomplete_details\": null,\n \"tools\": [\n {\n \"type\": \"code_interpreter\"\n }\n ],\n \"metadata\": {},\n \"usage\": {\n \"prompt_tokens\": 123,\n \"completion_tokens\": 456,\n \"total_tokens\": 579\n },\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_prompt_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"truncation_strategy\": {\n \"type\": \"auto\",\n \"last_messages\": null\n },\n \"response_format\": \"auto\",\n \"tool_choice\": \"auto\",\n \"parallel_tool_calls\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.runs.retrieve(\n run_id=\"run_id\",\n thread_id=\"thread_id\",\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.runs.retrieve('run_id', { thread_id: 'thread_id' });\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.Runs.Get(\n context.TODO(),\n \"thread_id\",\n \"run_id\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.Run;\nimport com.openai.models.beta.threads.runs.RunRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunRetrieveParams params = RunRetrieveParams.builder()\n .threadId(\"thread_id\")\n .runId(\"run_id\")\n .build();\n Run run = client.beta().threads().runs().retrieve(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.runs.retrieve(\"run_id\", thread_id: \"thread_id\")\n\nputs(run)" + } + } + }, + "description": "Retrieves a run." + }, + "post": { + "operationId": "modifyRun", + "tags": [ + "Assistants" + ], + "summary": "Modify run", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run." + }, + { + "in": "path", + "name": "run_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run to modify." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ModifyRunRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Modify run", + "group": "threads", + "beta": true, + "returns": "The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"run_abc123\",\n \"object\": \"thread.run\",\n \"created_at\": 1699075072,\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"status\": \"completed\",\n \"started_at\": 1699075072,\n \"expires_at\": null,\n \"cancelled_at\": null,\n \"failed_at\": null,\n \"completed_at\": 1699075073,\n \"last_error\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": null,\n \"incomplete_details\": null,\n \"tools\": [\n {\n \"type\": \"code_interpreter\"\n }\n ],\n \"tool_resources\": {\n \"code_interpreter\": {\n \"file_ids\": [\n \"file-abc123\",\n \"file-abc456\"\n ]\n }\n },\n \"metadata\": {\n \"user_id\": \"user_abc123\"\n },\n \"usage\": {\n \"prompt_tokens\": 123,\n \"completion_tokens\": 456,\n \"total_tokens\": 579\n },\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_prompt_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"truncation_strategy\": {\n \"type\": \"auto\",\n \"last_messages\": null\n },\n \"response_format\": \"auto\",\n \"tool_choice\": \"auto\",\n \"parallel_tool_calls\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"metadata\": {\n \"user_id\": \"user_abc123\"\n }\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.runs.update(\n run_id=\"run_id\",\n thread_id=\"thread_id\",\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.runs.update('run_id', { thread_id: 'thread_id' });\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.Runs.Update(\n context.TODO(),\n \"thread_id\",\n \"run_id\",\n openai.BetaThreadRunUpdateParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.Run;\nimport com.openai.models.beta.threads.runs.RunUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunUpdateParams params = RunUpdateParams.builder()\n .threadId(\"thread_id\")\n .runId(\"run_id\")\n .build();\n Run run = client.beta().threads().runs().update(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.runs.update(\"run_id\", thread_id: \"thread_id\")\n\nputs(run)" + } + } + }, + "description": "Modifies a run." + } + }, + "/threads/{thread_id}/runs/{run_id}/cancel": { + "post": { + "operationId": "cancelRun", + "tags": [ + "Assistants" + ], + "summary": "Cancel a run", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the thread to which this run belongs." + }, + { + "in": "path", + "name": "run_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run to cancel." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Cancel a run", + "group": "threads", + "beta": true, + "returns": "The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"run_abc123\",\n \"object\": \"thread.run\",\n \"created_at\": 1699076126,\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"status\": \"cancelling\",\n \"started_at\": 1699076126,\n \"expires_at\": 1699076726,\n \"cancelled_at\": null,\n \"failed_at\": null,\n \"completed_at\": null,\n \"last_error\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You summarize books.\",\n \"tools\": [\n {\n \"type\": \"file_search\"\n }\n ],\n \"tool_resources\": {\n \"file_search\": {\n \"vector_store_ids\": [\"vs_123\"]\n }\n },\n \"metadata\": {},\n \"usage\": null,\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"response_format\": \"auto\",\n \"tool_choice\": \"auto\",\n \"parallel_tool_calls\": true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/cancel \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -X POST\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.runs.cancel(\n run_id=\"run_id\",\n thread_id=\"thread_id\",\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.runs.cancel('run_id', { thread_id: 'thread_id' });\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.Runs.Cancel(\n context.TODO(),\n \"thread_id\",\n \"run_id\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.Run;\nimport com.openai.models.beta.threads.runs.RunCancelParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunCancelParams params = RunCancelParams.builder()\n .threadId(\"thread_id\")\n .runId(\"run_id\")\n .build();\n Run run = client.beta().threads().runs().cancel(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.runs.cancel(\"run_id\", thread_id: \"thread_id\")\n\nputs(run)" + } + } + }, + "description": "Cancels a run that is `in_progress`." + } + }, + "/threads/{thread_id}/runs/{run_id}/steps": { + "get": { + "operationId": "listRunSteps", + "tags": [ + "Assistants" + ], + "summary": "List run steps", + "parameters": [ + { + "name": "thread_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the thread the run and run steps belong to." + }, + { + "name": "run_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run the run steps belong to." + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "before", + "in": "query", + "description": "A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "include[]", + "in": "query", + "description": "A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content.\n\nSee the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n", + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "step_details.tool_calls[*].file_search.results[*].content" + ] + } + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListRunStepsResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List run steps", + "group": "threads", + "beta": true, + "returns": "A list of [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"step_abc123\",\n \"object\": \"thread.run.step\",\n \"created_at\": 1699063291,\n \"run_id\": \"run_abc123\",\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"type\": \"message_creation\",\n \"status\": \"completed\",\n \"cancelled_at\": null,\n \"completed_at\": 1699063291,\n \"expired_at\": null,\n \"failed_at\": null,\n \"last_error\": null,\n \"step_details\": {\n \"type\": \"message_creation\",\n \"message_creation\": {\n \"message_id\": \"msg_abc123\"\n }\n },\n \"usage\": {\n \"prompt_tokens\": 123,\n \"completion_tokens\": 456,\n \"total_tokens\": 579\n }\n }\n ],\n \"first_id\": \"step_abc123\",\n \"last_id\": \"step_abc456\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.beta.threads.runs.steps.list(\n run_id=\"run_id\",\n thread_id=\"thread_id\",\n)\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const runStep of client.beta.threads.runs.steps.list('run_id', { thread_id: 'thread_id' })) { console.log(runStep.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.Beta.Threads.Runs.Steps.List(\n context.TODO(),\n \"thread_id\",\n \"run_id\",\n openai.BetaThreadRunStepListParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.steps.StepListPage;\nimport com.openai.models.beta.threads.runs.steps.StepListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n StepListParams params = StepListParams.builder()\n .threadId(\"thread_id\")\n .runId(\"run_id\")\n .build();\n StepListPage page = client.beta().threads().runs().steps().list(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.beta.threads.runs.steps.list(\"run_id\", thread_id: \"thread_id\")\n\nputs(page)" + } + } + }, + "description": "Returns a list of run steps belonging to a run." + } + }, + "/threads/{thread_id}/runs/{run_id}/steps/{step_id}": { + "get": { + "operationId": "getRunStep", + "tags": [ + "Assistants" + ], + "summary": "Retrieve run step", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the thread to which the run and run step belongs." + }, + { + "in": "path", + "name": "run_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run to which the run step belongs." + }, + { + "in": "path", + "name": "step_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run step to retrieve." + }, + { + "name": "include[]", + "in": "query", + "description": "A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content.\n\nSee the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n", + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "step_details.tool_calls[*].file_search.results[*].content" + ] + } + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunStepObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve run step", + "group": "threads", + "beta": true, + "returns": "The [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"step_abc123\",\n \"object\": \"thread.run.step\",\n \"created_at\": 1699063291,\n \"run_id\": \"run_abc123\",\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"type\": \"message_creation\",\n \"status\": \"completed\",\n \"cancelled_at\": null,\n \"completed_at\": 1699063291,\n \"expired_at\": null,\n \"failed_at\": null,\n \"last_error\": null,\n \"step_details\": {\n \"type\": \"message_creation\",\n \"message_creation\": {\n \"message_id\": \"msg_abc123\"\n }\n },\n \"usage\": {\n \"prompt_tokens\": 123,\n \"completion_tokens\": 456,\n \"total_tokens\": 579\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps/step_abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun_step = client.beta.threads.runs.steps.retrieve(\n step_id=\"step_id\",\n thread_id=\"thread_id\",\n run_id=\"run_id\",\n)\nprint(run_step.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst runStep = await client.beta.threads.runs.steps.retrieve('step_id', {\n thread_id: 'thread_id',\n run_id: 'run_id',\n});\n\nconsole.log(runStep.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n runStep, err := client.Beta.Threads.Runs.Steps.Get(\n context.TODO(),\n \"thread_id\",\n \"run_id\",\n \"step_id\",\n openai.BetaThreadRunStepGetParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", runStep.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.steps.RunStep;\nimport com.openai.models.beta.threads.runs.steps.StepRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n StepRetrieveParams params = StepRetrieveParams.builder()\n .threadId(\"thread_id\")\n .runId(\"run_id\")\n .stepId(\"step_id\")\n .build();\n RunStep runStep = client.beta().threads().runs().steps().retrieve(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun_step = openai.beta.threads.runs.steps.retrieve(\"step_id\", thread_id: \"thread_id\", run_id: \"run_id\")\n\nputs(run_step)" + } + } + }, + "description": "Retrieves a run step." + } + }, + "/threads/{thread_id}/runs/{run_id}/submit_tool_outputs": { + "post": { + "operationId": "submitToolOuputsToRun", + "tags": [ + "Assistants" + ], + "summary": "Submit tool outputs to run", + "parameters": [ + { + "in": "path", + "name": "thread_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to which this run belongs." + }, + { + "in": "path", + "name": "run_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the run that requires the tool output submission." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubmitToolOutputsRunRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Submit tool outputs to run", + "group": "threads", + "beta": true, + "returns": "The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID.", + "examples": [ + { + "title": "Default", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"tool_outputs\": [\n {\n \"tool_call_id\": \"call_001\",\n \"output\": \"70 degrees and sunny.\"\n }\n ]\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.runs.submit_tool_outputs(\n run_id=\"run_id\",\n thread_id=\"thread_id\",\n tool_outputs=[{}],\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.runs.submitToolOutputs('run_id', {\n thread_id: 'thread_id',\n tool_outputs: [{}],\n});\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.Runs.SubmitToolOutputs(\n context.TODO(),\n \"thread_id\",\n \"run_id\",\n openai.BetaThreadRunSubmitToolOutputsParams{\n ToolOutputs: []openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{\n\n }},\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.Run;\nimport com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunSubmitToolOutputsParams params = RunSubmitToolOutputsParams.builder()\n .threadId(\"thread_id\")\n .runId(\"run_id\")\n .addToolOutput(RunSubmitToolOutputsParams.ToolOutput.builder().build())\n .build();\n Run run = client.beta().threads().runs().submitToolOutputs(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.runs.submit_tool_outputs(\"run_id\", thread_id: \"thread_id\", tool_outputs: [{}])\n\nputs(run)" + }, + "response": "{\n \"id\": \"run_123\",\n \"object\": \"thread.run\",\n \"created_at\": 1699075592,\n \"assistant_id\": \"asst_123\",\n \"thread_id\": \"thread_123\",\n \"status\": \"queued\",\n \"started_at\": 1699075592,\n \"expires_at\": 1699076192,\n \"cancelled_at\": null,\n \"failed_at\": null,\n \"completed_at\": null,\n \"last_error\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": null,\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_current_weather\",\n \"description\": \"Get the current weather in a given location\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and state, e.g. San Francisco, CA\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\"celsius\", \"fahrenheit\"]\n }\n },\n \"required\": [\"location\"]\n }\n }\n }\n ],\n \"metadata\": {},\n \"usage\": null,\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_prompt_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"truncation_strategy\": {\n \"type\": \"auto\",\n \"last_messages\": null\n },\n \"response_format\": \"auto\",\n \"tool_choice\": \"auto\",\n \"parallel_tool_calls\": true\n}\n" + }, + { + "title": "Streaming", + "request": { + "curl": "curl https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"tool_outputs\": [\n {\n \"tool_call_id\": \"call_001\",\n \"output\": \"70 degrees and sunny.\"\n }\n ],\n \"stream\": true\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nrun = client.beta.threads.runs.submit_tool_outputs(\n run_id=\"run_id\",\n thread_id=\"thread_id\",\n tool_outputs=[{}],\n)\nprint(run.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst run = await client.beta.threads.runs.submitToolOutputs('run_id', {\n thread_id: 'thread_id',\n tool_outputs: [{}],\n});\n\nconsole.log(run.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n run, err := client.Beta.Threads.Runs.SubmitToolOutputs(\n context.TODO(),\n \"thread_id\",\n \"run_id\",\n openai.BetaThreadRunSubmitToolOutputsParams{\n ToolOutputs: []openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{\n\n }},\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", run.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.beta.threads.runs.Run;\nimport com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n RunSubmitToolOutputsParams params = RunSubmitToolOutputsParams.builder()\n .threadId(\"thread_id\")\n .runId(\"run_id\")\n .addToolOutput(RunSubmitToolOutputsParams.ToolOutput.builder().build())\n .build();\n Run run = client.beta().threads().runs().submitToolOutputs(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nrun = openai.beta.threads.runs.submit_tool_outputs(\"run_id\", thread_id: \"thread_id\", tool_outputs: [{}])\n\nputs(run)" + }, + "response": "event: thread.run.step.completed\ndata: {\"id\":\"step_001\",\"object\":\"thread.run.step\",\"created_at\":1710352449,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"tool_calls\",\"status\":\"completed\",\"cancelled_at\":null,\"completed_at\":1710352475,\"expires_at\":1710353047,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"tool_calls\",\"tool_calls\":[{\"id\":\"call_iWr0kQ2EaYMaxNdl0v3KYkx7\",\"type\":\"function\",\"function\":{\"name\":\"get_current_weather\",\"arguments\":\"{\\\"location\\\":\\\"San Francisco, CA\\\",\\\"unit\\\":\\\"fahrenheit\\\"}\",\"output\":\"70 degrees and sunny.\"}}]},\"usage\":{\"prompt_tokens\":291,\"completion_tokens\":24,\"total_tokens\":315}}\n\nevent: thread.run.queued\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710352447,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"queued\",\"started_at\":1710352448,\"expires_at\":1710353047,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_current_weather\",\"description\":\"Get the current weather in a given location\",\"parameters\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"The city and state, e.g. San Francisco, CA\"},\"unit\":{\"type\":\"string\",\"enum\":[\"celsius\",\"fahrenheit\"]}},\"required\":[\"location\"]}}}],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.in_progress\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710352447,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"in_progress\",\"started_at\":1710352475,\"expires_at\":1710353047,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":null,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_current_weather\",\"description\":\"Get the current weather in a given location\",\"parameters\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"The city and state, e.g. San Francisco, CA\"},\"unit\":{\"type\":\"string\",\"enum\":[\"celsius\",\"fahrenheit\"]}},\"required\":[\"location\"]}}}],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":null,\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: thread.run.step.created\ndata: {\"id\":\"step_002\",\"object\":\"thread.run.step\",\"created_at\":1710352476,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"in_progress\",\"cancelled_at\":null,\"completed_at\":null,\"expires_at\":1710353047,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_002\"}},\"usage\":null}\n\nevent: thread.run.step.in_progress\ndata: {\"id\":\"step_002\",\"object\":\"thread.run.step\",\"created_at\":1710352476,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"in_progress\",\"cancelled_at\":null,\"completed_at\":null,\"expires_at\":1710353047,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_002\"}},\"usage\":null}\n\nevent: thread.message.created\ndata: {\"id\":\"msg_002\",\"object\":\"thread.message\",\"created_at\":1710352476,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"in_progress\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":null,\"role\":\"assistant\",\"content\":[],\"metadata\":{}}\n\nevent: thread.message.in_progress\ndata: {\"id\":\"msg_002\",\"object\":\"thread.message\",\"created_at\":1710352476,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"in_progress\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":null,\"role\":\"assistant\",\"content\":[],\"metadata\":{}}\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_002\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\"The\",\"annotations\":[]}}]}}\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_002\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\" current\"}}]}}\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_002\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\" weather\"}}]}}\n\n...\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_002\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\" sunny\"}}]}}\n\nevent: thread.message.delta\ndata: {\"id\":\"msg_002\",\"object\":\"thread.message.delta\",\"delta\":{\"content\":[{\"index\":0,\"type\":\"text\",\"text\":{\"value\":\".\"}}]}}\n\nevent: thread.message.completed\ndata: {\"id\":\"msg_002\",\"object\":\"thread.message\",\"created_at\":1710352476,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"run_id\":\"run_123\",\"status\":\"completed\",\"incomplete_details\":null,\"incomplete_at\":null,\"completed_at\":1710352477,\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":{\"value\":\"The current weather in San Francisco, CA is 70 degrees Fahrenheit and sunny.\",\"annotations\":[]}}],\"metadata\":{}}\n\nevent: thread.run.step.completed\ndata: {\"id\":\"step_002\",\"object\":\"thread.run.step\",\"created_at\":1710352476,\"run_id\":\"run_123\",\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"type\":\"message_creation\",\"status\":\"completed\",\"cancelled_at\":null,\"completed_at\":1710352477,\"expires_at\":1710353047,\"failed_at\":null,\"last_error\":null,\"step_details\":{\"type\":\"message_creation\",\"message_creation\":{\"message_id\":\"msg_002\"}},\"usage\":{\"prompt_tokens\":329,\"completion_tokens\":18,\"total_tokens\":347}}\n\nevent: thread.run.completed\ndata: {\"id\":\"run_123\",\"object\":\"thread.run\",\"created_at\":1710352447,\"assistant_id\":\"asst_123\",\"thread_id\":\"thread_123\",\"status\":\"completed\",\"started_at\":1710352475,\"expires_at\":null,\"cancelled_at\":null,\"failed_at\":null,\"completed_at\":1710352477,\"required_action\":null,\"last_error\":null,\"model\":\"gpt-4o\",\"instructions\":null,\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_current_weather\",\"description\":\"Get the current weather in a given location\",\"parameters\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"The city and state, e.g. San Francisco, CA\"},\"unit\":{\"type\":\"string\",\"enum\":[\"celsius\",\"fahrenheit\"]}},\"required\":[\"location\"]}}}],\"metadata\":{},\"temperature\":1.0,\"top_p\":1.0,\"max_completion_tokens\":null,\"max_prompt_tokens\":null,\"truncation_strategy\":{\"type\":\"auto\",\"last_messages\":null},\"incomplete_details\":null,\"usage\":{\"prompt_tokens\":20,\"completion_tokens\":11,\"total_tokens\":31},\"response_format\":\"auto\",\"tool_choice\":\"auto\",\"parallel_tool_calls\":true}}\n\nevent: done\ndata: [DONE]\n" + } + ] + }, + "description": "When a run has the `status: \"requires_action\"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request.\n" + } + }, + "/uploads": { + "post": { + "operationId": "createUpload", + "tags": [ + "Uploads" + ], + "summary": "Create upload", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateUploadRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Upload" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create upload", + "group": "uploads", + "returns": "The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status `pending`.", + "examples": { + "response": "{\n \"id\": \"upload_abc123\",\n \"object\": \"upload\",\n \"bytes\": 2147483648,\n \"created_at\": 1719184911,\n \"filename\": \"training_examples.jsonl\",\n \"purpose\": \"fine-tune\",\n \"status\": \"pending\",\n \"expires_at\": 1719127296\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/uploads \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -d '{\n \"purpose\": \"fine-tune\",\n \"filename\": \"training_examples.jsonl\",\n \"bytes\": 2147483648,\n \"mime_type\": \"text/jsonl\",\n \"expires_after\": {\n \"anchor\": \"created_at\",\n \"seconds\": 3600\n }\n }'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst upload = await client.uploads.create({\n bytes: 0,\n filename: 'filename',\n mime_type: 'mime_type',\n purpose: 'assistants',\n});\n\nconsole.log(upload.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nupload = client.uploads.create(\n bytes=0,\n filename=\"filename\",\n mime_type=\"mime_type\",\n purpose=\"assistants\",\n)\nprint(upload.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n upload, err := client.Uploads.New(context.TODO(), openai.UploadNewParams{\n Bytes: 0,\n Filename: \"filename\",\n MimeType: \"mime_type\",\n Purpose: openai.FilePurposeAssistants,\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", upload.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.files.FilePurpose;\nimport com.openai.models.uploads.Upload;\nimport com.openai.models.uploads.UploadCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n UploadCreateParams params = UploadCreateParams.builder()\n .bytes(0L)\n .filename(\"filename\")\n .mimeType(\"mime_type\")\n .purpose(FilePurpose.ASSISTANTS)\n .build();\n Upload upload = client.uploads().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nupload = openai.uploads.create(bytes: 0, filename: \"filename\", mime_type: \"mime_type\", purpose: :assistants)\n\nputs(upload)" + } + } + }, + "description": "Creates an intermediate [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object\nthat you can add [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.\nCurrently, an Upload can accept at most 8 GB in total and expires after an\nhour after you create it.\n\nOnce you complete the Upload, we will create a\n[File](https://platform.openai.com/docs/api-reference/files/object) object that contains all the parts\nyou uploaded. This File is usable in the rest of our platform as a regular\nFile object.\n\nFor certain `purpose` values, the correct `mime_type` must be specified.\nPlease refer to documentation for the\n[supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files).\n\nFor guidance on the proper filename extensions for each purpose, please\nfollow the documentation on [creating a\nFile](https://platform.openai.com/docs/api-reference/files/create).\n" + } + }, + "/uploads/{upload_id}/cancel": { + "post": { + "operationId": "cancelUpload", + "tags": [ + "Uploads" + ], + "summary": "Cancel upload", + "parameters": [ + { + "in": "path", + "name": "upload_id", + "required": true, + "schema": { + "type": "string", + "example": "upload_abc123" + }, + "description": "The ID of the Upload.\n" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Upload" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Cancel upload", + "group": "uploads", + "returns": "The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status `cancelled`.", + "examples": { + "response": "{\n \"id\": \"upload_abc123\",\n \"object\": \"upload\",\n \"bytes\": 2147483648,\n \"created_at\": 1719184911,\n \"filename\": \"training_examples.jsonl\",\n \"purpose\": \"fine-tune\",\n \"status\": \"cancelled\",\n \"expires_at\": 1719127296\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/uploads/upload_abc123/cancel\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst upload = await client.uploads.cancel('upload_abc123');\n\nconsole.log(upload.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nupload = client.uploads.cancel(\n \"upload_abc123\",\n)\nprint(upload.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n upload, err := client.Uploads.Cancel(context.TODO(), \"upload_abc123\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", upload.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.uploads.Upload;\nimport com.openai.models.uploads.UploadCancelParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n Upload upload = client.uploads().cancel(\"upload_abc123\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nupload = openai.uploads.cancel(\"upload_abc123\")\n\nputs(upload)" + } + } + }, + "description": "Cancels the Upload. No Parts may be added after an Upload is cancelled.\n" + } + }, + "/uploads/{upload_id}/complete": { + "post": { + "operationId": "completeUpload", + "tags": [ + "Uploads" + ], + "summary": "Complete upload", + "parameters": [ + { + "in": "path", + "name": "upload_id", + "required": true, + "schema": { + "type": "string", + "example": "upload_abc123" + }, + "description": "The ID of the Upload.\n" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CompleteUploadRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Upload" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Complete upload", + "group": "uploads", + "returns": "The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status `completed` with an additional `file` property containing the created usable File object.", + "examples": { + "response": "{\n \"id\": \"upload_abc123\",\n \"object\": \"upload\",\n \"bytes\": 2147483648,\n \"created_at\": 1719184911,\n \"filename\": \"training_examples.jsonl\",\n \"purpose\": \"fine-tune\",\n \"status\": \"completed\",\n \"expires_at\": 1719127296,\n \"file\": {\n \"id\": \"file-xyz321\",\n \"object\": \"file\",\n \"bytes\": 2147483648,\n \"created_at\": 1719186911,\n \"expires_at\": 1719127296,\n \"filename\": \"training_examples.jsonl\",\n \"purpose\": \"fine-tune\",\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/uploads/upload_abc123/complete\n -d '{\n \"part_ids\": [\"part_def456\", \"part_ghi789\"]\n }'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst upload = await client.uploads.complete('upload_abc123', { part_ids: ['string'] });\n\nconsole.log(upload.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nupload = client.uploads.complete(\n upload_id=\"upload_abc123\",\n part_ids=[\"string\"],\n)\nprint(upload.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n upload, err := client.Uploads.Complete(\n context.TODO(),\n \"upload_abc123\",\n openai.UploadCompleteParams{\n PartIDs: []string{\"string\"},\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", upload.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.uploads.Upload;\nimport com.openai.models.uploads.UploadCompleteParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n UploadCompleteParams params = UploadCompleteParams.builder()\n .uploadId(\"upload_abc123\")\n .addPartId(\"string\")\n .build();\n Upload upload = client.uploads().complete(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nupload = openai.uploads.complete(\"upload_abc123\", part_ids: [\"string\"])\n\nputs(upload)" + } + } + }, + "description": "Completes the [Upload](https://platform.openai.com/docs/api-reference/uploads/object).\n\nWithin the returned Upload object, there is a nested [File](https://platform.openai.com/docs/api-reference/files/object) object that is ready to use in the rest of the platform.\n\nYou can specify the order of the Parts by passing in an ordered list of the Part IDs.\n\nThe number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed.\n" + } + }, + "/uploads/{upload_id}/parts": { + "post": { + "operationId": "addUploadPart", + "tags": [ + "Uploads" + ], + "summary": "Add upload part", + "parameters": [ + { + "in": "path", + "name": "upload_id", + "required": true, + "schema": { + "type": "string", + "example": "upload_abc123" + }, + "description": "The ID of the Upload.\n" + } + ], + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/AddUploadPartRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UploadPart" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Add upload part", + "group": "uploads", + "returns": "The upload [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) object.", + "examples": { + "response": "{\n \"id\": \"part_def456\",\n \"object\": \"upload.part\",\n \"created_at\": 1719185911,\n \"upload_id\": \"upload_abc123\"\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/uploads/upload_abc123/parts\n -F data=\"aHR0cHM6Ly9hcGkub3BlbmFpLmNvbS92MS91cGxvYWRz...\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst uploadPart = await client.uploads.parts.create('upload_abc123', {\n data: fs.createReadStream('path/to/file'),\n});\n\nconsole.log(uploadPart.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nupload_part = client.uploads.parts.create(\n upload_id=\"upload_abc123\",\n data=b\"raw file contents\",\n)\nprint(upload_part.id)", + "go": "package main\n\nimport (\n \"bytes\"\n \"context\"\n \"fmt\"\n \"io\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n uploadPart, err := client.Uploads.Parts.New(\n context.TODO(),\n \"upload_abc123\",\n openai.UploadPartNewParams{\n Data: io.Reader(bytes.NewBuffer([]byte(\"some file contents\"))),\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", uploadPart.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.uploads.parts.PartCreateParams;\nimport com.openai.models.uploads.parts.UploadPart;\nimport java.io.ByteArrayInputStream;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n PartCreateParams params = PartCreateParams.builder()\n .uploadId(\"upload_abc123\")\n .data(ByteArrayInputStream(\"some content\".getBytes()))\n .build();\n UploadPart uploadPart = client.uploads().parts().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nupload_part = openai.uploads.parts.create(\"upload_abc123\", data: Pathname(__FILE__))\n\nputs(upload_part)" + } + } + }, + "description": "Adds a [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. A Part represents a chunk of bytes from the file you are trying to upload.\n\nEach Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB.\n\nIt is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).\n" + } + }, + "/vector_stores": { + "get": { + "operationId": "listVectorStores", + "tags": [ + "Vector stores" + ], + "summary": "List vector stores", + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "before", + "in": "query", + "description": "A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.\n", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListVectorStoresResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List vector stores", + "group": "vector_stores", + "returns": "A list of [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"vs_abc123\",\n \"object\": \"vector_store\",\n \"created_at\": 1699061776,\n \"name\": \"Support FAQ\",\n \"bytes\": 139920,\n \"file_counts\": {\n \"in_progress\": 0,\n \"completed\": 3,\n \"failed\": 0,\n \"cancelled\": 0,\n \"total\": 3\n }\n },\n {\n \"id\": \"vs_abc456\",\n \"object\": \"vector_store\",\n \"created_at\": 1699061776,\n \"name\": \"Support FAQ v2\",\n \"bytes\": 139920,\n \"file_counts\": {\n \"in_progress\": 0,\n \"completed\": 3,\n \"failed\": 0,\n \"cancelled\": 0,\n \"total\": 3\n }\n }\n ],\n \"first_id\": \"vs_abc123\",\n \"last_id\": \"vs_abc456\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.vector_stores.list()\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const vectorStore of client.vectorStores.list()) {\n console.log(vectorStore.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.VectorStores.List(context.TODO(), openai.VectorStoreListParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.VectorStoreListPage;\nimport com.openai.models.vectorstores.VectorStoreListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n VectorStoreListPage page = client.vectorStores().list();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.vector_stores.list\n\nputs(page)" + } + } + }, + "description": "Returns a list of vector stores." + }, + "post": { + "operationId": "createVectorStore", + "tags": [ + "Vector stores" + ], + "summary": "Create vector store", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateVectorStoreRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create vector store", + "group": "vector_stores", + "returns": "A [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object.", + "examples": { + "response": "{\n \"id\": \"vs_abc123\",\n \"object\": \"vector_store\",\n \"created_at\": 1699061776,\n \"name\": \"Support FAQ\",\n \"bytes\": 139920,\n \"file_counts\": {\n \"in_progress\": 0,\n \"completed\": 3,\n \"failed\": 0,\n \"cancelled\": 0,\n \"total\": 3\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"name\": \"Support FAQ\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store = client.vector_stores.create()\nprint(vector_store.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst vectorStore = await client.vectorStores.create();\n\nconsole.log(vectorStore.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStore, err := client.VectorStores.New(context.TODO(), openai.VectorStoreNewParams{\n\n })\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStore.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.VectorStore;\nimport com.openai.models.vectorstores.VectorStoreCreateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n VectorStore vectorStore = client.vectorStores().create();\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store = openai.vector_stores.create\n\nputs(vector_store)" + } + } + }, + "description": "Create a vector store." + } + }, + "/vector_stores/{vector_store_id}": { + "get": { + "operationId": "getVectorStore", + "tags": [ + "Vector stores" + ], + "summary": "Retrieve vector store", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the vector store to retrieve." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve vector store", + "group": "vector_stores", + "returns": "The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object matching the specified ID.", + "examples": { + "response": "{\n \"id\": \"vs_abc123\",\n \"object\": \"vector_store\",\n \"created_at\": 1699061776\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store = client.vector_stores.retrieve(\n \"vector_store_id\",\n)\nprint(vector_store.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst vectorStore = await client.vectorStores.retrieve('vector_store_id');\n\nconsole.log(vectorStore.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStore, err := client.VectorStores.Get(context.TODO(), \"vector_store_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStore.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.VectorStore;\nimport com.openai.models.vectorstores.VectorStoreRetrieveParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n VectorStore vectorStore = client.vectorStores().retrieve(\"vector_store_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store = openai.vector_stores.retrieve(\"vector_store_id\")\n\nputs(vector_store)" + } + } + }, + "description": "Retrieves a vector store." + }, + "post": { + "operationId": "modifyVectorStore", + "tags": [ + "Vector stores" + ], + "summary": "Modify vector store", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the vector store to modify." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateVectorStoreRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Modify vector store", + "group": "vector_stores", + "returns": "The modified [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object.", + "examples": { + "response": "{\n \"id\": \"vs_abc123\",\n \"object\": \"vector_store\",\n \"created_at\": 1699061776,\n \"name\": \"Support FAQ\",\n \"bytes\": 139920,\n \"file_counts\": {\n \"in_progress\": 0,\n \"completed\": 3,\n \"failed\": 0,\n \"cancelled\": 0,\n \"total\": 3\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n -d '{\n \"name\": \"Support FAQ\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store = client.vector_stores.update(\n vector_store_id=\"vector_store_id\",\n)\nprint(vector_store.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst vectorStore = await client.vectorStores.update('vector_store_id');\n\nconsole.log(vectorStore.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStore, err := client.VectorStores.Update(\n context.TODO(),\n \"vector_store_id\",\n openai.VectorStoreUpdateParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStore.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.VectorStore;\nimport com.openai.models.vectorstores.VectorStoreUpdateParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n VectorStore vectorStore = client.vectorStores().update(\"vector_store_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store = openai.vector_stores.update(\"vector_store_id\")\n\nputs(vector_store)" + } + } + }, + "description": "Modifies a vector store." + }, + "delete": { + "operationId": "deleteVectorStore", + "tags": [ + "Vector stores" + ], + "summary": "Delete vector store", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the vector store to delete." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteVectorStoreResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete vector store", + "group": "vector_stores", + "returns": "Deletion status", + "examples": { + "response": "{\n id: \"vs_abc123\",\n object: \"vector_store.deleted\",\n deleted: true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -X DELETE\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store_deleted = client.vector_stores.delete(\n \"vector_store_id\",\n)\nprint(vector_store_deleted.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst vectorStoreDeleted = await client.vectorStores.delete('vector_store_id');\n\nconsole.log(vectorStoreDeleted.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStoreDeleted, err := client.VectorStores.Delete(context.TODO(), \"vector_store_id\")\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStoreDeleted.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.VectorStoreDeleteParams;\nimport com.openai.models.vectorstores.VectorStoreDeleted;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n VectorStoreDeleted vectorStoreDeleted = client.vectorStores().delete(\"vector_store_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store_deleted = openai.vector_stores.delete(\"vector_store_id\")\n\nputs(vector_store_deleted)" + } + } + }, + "description": "Delete a vector store." + } + }, + "/vector_stores/{vector_store_id}/file_batches": { + "post": { + "operationId": "createVectorStoreFileBatch", + "tags": [ + "Vector stores" + ], + "summary": "Create vector store file batch", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string", + "example": "vs_abc123" + }, + "description": "The ID of the vector store for which to create a File Batch.\n" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateVectorStoreFileBatchRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreFileBatchObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create vector store file batch", + "group": "vector_stores", + "returns": "A [vector store file batch](https://platform.openai.com/docs/api-reference/vector-stores-file-batches/batch-object) object.", + "examples": { + "response": "{\n \"id\": \"vsfb_abc123\",\n \"object\": \"vector_store.file_batch\",\n \"created_at\": 1699061776,\n \"vector_store_id\": \"vs_abc123\",\n \"status\": \"in_progress\",\n \"file_counts\": {\n \"in_progress\": 1,\n \"completed\": 1,\n \"failed\": 0,\n \"cancelled\": 0,\n \"total\": 0,\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123/file_batches \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"file_ids\": [\"file-abc123\", \"file-abc456\"]\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store_file_batch = client.vector_stores.file_batches.create(\n vector_store_id=\"vs_abc123\",\n file_ids=[\"string\"],\n)\nprint(vector_store_file_batch.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst vectorStoreFileBatch = await client.vectorStores.fileBatches.create('vs_abc123', {\n file_ids: ['string'],\n});\n\nconsole.log(vectorStoreFileBatch.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStoreFileBatch, err := client.VectorStores.FileBatches.New(\n context.TODO(),\n \"vs_abc123\",\n openai.VectorStoreFileBatchNewParams{\n FileIDs: []string{\"string\"},\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStoreFileBatch.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.filebatches.FileBatchCreateParams;\nimport com.openai.models.vectorstores.filebatches.VectorStoreFileBatch;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileBatchCreateParams params = FileBatchCreateParams.builder()\n .vectorStoreId(\"vs_abc123\")\n .addFileId(\"string\")\n .build();\n VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store_file_batch = openai.vector_stores.file_batches.create(\"vs_abc123\", file_ids: [\"string\"])\n\nputs(vector_store_file_batch)" + } + } + }, + "description": "Create a vector store file batch." + } + }, + "/vector_stores/{vector_store_id}/file_batches/{batch_id}": { + "get": { + "operationId": "getVectorStoreFileBatch", + "tags": [ + "Vector stores" + ], + "summary": "Retrieve vector store file batch", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string", + "example": "vs_abc123" + }, + "description": "The ID of the vector store that the file batch belongs to." + }, + { + "in": "path", + "name": "batch_id", + "required": true, + "schema": { + "type": "string", + "example": "vsfb_abc123" + }, + "description": "The ID of the file batch being retrieved." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreFileBatchObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve vector store file batch", + "group": "vector_stores", + "returns": "The [vector store file batch](https://platform.openai.com/docs/api-reference/vector-stores-file-batches/batch-object) object.", + "examples": { + "response": "{\n \"id\": \"vsfb_abc123\",\n \"object\": \"vector_store.file_batch\",\n \"created_at\": 1699061776,\n \"vector_store_id\": \"vs_abc123\",\n \"status\": \"in_progress\",\n \"file_counts\": {\n \"in_progress\": 1,\n \"completed\": 1,\n \"failed\": 0,\n \"cancelled\": 0,\n \"total\": 0,\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store_file_batch = client.vector_stores.file_batches.retrieve(\n batch_id=\"vsfb_abc123\",\n vector_store_id=\"vs_abc123\",\n)\nprint(vector_store_file_batch.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst vectorStoreFileBatch = await client.vectorStores.fileBatches.retrieve('vsfb_abc123', {\n vector_store_id: 'vs_abc123',\n});\n\nconsole.log(vectorStoreFileBatch.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStoreFileBatch, err := client.VectorStores.FileBatches.Get(\n context.TODO(),\n \"vs_abc123\",\n \"vsfb_abc123\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStoreFileBatch.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.filebatches.FileBatchRetrieveParams;\nimport com.openai.models.vectorstores.filebatches.VectorStoreFileBatch;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileBatchRetrieveParams params = FileBatchRetrieveParams.builder()\n .vectorStoreId(\"vs_abc123\")\n .batchId(\"vsfb_abc123\")\n .build();\n VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().retrieve(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store_file_batch = openai.vector_stores.file_batches.retrieve(\"vsfb_abc123\", vector_store_id: \"vs_abc123\")\n\nputs(vector_store_file_batch)" + } + } + }, + "description": "Retrieves a vector store file batch." + } + }, + "/vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel": { + "post": { + "operationId": "cancelVectorStoreFileBatch", + "tags": [ + "Vector stores" + ], + "summary": "Cancel vector store file batch", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the vector store that the file batch belongs to." + }, + { + "in": "path", + "name": "batch_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the file batch to cancel." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreFileBatchObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Cancel vector store file batch", + "group": "vector_stores", + "returns": "The modified vector store file batch object.", + "examples": { + "response": "{\n \"id\": \"vsfb_abc123\",\n \"object\": \"vector_store.file_batch\",\n \"created_at\": 1699061776,\n \"vector_store_id\": \"vs_abc123\",\n \"status\": \"in_progress\",\n \"file_counts\": {\n \"in_progress\": 12,\n \"completed\": 3,\n \"failed\": 0,\n \"cancelled\": 0,\n \"total\": 15,\n }\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/cancel \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -X POST\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store_file_batch = client.vector_stores.file_batches.cancel(\n batch_id=\"batch_id\",\n vector_store_id=\"vector_store_id\",\n)\nprint(vector_store_file_batch.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst vectorStoreFileBatch = await client.vectorStores.fileBatches.cancel('batch_id', {\n vector_store_id: 'vector_store_id',\n});\n\nconsole.log(vectorStoreFileBatch.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStoreFileBatch, err := client.VectorStores.FileBatches.Cancel(\n context.TODO(),\n \"vector_store_id\",\n \"batch_id\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStoreFileBatch.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.filebatches.FileBatchCancelParams;\nimport com.openai.models.vectorstores.filebatches.VectorStoreFileBatch;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileBatchCancelParams params = FileBatchCancelParams.builder()\n .vectorStoreId(\"vector_store_id\")\n .batchId(\"batch_id\")\n .build();\n VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().cancel(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store_file_batch = openai.vector_stores.file_batches.cancel(\"batch_id\", vector_store_id: \"vector_store_id\")\n\nputs(vector_store_file_batch)" + } + } + }, + "description": "Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible." + } + }, + "/vector_stores/{vector_store_id}/file_batches/{batch_id}/files": { + "get": { + "operationId": "listFilesInVectorStoreBatch", + "tags": [ + "Vector stores" + ], + "summary": "List vector store files in a batch", + "parameters": [ + { + "name": "vector_store_id", + "in": "path", + "description": "The ID of the vector store that the files belong to.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "batch_id", + "in": "path", + "description": "The ID of the file batch that the files belong to.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "before", + "in": "query", + "description": "A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "filter", + "in": "query", + "description": "Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`.", + "schema": { + "type": "string", + "enum": [ + "in_progress", + "completed", + "failed", + "cancelled" + ] + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListVectorStoreFilesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List vector store files in a batch", + "group": "vector_stores", + "returns": "A list of [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"file-abc123\",\n \"object\": \"vector_store.file\",\n \"created_at\": 1699061776,\n \"vector_store_id\": \"vs_abc123\"\n },\n {\n \"id\": \"file-abc456\",\n \"object\": \"vector_store.file\",\n \"created_at\": 1699061776,\n \"vector_store_id\": \"vs_abc123\"\n }\n ],\n \"first_id\": \"file-abc123\",\n \"last_id\": \"file-abc456\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/files \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.vector_stores.file_batches.list_files(\n batch_id=\"batch_id\",\n vector_store_id=\"vector_store_id\",\n)\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const vectorStoreFile of client.vectorStores.fileBatches.listFiles('batch_id', {\n vector_store_id: 'vector_store_id',\n})) {\n console.log(vectorStoreFile.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.VectorStores.FileBatches.ListFiles(\n context.TODO(),\n \"vector_store_id\",\n \"batch_id\",\n openai.VectorStoreFileBatchListFilesParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.filebatches.FileBatchListFilesPage;\nimport com.openai.models.vectorstores.filebatches.FileBatchListFilesParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileBatchListFilesParams params = FileBatchListFilesParams.builder()\n .vectorStoreId(\"vector_store_id\")\n .batchId(\"batch_id\")\n .build();\n FileBatchListFilesPage page = client.vectorStores().fileBatches().listFiles(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.vector_stores.file_batches.list_files(\"batch_id\", vector_store_id: \"vector_store_id\")\n\nputs(page)" + } + } + }, + "description": "Returns a list of vector store files in a batch." + } + }, + "/vector_stores/{vector_store_id}/files": { + "get": { + "operationId": "listVectorStoreFiles", + "tags": [ + "Vector stores" + ], + "summary": "List vector store files", + "parameters": [ + { + "name": "vector_store_id", + "in": "path", + "description": "The ID of the vector store that the files belong to.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.\n", + "required": false, + "schema": { + "type": "integer", + "default": 20 + } + }, + { + "name": "order", + "in": "query", + "description": "Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.\n", + "schema": { + "type": "string", + "default": "desc", + "enum": [ + "asc", + "desc" + ] + } + }, + { + "name": "after", + "in": "query", + "description": "A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "before", + "in": "query", + "description": "A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.\n", + "schema": { + "type": "string" + } + }, + { + "name": "filter", + "in": "query", + "description": "Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`.", + "schema": { + "type": "string", + "enum": [ + "in_progress", + "completed", + "failed", + "cancelled" + ] + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListVectorStoreFilesResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "List vector store files", + "group": "vector_stores", + "returns": "A list of [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) objects.", + "examples": { + "response": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"file-abc123\",\n \"object\": \"vector_store.file\",\n \"created_at\": 1699061776,\n \"vector_store_id\": \"vs_abc123\"\n },\n {\n \"id\": \"file-abc456\",\n \"object\": \"vector_store.file\",\n \"created_at\": 1699061776,\n \"vector_store_id\": \"vs_abc123\"\n }\n ],\n \"first_id\": \"file-abc123\",\n \"last_id\": \"file-abc456\",\n \"has_more\": false\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123/files \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.vector_stores.files.list(\n vector_store_id=\"vector_store_id\",\n)\npage = page.data[0]\nprint(page.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const vectorStoreFile of client.vectorStores.files.list('vector_store_id')) {\n console.log(vectorStoreFile.id);\n}", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.VectorStores.Files.List(\n context.TODO(),\n \"vector_store_id\",\n openai.VectorStoreFileListParams{\n\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.files.FileListPage;\nimport com.openai.models.vectorstores.files.FileListParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileListPage page = client.vectorStores().files().list(\"vector_store_id\");\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.vector_stores.files.list(\"vector_store_id\")\n\nputs(page)" + } + } + }, + "description": "Returns a list of vector store files." + }, + "post": { + "operationId": "createVectorStoreFile", + "tags": [ + "Vector stores" + ], + "summary": "Create vector store file", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string", + "example": "vs_abc123" + }, + "description": "The ID of the vector store for which to create a File.\n" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateVectorStoreFileRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreFileObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Create vector store file", + "group": "vector_stores", + "returns": "A [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object.", + "examples": { + "response": "{\n \"id\": \"file-abc123\",\n \"object\": \"vector_store.file\",\n \"created_at\": 1699061776,\n \"usage_bytes\": 1234,\n \"vector_store_id\": \"vs_abcd\",\n \"status\": \"completed\",\n \"last_error\": null\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123/files \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -d '{\n \"file_id\": \"file-abc123\"\n }'\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store_file = client.vector_stores.files.create(\n vector_store_id=\"vs_abc123\",\n file_id=\"file_id\",\n)\nprint(vector_store_file.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\nconst vectorStoreFile = await client.vectorStores.files.create('vs_abc123', { file_id: 'file_id' });\n\nconsole.log(vectorStoreFile.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStoreFile, err := client.VectorStores.Files.New(\n context.TODO(),\n \"vs_abc123\",\n openai.VectorStoreFileNewParams{\n FileID: \"file_id\",\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStoreFile.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.files.FileCreateParams;\nimport com.openai.models.vectorstores.files.VectorStoreFile;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileCreateParams params = FileCreateParams.builder()\n .vectorStoreId(\"vs_abc123\")\n .fileId(\"file_id\")\n .build();\n VectorStoreFile vectorStoreFile = client.vectorStores().files().create(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store_file = openai.vector_stores.files.create(\"vs_abc123\", file_id: \"file_id\")\n\nputs(vector_store_file)" + } + } + }, + "description": "Create a vector store file by attaching a [File](https://platform.openai.com/docs/api-reference/files) to a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)." + } + }, + "/vector_stores/{vector_store_id}/files/{file_id}": { + "get": { + "operationId": "getVectorStoreFile", + "tags": [ + "Vector stores" + ], + "summary": "Retrieve vector store file", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string", + "example": "vs_abc123" + }, + "description": "The ID of the vector store that the file belongs to." + }, + { + "in": "path", + "name": "file_id", + "required": true, + "schema": { + "type": "string", + "example": "file-abc123" + }, + "description": "The ID of the file being retrieved." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreFileObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve vector store file", + "group": "vector_stores", + "returns": "The [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object.", + "examples": { + "response": "{\n \"id\": \"file-abc123\",\n \"object\": \"vector_store.file\",\n \"created_at\": 1699061776,\n \"vector_store_id\": \"vs_abcd\",\n \"status\": \"completed\",\n \"last_error\": null\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\"\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store_file = client.vector_stores.files.retrieve(\n file_id=\"file-abc123\",\n vector_store_id=\"vs_abc123\",\n)\nprint(vector_store_file.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst vectorStoreFile = await client.vectorStores.files.retrieve('file-abc123', {\n vector_store_id: 'vs_abc123',\n});\n\nconsole.log(vectorStoreFile.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStoreFile, err := client.VectorStores.Files.Get(\n context.TODO(),\n \"vs_abc123\",\n \"file-abc123\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStoreFile.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.files.FileRetrieveParams;\nimport com.openai.models.vectorstores.files.VectorStoreFile;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileRetrieveParams params = FileRetrieveParams.builder()\n .vectorStoreId(\"vs_abc123\")\n .fileId(\"file-abc123\")\n .build();\n VectorStoreFile vectorStoreFile = client.vectorStores().files().retrieve(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store_file = openai.vector_stores.files.retrieve(\"file-abc123\", vector_store_id: \"vs_abc123\")\n\nputs(vector_store_file)" + } + } + }, + "description": "Retrieves a vector store file." + }, + "delete": { + "operationId": "deleteVectorStoreFile", + "tags": [ + "Vector stores" + ], + "summary": "Delete vector store file", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the vector store that the file belongs to." + }, + { + "in": "path", + "name": "file_id", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the file to delete." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeleteVectorStoreFileResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Delete vector store file", + "group": "vector_stores", + "returns": "Deletion status", + "examples": { + "response": "{\n id: \"file-abc123\",\n object: \"vector_store.file.deleted\",\n deleted: true\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"OpenAI-Beta: assistants=v2\" \\\n -X DELETE\n", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store_file_deleted = client.vector_stores.files.delete(\n file_id=\"file_id\",\n vector_store_id=\"vector_store_id\",\n)\nprint(vector_store_file_deleted.id)", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst vectorStoreFileDeleted = await client.vectorStores.files.delete('file_id', {\n vector_store_id: 'vector_store_id',\n});\n\nconsole.log(vectorStoreFileDeleted.id);", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStoreFileDeleted, err := client.VectorStores.Files.Delete(\n context.TODO(),\n \"vector_store_id\",\n \"file_id\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStoreFileDeleted.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.files.FileDeleteParams;\nimport com.openai.models.vectorstores.files.VectorStoreFileDeleted;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileDeleteParams params = FileDeleteParams.builder()\n .vectorStoreId(\"vector_store_id\")\n .fileId(\"file_id\")\n .build();\n VectorStoreFileDeleted vectorStoreFileDeleted = client.vectorStores().files().delete(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store_file_deleted = openai.vector_stores.files.delete(\"file_id\", vector_store_id: \"vector_store_id\")\n\nputs(vector_store_file_deleted)" + } + } + }, + "description": "Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. To delete the file, use the [delete file](https://platform.openai.com/docs/api-reference/files/delete) endpoint." + }, + "post": { + "operationId": "updateVectorStoreFileAttributes", + "tags": [ + "Vector stores" + ], + "summary": "Update vector store file attributes", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string", + "example": "vs_abc123" + }, + "description": "The ID of the vector store the file belongs to." + }, + { + "in": "path", + "name": "file_id", + "required": true, + "schema": { + "type": "string", + "example": "file-abc123" + }, + "description": "The ID of the file to update attributes." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateVectorStoreFileAttributesRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreFileObject" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Update vector store file attributes", + "group": "vector_stores", + "returns": "The updated [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object.", + "examples": { + "response": "{\n \"id\": \"file-abc123\",\n \"object\": \"vector_store.file\",\n \"usage_bytes\": 1234,\n \"created_at\": 1699061776,\n \"vector_store_id\": \"vs_abcd\",\n \"status\": \"completed\",\n \"last_error\": null,\n \"chunking_strategy\": {...},\n \"attributes\": {\"key1\": \"value1\", \"key2\": 2}\n}\n", + "request": { + "curl": "curl https://api.openai.com/v1/vector_stores/{vector_store_id}/files/{file_id} \\\n -H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"attributes\": {\"key1\": \"value1\", \"key2\": 2}}'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\nconst vectorStoreFile = await client.vectorStores.files.update('file-abc123', {\n vector_store_id: 'vs_abc123',\n attributes: { foo: 'string' },\n});\n\nconsole.log(vectorStoreFile.id);", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\nvector_store_file = client.vector_stores.files.update(\n file_id=\"file-abc123\",\n vector_store_id=\"vs_abc123\",\n attributes={\n \"foo\": \"string\"\n },\n)\nprint(vector_store_file.id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n vectorStoreFile, err := client.VectorStores.Files.Update(\n context.TODO(),\n \"vs_abc123\",\n \"file-abc123\",\n openai.VectorStoreFileUpdateParams{\n Attributes: map[string]openai.VectorStoreFileUpdateParamsAttributeUnion{\n \"foo\": openai.VectorStoreFileUpdateParamsAttributeUnion{\n OfString: openai.String(\"string\"),\n },\n },\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", vectorStoreFile.ID)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.core.JsonValue;\nimport com.openai.models.vectorstores.files.FileUpdateParams;\nimport com.openai.models.vectorstores.files.VectorStoreFile;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileUpdateParams params = FileUpdateParams.builder()\n .vectorStoreId(\"vs_abc123\")\n .fileId(\"file-abc123\")\n .attributes(FileUpdateParams.Attributes.builder()\n .putAdditionalProperty(\"foo\", JsonValue.from(\"string\"))\n .build())\n .build();\n VectorStoreFile vectorStoreFile = client.vectorStores().files().update(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\nvector_store_file = openai.vector_stores.files.update(\n \"file-abc123\",\n vector_store_id: \"vs_abc123\",\n attributes: {foo: \"string\"}\n)\n\nputs(vector_store_file)" + } + } + }, + "description": "Update attributes on a vector store file." + } + }, + "/vector_stores/{vector_store_id}/files/{file_id}/content": { + "get": { + "operationId": "retrieveVectorStoreFileContent", + "tags": [ + "Vector stores" + ], + "summary": "Retrieve vector store file content", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string", + "example": "vs_abc123" + }, + "description": "The ID of the vector store." + }, + { + "in": "path", + "name": "file_id", + "required": true, + "schema": { + "type": "string", + "example": "file-abc123" + }, + "description": "The ID of the file within the vector store." + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreFileContentResponse" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Retrieve vector store file content", + "group": "vector_stores", + "returns": "The parsed contents of the specified vector store file.", + "examples": { + "response": "{\n \"file_id\": \"file-abc123\",\n \"filename\": \"example.txt\",\n \"attributes\": {\"key\": \"value\"},\n \"content\": [\n {\"type\": \"text\", \"text\": \"...\"},\n ...\n ]\n}\n", + "request": { + "curl": "curl \\\nhttps://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123/content \\\n-H \"Authorization: Bearer $OPENAI_API_KEY\"\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({\n apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const fileContentResponse of client.vectorStores.files.content('file-abc123', {\n vector_store_id: 'vs_abc123',\n})) {\n console.log(fileContentResponse.text);\n}", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.vector_stores.files.content(\n file_id=\"file-abc123\",\n vector_store_id=\"vs_abc123\",\n)\npage = page.data[0]\nprint(page.text)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.VectorStores.Files.Content(\n context.TODO(),\n \"vs_abc123\",\n \"file-abc123\",\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.files.FileContentPage;\nimport com.openai.models.vectorstores.files.FileContentParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n FileContentParams params = FileContentParams.builder()\n .vectorStoreId(\"vs_abc123\")\n .fileId(\"file-abc123\")\n .build();\n FileContentPage page = client.vectorStores().files().content(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.vector_stores.files.content(\"file-abc123\", vector_store_id: \"vs_abc123\")\n\nputs(page)" + } + } + }, + "description": "Retrieve the parsed contents of a vector store file." + } + }, + "/vector_stores/{vector_store_id}/search": { + "post": { + "operationId": "searchVectorStore", + "tags": [ + "Vector stores" + ], + "summary": "Search vector store", + "parameters": [ + { + "in": "path", + "name": "vector_store_id", + "required": true, + "schema": { + "type": "string", + "example": "vs_abc123" + }, + "description": "The ID of the vector store to search." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreSearchRequest" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VectorStoreSearchResultsPage" + } + } + } + } + }, + "x-oaiMeta": { + "name": "Search vector store", + "group": "vector_stores", + "returns": "A page of search results from the vector store.", + "examples": { + "response": "{\n \"object\": \"vector_store.search_results.page\",\n \"search_query\": \"What is the return policy?\",\n \"data\": [\n {\n \"file_id\": \"file_123\",\n \"filename\": \"document.pdf\",\n \"score\": 0.95,\n \"attributes\": {\n \"author\": \"John Doe\",\n \"date\": \"2023-01-01\"\n },\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": \"Relevant chunk\"\n }\n ]\n },\n {\n \"file_id\": \"file_456\",\n \"filename\": \"notes.txt\",\n \"score\": 0.89,\n \"attributes\": {\n \"author\": \"Jane Smith\",\n \"date\": \"2023-01-02\"\n },\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": \"Sample text content from the vector store.\"\n }\n ]\n }\n ],\n \"has_more\": false,\n \"next_page\": null\n}\n", + "request": { + "curl": "curl -X POST \\\nhttps://api.openai.com/v1/vector_stores/vs_abc123/search \\\n-H \"Authorization: Bearer $OPENAI_API_KEY\" \\\n-H \"Content-Type: application/json\" \\\n-d '{\"query\": \"What is the return policy?\", \"filters\": {...}}'\n", + "node.js": "import OpenAI from 'openai';\n\nconst client = new OpenAI({ apiKey: 'My API Key',\n});\n\n// Automatically fetches more pages as needed.\nfor await (const vectorStoreSearchResponse of client.vectorStores.search('vs_abc123', { query: 'string' })) { console.log(vectorStoreSearchResponse.file_id);\n}", + "python": "from openai import OpenAI\n\nclient = OpenAI(\n api_key=\"My API Key\",\n)\npage = client.vector_stores.search(\n vector_store_id=\"vs_abc123\",\n query=\"string\",\n)\npage = page.data[0]\nprint(page.file_id)", + "go": "package main\n\nimport (\n \"context\"\n \"fmt\"\n\n \"github.com/openai/openai-go\"\n \"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n client := openai.NewClient(\n option.WithAPIKey(\"My API Key\"),\n )\n page, err := client.VectorStores.Search(\n context.TODO(),\n \"vs_abc123\",\n openai.VectorStoreSearchParams{\n Query: openai.VectorStoreSearchParamsQueryUnion{\n OfString: openai.String(\"string\"),\n },\n },\n )\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\"%+v\\n\", page)\n}\n", + "java": "package com.openai.example;\n\nimport com.openai.client.OpenAIClient;\nimport com.openai.client.okhttp.OpenAIOkHttpClient;\nimport com.openai.models.vectorstores.VectorStoreSearchPage;\nimport com.openai.models.vectorstores.VectorStoreSearchParams;\n\npublic final class Main {\n private Main() {}\n\n public static void main(String[] args) {\n OpenAIClient client = OpenAIOkHttpClient.fromEnv();\n\n VectorStoreSearchParams params = VectorStoreSearchParams.builder()\n .vectorStoreId(\"vs_abc123\")\n .query(\"string\")\n .build();\n VectorStoreSearchPage page = client.vectorStores().search(params);\n }\n}", + "ruby": "require \"openai\"\n\nopenai = OpenAI::Client.new(api_key: \"My API Key\")\n\npage = openai.vector_stores.search(\"vs_abc123\", query: \"string\")\n\nputs(page)" + } + } + }, + "description": "Search a vector store for relevant chunks based on a query and file attributes filter." + } + } + }, + "webhooks": { + "batch_cancelled": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookBatchCancelled" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "batch_completed": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookBatchCompleted" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "batch_expired": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookBatchExpired" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "batch_failed": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookBatchFailed" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "eval_run_canceled": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookEvalRunCanceled" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "eval_run_failed": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookEvalRunFailed" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "eval_run_succeeded": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookEvalRunSucceeded" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "fine_tuning_job_cancelled": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookFineTuningJobCancelled" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "fine_tuning_job_failed": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookFineTuningJobFailed" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "fine_tuning_job_succeeded": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookFineTuningJobSucceeded" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "realtime_call_incoming": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookRealtimeCallIncoming" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200\nstatus codes will be retried.\n" + } + } + } + }, + "response_cancelled": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookResponseCancelled" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "response_completed": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookResponseCompleted" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "response_failed": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookResponseFailed" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + }, + "response_incomplete": { + "post": { + "requestBody": { + "description": "The event payload sent by the API.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookResponseIncomplete" + } + } + } + }, + "responses": { + "200": { + "description": "Return a 200 status code to acknowledge receipt of the event. Non-200 \nstatus codes will be retried.\n" + } + } + } + } + }, + "components": { + "schemas": { + "AddUploadPartRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "data": { + "description": "The chunk of bytes for this Part.\n", + "type": "string", + "format": "binary" + } + }, + "required": [ + "data" + ] + }, + "AdminApiKey": { + "type": "object", + "description": "Represents an individual Admin API key in an org.", + "properties": { + "object": { + "type": "string", + "example": "organization.admin_api_key", + "description": "The object type, which is always `organization.admin_api_key`", + "x-stainless-const": true + }, + "id": { + "type": "string", + "example": "key_abc", + "description": "The identifier, which can be referenced in API endpoints" + }, + "name": { + "type": "string", + "example": "Administration Key", + "description": "The name of the API key" + }, + "redacted_value": { + "type": "string", + "example": "sk-admin...def", + "description": "The redacted value of the API key" + }, + "value": { + "type": "string", + "example": "sk-admin-1234abcd", + "description": "The value of the API key. Only shown on create." + }, + "created_at": { + "type": "integer", + "format": "int64", + "example": 1711471533, + "description": "The Unix timestamp (in seconds) of when the API key was created" + }, + "last_used_at": { + "type": "integer", + "format": "int64", + "nullable": true, + "example": 1711471534, + "description": "The Unix timestamp (in seconds) of when the API key was last used" + }, + "owner": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "user", + "description": "Always `user`" + }, + "object": { + "type": "string", + "example": "organization.user", + "description": "The object type, which is always organization.user" + }, + "id": { + "type": "string", + "example": "sa_456", + "description": "The identifier, which can be referenced in API endpoints" + }, + "name": { + "type": "string", + "example": "My Service Account", + "description": "The name of the user" + }, + "created_at": { + "type": "integer", + "format": "int64", + "example": 1711471533, + "description": "The Unix timestamp (in seconds) of when the user was created" + }, + "role": { + "type": "string", + "example": "owner", + "description": "Always `owner`" + } + } + } + }, + "required": [ + "object", + "redacted_value", + "name", + "created_at", + "last_used_at", + "id", + "owner" + ], + "x-oaiMeta": { + "name": "The admin API key object", + "example": "{\n \"object\": \"organization.admin_api_key\",\n \"id\": \"key_abc\",\n \"name\": \"Main Admin Key\",\n \"redacted_value\": \"sk-admin...xyz\",\n \"created_at\": 1711471533,\n \"last_used_at\": 1711471534,\n \"owner\": {\n \"type\": \"user\",\n \"object\": \"organization.user\",\n \"id\": \"user_123\",\n \"name\": \"John Doe\",\n \"created_at\": 1711471533,\n \"role\": \"owner\"\n }\n}\n" + } + }, + "ApiKeyList": { + "type": "object", + "properties": { + "object": { + "type": "string", + "example": "list" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminApiKey" + } + }, + "has_more": { + "type": "boolean", + "example": false + }, + "first_id": { + "type": "string", + "example": "key_abc" + }, + "last_id": { + "type": "string", + "example": "key_xyz" + } + } + }, + "AssistantObject": { + "type": "object", + "title": "Assistant", + "description": "Represents an `assistant` that can call the model and use tools.", + "properties": { + "id": { + "description": "The identifier, which can be referenced in API endpoints.", + "type": "string" + }, + "object": { + "description": "The object type, which is always `assistant`.", + "type": "string", + "enum": [ + "assistant" + ], + "x-stainless-const": true + }, + "created_at": { + "description": "The Unix timestamp (in seconds) for when the assistant was created.", + "type": "integer" + }, + "name": { + "description": "The name of the assistant. The maximum length is 256 characters.\n", + "type": "string", + "maxLength": 256, + "nullable": true + }, + "description": { + "description": "The description of the assistant. The maximum length is 512 characters.\n", + "type": "string", + "maxLength": 512, + "nullable": true + }, + "model": { + "description": "ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n", + "type": "string" + }, + "instructions": { + "description": "The system instructions that the assistant uses. The maximum length is 256,000 characters.\n", + "type": "string", + "maxLength": 256000, + "nullable": true + }, + "tools": { + "description": "A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n", + "default": [], + "type": "array", + "maxItems": 128, + "items": { + "$ref": "#/components/schemas/AssistantTool" + } + }, + "tool_resources": { + "type": "object", + "description": "A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n", + "properties": { + "code_interpreter": { + "type": "object", + "properties": { + "file_ids": { + "type": "array", + "description": "A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool.\n", + "default": [], + "maxItems": 20, + "items": { + "type": "string" + } + } + } + }, + "file_search": { + "type": "object", + "properties": { + "vector_store_ids": { + "type": "array", + "description": "The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + "maxItems": 1, + "items": { + "type": "string" + } + } + } + } + }, + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "temperature": { + "description": "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 1, + "example": 1, + "nullable": true + }, + "top_p": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 1, + "example": 1, + "nullable": true, + "description": "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }, + "response_format": { + "$ref": "#/components/schemas/AssistantsApiResponseFormatOption", + "nullable": true + } + }, + "required": [ + "id", + "object", + "created_at", + "name", + "description", + "model", + "instructions", + "tools", + "metadata" + ], + "x-oaiMeta": { + "name": "The assistant object", + "beta": true, + "example": "{\n \"id\": \"asst_abc123\",\n \"object\": \"assistant\",\n \"created_at\": 1698984975,\n \"name\": \"Math Tutor\",\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You are a personal math tutor. When asked a question, write and run Python code to answer the question.\",\n \"tools\": [\n {\n \"type\": \"code_interpreter\"\n }\n ],\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n}\n" + } + }, + "AssistantStreamEvent": { + "description": "Represents an event emitted when streaming a Run.\n\nEach event in a server-sent events stream has an `event` and `data` property:\n\n```\nevent: thread.created\ndata: {\"id\": \"thread_123\", \"object\": \"thread\", ...}\n```\n\nWe emit events whenever a new object is created, transitions to a new state, or is being\nstreamed in parts (deltas). For example, we emit `thread.run.created` when a new run\nis created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses\nto create a message during a run, we emit a `thread.message.created event`, a\n`thread.message.in_progress` event, many `thread.message.delta` events, and finally a\n`thread.message.completed` event.\n\nWe may add additional events over time, so we recommend handling unknown events gracefully\nin your code. See the [Assistants API quickstart](https://platform.openai.com/docs/assistants/overview) to learn how to\nintegrate the Assistants API with streaming.\n", + "x-oaiMeta": { + "name": "Assistant stream events", + "beta": true + }, + "anyOf": [ + { + "$ref": "#/components/schemas/ThreadStreamEvent" + }, + { + "$ref": "#/components/schemas/RunStreamEvent" + }, + { + "$ref": "#/components/schemas/RunStepStreamEvent" + }, + { + "$ref": "#/components/schemas/MessageStreamEvent" + }, + { + "$ref": "#/components/schemas/ErrorEvent", + "x-stainless-variantName": "error_event" + } + ], + "discriminator": { + "propertyName": "event" + } + }, + "AssistantSupportedModels": { + "type": "string", + "enum": [ + "gpt-5", + "gpt-5-mini", + "gpt-5-nano", + "gpt-5-2025-08-07", + "gpt-5-mini-2025-08-07", + "gpt-5-nano-2025-08-07", + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", + "o3-mini", + "o3-mini-2025-01-31", + "o1", + "o1-2024-12-17", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613" + ] + }, + "AssistantToolsCode": { + "type": "object", + "title": "Code interpreter tool", + "properties": { + "type": { + "type": "string", + "description": "The type of tool being defined: `code_interpreter`", + "enum": [ + "code_interpreter" + ], + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + "AssistantToolsFileSearch": { + "type": "object", + "title": "FileSearch tool", + "properties": { + "type": { + "type": "string", + "description": "The type of tool being defined: `file_search`", + "enum": [ + "file_search" + ], + "x-stainless-const": true + }, + "file_search": { + "type": "object", + "description": "Overrides for the file search tool.", + "properties": { + "max_num_results": { + "type": "integer", + "minimum": 1, + "maximum": 50, + "description": "The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive.\n\nNote that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n" + }, + "ranking_options": { + "$ref": "#/components/schemas/FileSearchRankingOptions" + } + } + } + }, + "required": [ + "type" + ] + }, + "AssistantToolsFileSearchTypeOnly": { + "type": "object", + "title": "FileSearch tool", + "properties": { + "type": { + "type": "string", + "description": "The type of tool being defined: `file_search`", + "enum": [ + "file_search" + ], + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + "AssistantToolsFunction": { + "type": "object", + "title": "Function tool", + "properties": { + "type": { + "type": "string", + "description": "The type of tool being defined: `function`", + "enum": [ + "function" + ], + "x-stainless-const": true + }, + "function": { + "$ref": "#/components/schemas/FunctionObject" + } + }, + "required": [ + "type", + "function" + ] + }, + "AssistantsApiResponseFormatOption": { + "description": "Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n\nSetting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n\nSetting to `{ \"type\": \"json_object\" }` enables JSON mode, which ensures the message the model generates is valid JSON.\n\n**Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly \"stuck\" request. Also note that the message content may be partially cut off if `finish_reason=\"length\"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.\n", + "anyOf": [ + { + "type": "string", + "description": "`auto` is the default value\n", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "$ref": "#/components/schemas/ResponseFormatText" + }, + { + "$ref": "#/components/schemas/ResponseFormatJsonObject" + }, + { + "$ref": "#/components/schemas/ResponseFormatJsonSchema" + } + ] + }, + "AssistantsApiToolChoiceOption": { + "description": "Controls which (if any) tool is called by the model.\n`none` means the model will not call any tools and instead generates a message.\n`auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools before responding to the user.\nSpecifying a particular tool like `{\"type\": \"file_search\"}` or `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.\n", + "anyOf": [ + { + "type": "string", + "description": "`none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user.\n", + "enum": [ + "none", + "auto", + "required" + ], + "title": "Auto" + }, + { + "$ref": "#/components/schemas/AssistantsNamedToolChoice" + } + ] + }, + "AssistantsNamedToolChoice": { + "type": "object", + "description": "Specifies a tool the model should use. Use to force the model to call a specific tool.", + "properties": { + "type": { + "type": "string", + "enum": [ + "function", + "code_interpreter", + "file_search" + ], + "description": "The type of the tool. If type is `function`, the function name must be set" + }, + "function": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the function to call." + } + }, + "required": [ + "name" + ] + } + }, + "required": [ + "type" + ] + }, + "AudioResponseFormat": { + "description": "The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is `json`.\n", + "type": "string", + "enum": [ + "json", + "text", + "srt", + "verbose_json", + "vtt" + ], + "default": "json" + }, + "AuditLog": { + "type": "object", + "description": "A log of a user action or configuration change within this organization.", + "properties": { + "id": { + "type": "string", + "description": "The ID of this log." + }, + "type": { + "$ref": "#/components/schemas/AuditLogEventType" + }, + "effective_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of the event." + }, + "project": { + "type": "object", + "description": "The project that the action was scoped to. Absent for actions not scoped to projects. Note that any admin actions taken via Admin API keys are associated with the default project.", + "properties": { + "id": { + "type": "string", + "description": "The project ID." + }, + "name": { + "type": "string", + "description": "The project title." + } + } + }, + "actor": { + "$ref": "#/components/schemas/AuditLogActor" + }, + "api_key.created": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The tracking ID of the API key." + }, + "data": { + "type": "object", + "description": "The payload used to create the API key.", + "properties": { + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A list of scopes allowed for the API key, e.g. `[\"api.model.request\"]`" + } + } + } + } + }, + "api_key.updated": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The tracking ID of the API key." + }, + "changes_requested": { + "type": "object", + "description": "The payload used to update the API key.", + "properties": { + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A list of scopes allowed for the API key, e.g. `[\"api.model.request\"]`" + } + } + } + } + }, + "api_key.deleted": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The tracking ID of the API key." + } + } + }, + "checkpoint_permission.created": { + "type": "object", + "description": "The project and fine-tuned model checkpoint that the checkpoint permission was created for.", + "properties": { + "id": { + "type": "string", + "description": "The ID of the checkpoint permission." + }, + "data": { + "type": "object", + "description": "The payload used to create the checkpoint permission.", + "properties": { + "project_id": { + "type": "string", + "description": "The ID of the project that the checkpoint permission was created for." + }, + "fine_tuned_model_checkpoint": { + "type": "string", + "description": "The ID of the fine-tuned model checkpoint." + } + } + } + } + }, + "checkpoint_permission.deleted": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The ID of the checkpoint permission." + } + } + }, + "invite.sent": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The ID of the invite." + }, + "data": { + "type": "object", + "description": "The payload used to create the invite.", + "properties": { + "email": { + "type": "string", + "description": "The email invited to the organization." + }, + "role": { + "type": "string", + "description": "The role the email was invited to be. Is either `owner` or `member`." + } + } + } + } + }, + "invite.accepted": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The ID of the invite." + } + } + }, + "invite.deleted": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The ID of the invite." + } + } + }, + "login.failed": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "error_code": { + "type": "string", + "description": "The error code of the failure." + }, + "error_message": { + "type": "string", + "description": "The error message of the failure." + } + } + }, + "logout.failed": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "error_code": { + "type": "string", + "description": "The error code of the failure." + }, + "error_message": { + "type": "string", + "description": "The error message of the failure." + } + } + }, + "organization.updated": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The organization ID." + }, + "changes_requested": { + "type": "object", + "description": "The payload used to update the organization settings.", + "properties": { + "title": { + "type": "string", + "description": "The organization title." + }, + "description": { + "type": "string", + "description": "The organization description." + }, + "name": { + "type": "string", + "description": "The organization name." + }, + "threads_ui_visibility": { + "type": "string", + "description": "Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`." + }, + "usage_dashboard_visibility": { + "type": "string", + "description": "Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`." + }, + "api_call_logging": { + "type": "string", + "description": "How your organization logs data from supported API calls. One of `disabled`, `enabled_per_call`, `enabled_for_all_projects`, or `enabled_for_selected_projects`" + }, + "api_call_logging_project_ids": { + "type": "string", + "description": "The list of project ids if api_call_logging is set to `enabled_for_selected_projects`" + } + } + } + } + }, + "project.created": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The project ID." + }, + "data": { + "type": "object", + "description": "The payload used to create the project.", + "properties": { + "name": { + "type": "string", + "description": "The project name." + }, + "title": { + "type": "string", + "description": "The title of the project as seen on the dashboard." + } + } + } + } + }, + "project.updated": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The project ID." + }, + "changes_requested": { + "type": "object", + "description": "The payload used to update the project.", + "properties": { + "title": { + "type": "string", + "description": "The title of the project as seen on the dashboard." + } + } + } + } + }, + "project.archived": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The project ID." + } + } + }, + "rate_limit.updated": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The rate limit ID" + }, + "changes_requested": { + "type": "object", + "description": "The payload used to update the rate limits.", + "properties": { + "max_requests_per_1_minute": { + "type": "integer", + "description": "The maximum requests per minute." + }, + "max_tokens_per_1_minute": { + "type": "integer", + "description": "The maximum tokens per minute." + }, + "max_images_per_1_minute": { + "type": "integer", + "description": "The maximum images per minute. Only relevant for certain models." + }, + "max_audio_megabytes_per_1_minute": { + "type": "integer", + "description": "The maximum audio megabytes per minute. Only relevant for certain models." + }, + "max_requests_per_1_day": { + "type": "integer", + "description": "The maximum requests per day. Only relevant for certain models." + }, + "batch_1_day_max_input_tokens": { + "type": "integer", + "description": "The maximum batch input tokens per day. Only relevant for certain models." + } + } + } + } + }, + "rate_limit.deleted": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The rate limit ID" + } + } + }, + "service_account.created": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The service account ID." + }, + "data": { + "type": "object", + "description": "The payload used to create the service account.", + "properties": { + "role": { + "type": "string", + "description": "The role of the service account. Is either `owner` or `member`." + } + } + } + } + }, + "service_account.updated": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The service account ID." + }, + "changes_requested": { + "type": "object", + "description": "The payload used to updated the service account.", + "properties": { + "role": { + "type": "string", + "description": "The role of the service account. Is either `owner` or `member`." + } + } + } + } + }, + "service_account.deleted": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The service account ID." + } + } + }, + "user.added": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The user ID." + }, + "data": { + "type": "object", + "description": "The payload used to add the user to the project.", + "properties": { + "role": { + "type": "string", + "description": "The role of the user. Is either `owner` or `member`." + } + } + } + } + }, + "user.updated": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The project ID." + }, + "changes_requested": { + "type": "object", + "description": "The payload used to update the user.", + "properties": { + "role": { + "type": "string", + "description": "The role of the user. Is either `owner` or `member`." + } + } + } + } + }, + "user.deleted": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The user ID." + } + } + }, + "certificate.created": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The certificate ID." + }, + "name": { + "type": "string", + "description": "The name of the certificate." + } + } + }, + "certificate.updated": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The certificate ID." + }, + "name": { + "type": "string", + "description": "The name of the certificate." + } + } + }, + "certificate.deleted": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "id": { + "type": "string", + "description": "The certificate ID." + }, + "name": { + "type": "string", + "description": "The name of the certificate." + }, + "certificate": { + "type": "string", + "description": "The certificate content in PEM format." + } + } + }, + "certificates.activated": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "certificates": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The certificate ID." + }, + "name": { + "type": "string", + "description": "The name of the certificate." + } + } + } + } + } + }, + "certificates.deactivated": { + "type": "object", + "description": "The details for events with this `type`.", + "properties": { + "certificates": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The certificate ID." + }, + "name": { + "type": "string", + "description": "The name of the certificate." + } + } + } + } + } + } + }, + "required": [ + "id", + "type", + "effective_at", + "actor" + ], + "x-oaiMeta": { + "name": "The audit log object", + "example": "{\n \"id\": \"req_xxx_20240101\",\n \"type\": \"api_key.created\",\n \"effective_at\": 1720804090,\n \"actor\": {\n \"type\": \"session\",\n \"session\": {\n \"user\": {\n \"id\": \"user-xxx\",\n \"email\": \"user@example.com\"\n },\n \"ip_address\": \"127.0.0.1\",\n \"user_agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\"\n }\n },\n \"api_key.created\": {\n \"id\": \"key_xxxx\",\n \"data\": {\n \"scopes\": [\"resource.operation\"]\n }\n }\n}\n" + } + }, + "AuditLogActor": { + "type": "object", + "description": "The actor who performed the audit logged action.", + "properties": { + "type": { + "type": "string", + "description": "The type of actor. Is either `session` or `api_key`.", + "enum": [ + "session", + "api_key" + ] + }, + "session": { + "$ref": "#/components/schemas/AuditLogActorSession" + }, + "api_key": { + "$ref": "#/components/schemas/AuditLogActorApiKey" + } + } + }, + "AuditLogActorApiKey": { + "type": "object", + "description": "The API Key used to perform the audit logged action.", + "properties": { + "id": { + "type": "string", + "description": "The tracking id of the API key." + }, + "type": { + "type": "string", + "description": "The type of API key. Can be either `user` or `service_account`.", + "enum": [ + "user", + "service_account" + ] + }, + "user": { + "$ref": "#/components/schemas/AuditLogActorUser" + }, + "service_account": { + "$ref": "#/components/schemas/AuditLogActorServiceAccount" + } + } + }, + "AuditLogActorServiceAccount": { + "type": "object", + "description": "The service account that performed the audit logged action.", + "properties": { + "id": { + "type": "string", + "description": "The service account id." + } + } + }, + "AuditLogActorSession": { + "type": "object", + "description": "The session in which the audit logged action was performed.", + "properties": { + "user": { + "$ref": "#/components/schemas/AuditLogActorUser" + }, + "ip_address": { + "type": "string", + "description": "The IP address from which the action was performed." + } + } + }, + "AuditLogActorUser": { + "type": "object", + "description": "The user who performed the audit logged action.", + "properties": { + "id": { + "type": "string", + "description": "The user id." + }, + "email": { + "type": "string", + "description": "The user email." + } + } + }, + "AuditLogEventType": { + "type": "string", + "description": "The event type.", + "enum": [ + "api_key.created", + "api_key.updated", + "api_key.deleted", + "checkpoint_permission.created", + "checkpoint_permission.deleted", + "invite.sent", + "invite.accepted", + "invite.deleted", + "login.succeeded", + "login.failed", + "logout.succeeded", + "logout.failed", + "organization.updated", + "project.created", + "project.updated", + "project.archived", + "service_account.created", + "service_account.updated", + "service_account.deleted", + "rate_limit.updated", + "rate_limit.deleted", + "user.added", + "user.updated", + "user.deleted" + ] + }, + "AutoChunkingStrategyRequestParam": { + "type": "object", + "title": "Auto Chunking Strategy", + "description": "The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`.", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "Always `auto`.", + "enum": [ + "auto" + ], + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + "Batch": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "object": { + "type": "string", + "enum": [ + "batch" + ], + "description": "The object type, which is always `batch`.", + "x-stainless-const": true + }, + "endpoint": { + "type": "string", + "description": "The OpenAI API endpoint used by the batch." + }, + "errors": { + "type": "object", + "properties": { + "object": { + "type": "string", + "description": "The object type, which is always `list`." + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/BatchError" + } + } + } + }, + "input_file_id": { + "type": "string", + "description": "The ID of the input file for the batch." + }, + "completion_window": { + "type": "string", + "description": "The time frame within which the batch should be processed." + }, + "status": { + "type": "string", + "description": "The current status of the batch.", + "enum": [ + "validating", + "failed", + "in_progress", + "finalizing", + "completed", + "expired", + "cancelling", + "cancelled" + ] + }, + "output_file_id": { + "type": "string", + "description": "The ID of the file containing the outputs of successfully executed requests." + }, + "error_file_id": { + "type": "string", + "description": "The ID of the file containing the outputs of requests with errors." + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the batch was created." + }, + "in_progress_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the batch started processing." + }, + "expires_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the batch will expire." + }, + "finalizing_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the batch started finalizing." + }, + "completed_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the batch was completed." + }, + "failed_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the batch failed." + }, + "expired_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the batch expired." + }, + "cancelling_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the batch started cancelling." + }, + "cancelled_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the batch was cancelled." + }, + "request_counts": { + "$ref": "#/components/schemas/BatchRequestCounts" + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + }, + "required": [ + "id", + "object", + "endpoint", + "input_file_id", + "completion_window", + "status", + "created_at" + ], + "x-oaiMeta": { + "name": "The batch object", + "example": "{\n \"id\": \"batch_abc123\",\n \"object\": \"batch\",\n \"endpoint\": \"/v1/completions\",\n \"errors\": null,\n \"input_file_id\": \"file-abc123\",\n \"completion_window\": \"24h\",\n \"status\": \"completed\",\n \"output_file_id\": \"file-cvaTdG\",\n \"error_file_id\": \"file-HOWS94\",\n \"created_at\": 1711471533,\n \"in_progress_at\": 1711471538,\n \"expires_at\": 1711557933,\n \"finalizing_at\": 1711493133,\n \"completed_at\": 1711493163,\n \"failed_at\": null,\n \"expired_at\": null,\n \"cancelling_at\": null,\n \"cancelled_at\": null,\n \"request_counts\": {\n \"total\": 100,\n \"completed\": 95,\n \"failed\": 5\n },\n \"metadata\": {\n \"customer_id\": \"user_123456789\",\n \"batch_description\": \"Nightly eval job\",\n }\n}\n" + } + }, + "BatchFileExpirationAfter": { + "type": "object", + "title": "File expiration policy", + "description": "The expiration policy for the output and/or error file that are generated for a batch.", + "properties": { + "anchor": { + "description": "Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. Note that the anchor is the file creation time, not the time the batch is created.", + "type": "string", + "enum": [ + "created_at" + ], + "x-stainless-const": true + }, + "seconds": { + "description": "The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days).", + "type": "integer", + "minimum": 3600, + "maximum": 2592000 + } + }, + "required": [ + "anchor", + "seconds" + ] + }, + "BatchRequestInput": { + "type": "object", + "description": "The per-line object of the batch input file", + "properties": { + "custom_id": { + "type": "string", + "description": "A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch." + }, + "method": { + "type": "string", + "enum": [ + "POST" + ], + "description": "The HTTP method to be used for the request. Currently only `POST` is supported.", + "x-stainless-const": true + }, + "url": { + "type": "string", + "description": "The OpenAI API relative URL to be used for the request. Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported." + } + }, + "x-oaiMeta": { + "name": "The request input object", + "example": "{\"custom_id\": \"request-1\", \"method\": \"POST\", \"url\": \"/v1/chat/completions\", \"body\": {\"model\": \"gpt-4o-mini\", \"messages\": [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}, {\"role\": \"user\", \"content\": \"What is 2+2?\"}]}}\n" + } + }, + "BatchRequestOutput": { + "type": "object", + "description": "The per-line object of the batch output and error files", + "properties": { + "id": { + "type": "string" + }, + "custom_id": { + "type": "string", + "description": "A developer-provided per-request id that will be used to match outputs to inputs." + }, + "response": { + "type": "object", + "nullable": true, + "properties": { + "status_code": { + "type": "integer", + "description": "The HTTP status code of the response" + }, + "request_id": { + "type": "string", + "description": "An unique identifier for the OpenAI API request. Please include this request ID when contacting support." + }, + "body": { + "type": "object", + "x-oaiTypeLabel": "map", + "description": "The JSON body of the response" + } + } + }, + "error": { + "type": "object", + "nullable": true, + "description": "For requests that failed with a non-HTTP error, this will contain more information on the cause of the failure.", + "properties": { + "code": { + "type": "string", + "description": "A machine-readable error code." + }, + "message": { + "type": "string", + "description": "A human-readable error message." + } + } + } + }, + "x-oaiMeta": { + "name": "The request output object", + "example": "{\"id\": \"batch_req_wnaDys\", \"custom_id\": \"request-2\", \"response\": {\"status_code\": 200, \"request_id\": \"req_c187b3\", \"body\": {\"id\": \"chatcmpl-9758Iw\", \"object\": \"chat.completion\", \"created\": 1711475054, \"model\": \"gpt-4o-mini\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"2 + 2 equals 4.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 24, \"completion_tokens\": 15, \"total_tokens\": 39}, \"system_fingerprint\": null}}, \"error\": null}\n" + } + }, + "Certificate": { + "type": "object", + "description": "Represents an individual `certificate` uploaded to the organization.", + "properties": { + "object": { + "type": "string", + "enum": [ + "certificate", + "organization.certificate", + "organization.project.certificate" + ], + "description": "The object type.\n\n- If creating, updating, or getting a specific certificate, the object type is `certificate`.\n- If listing, activating, or deactivating certificates for the organization, the object type is `organization.certificate`.\n- If listing, activating, or deactivating certificates for a project, the object type is `organization.project.certificate`.\n", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The identifier, which can be referenced in API endpoints" + }, + "name": { + "type": "string", + "description": "The name of the certificate." + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the certificate was uploaded." + }, + "certificate_details": { + "type": "object", + "properties": { + "valid_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the certificate becomes valid." + }, + "expires_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the certificate expires." + }, + "content": { + "type": "string", + "description": "The content of the certificate in PEM format." + } + } + }, + "active": { + "type": "boolean", + "description": "Whether the certificate is currently active at the specified scope. Not returned when getting details for a specific certificate." + } + }, + "required": [ + "object", + "id", + "name", + "created_at", + "certificate_details" + ], + "x-oaiMeta": { + "name": "The certificate object", + "example": "{\n \"object\": \"certificate\",\n \"id\": \"cert_abc\",\n \"name\": \"My Certificate\",\n \"created_at\": 1234567,\n \"certificate_details\": {\n \"valid_at\": 1234567,\n \"expires_at\": 12345678,\n \"content\": \"-----BEGIN CERTIFICATE----- MIIGAjCCA...6znFlOW+ -----END CERTIFICATE-----\"\n }\n}\n" + } + }, + "ChatCompletionAllowedTools": { + "type": "object", + "title": "Allowed tools", + "description": "Constrains the tools available to the model to a pre-defined set.\n", + "properties": { + "mode": { + "type": "string", + "enum": [ + "auto", + "required" + ], + "description": "Constrains the tools available to the model to a pre-defined set.\n\n`auto` allows the model to pick from among the allowed tools and generate a\nmessage.\n\n`required` requires the model to call one or more of the allowed tools.\n" + }, + "tools": { + "type": "array", + "description": "A list of tool definitions that the model should be allowed to call.\n\nFor the Chat Completions API, the list of tool definitions might look like:\n```json\n[\n { \"type\": \"function\", \"function\": { \"name\": \"get_weather\" } },\n { \"type\": \"function\", \"function\": { \"name\": \"get_time\" } }\n]\n```\n", + "items": { + "type": "object", + "x-oaiExpandable": false, + "description": "A tool definition that the model should be allowed to call.\n", + "additionalProperties": true + } + } + }, + "required": [ + "mode", + "tools" + ] + }, + "ChatCompletionAllowedToolsChoice": { + "type": "object", + "title": "Allowed tools", + "description": "Constrains the tools available to the model to a pre-defined set.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "allowed_tools" + ], + "description": "Allowed tool configuration type. Always `allowed_tools`.", + "x-stainless-const": true + }, + "allowed_tools": { + "$ref": "#/components/schemas/ChatCompletionAllowedTools" + } + }, + "required": [ + "type", + "allowed_tools" + ] + }, + "ChatCompletionDeleted": { + "type": "object", + "properties": { + "object": { + "type": "string", + "description": "The type of object being deleted.", + "enum": [ + "chat.completion.deleted" + ], + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The ID of the chat completion that was deleted." + }, + "deleted": { + "type": "boolean", + "description": "Whether the chat completion was deleted." + } + }, + "required": [ + "object", + "id", + "deleted" + ] + }, + "ChatCompletionFunctionCallOption": { + "type": "object", + "description": "Specifying a particular function via `{\"name\": \"my_function\"}` forces the model to call that function.\n", + "properties": { + "name": { + "type": "string", + "description": "The name of the function to call." + } + }, + "required": [ + "name" + ], + "x-stainless-variantName": "function_call_option" + }, + "ChatCompletionFunctions": { + "type": "object", + "deprecated": true, + "properties": { + "description": { + "type": "string", + "description": "A description of what the function does, used by the model to choose when and how to call the function." + }, + "name": { + "type": "string", + "description": "The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64." + }, + "parameters": { + "$ref": "#/components/schemas/FunctionParameters" + } + }, + "required": [ + "name" + ] + }, + "ChatCompletionList": { + "type": "object", + "title": "ChatCompletionList", + "description": "An object representing a list of Chat Completions.\n", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "default": "list", + "description": "The type of this object. It is always set to \"list\".\n", + "x-stainless-const": true + }, + "data": { + "type": "array", + "description": "An array of chat completion objects.\n", + "items": { + "$ref": "#/components/schemas/CreateChatCompletionResponse" + } + }, + "first_id": { + "type": "string", + "description": "The identifier of the first chat completion in the data array." + }, + "last_id": { + "type": "string", + "description": "The identifier of the last chat completion in the data array." + }, + "has_more": { + "type": "boolean", + "description": "Indicates whether there are more Chat Completions available." + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ], + "x-oaiMeta": { + "name": "The chat completion list object", + "group": "chat", + "example": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"chat.completion\",\n \"id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2\",\n \"model\": \"gpt-4o-2024-08-06\",\n \"created\": 1738960610,\n \"request_id\": \"req_ded8ab984ec4bf840f37566c1011c417\",\n \"tool_choice\": null,\n \"usage\": {\n \"total_tokens\": 31,\n \"completion_tokens\": 18,\n \"prompt_tokens\": 13\n },\n \"seed\": 4944116822809979520,\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"presence_penalty\": 0.0,\n \"frequency_penalty\": 0.0,\n \"system_fingerprint\": \"fp_50cad350e4\",\n \"input_user\": null,\n \"service_tier\": \"default\",\n \"tools\": null,\n \"metadata\": {},\n \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"content\": \"Mind of circuits hum, \\nLearning patterns in silence— \\nFuture's quiet spark.\",\n \"role\": \"assistant\",\n \"tool_calls\": null,\n \"function_call\": null\n },\n \"finish_reason\": \"stop\",\n \"logprobs\": null\n }\n ],\n \"response_format\": null\n }\n ],\n \"first_id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2\",\n \"last_id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2\",\n \"has_more\": false\n}\n" + } + }, + "ChatCompletionMessageCustomToolCall": { + "type": "object", + "title": "Custom tool call", + "description": "A call to a custom tool created by the model.\n", + "properties": { + "id": { + "type": "string", + "description": "The ID of the tool call." + }, + "type": { + "type": "string", + "enum": [ + "custom" + ], + "description": "The type of the tool. Always `custom`.", + "x-stainless-const": true + }, + "custom": { + "type": "object", + "description": "The custom tool that the model called.", + "properties": { + "name": { + "type": "string", + "description": "The name of the custom tool to call." + }, + "input": { + "type": "string", + "description": "The input for the custom tool call generated by the model." + } + }, + "required": [ + "name", + "input" + ] + } + }, + "required": [ + "id", + "type", + "custom" + ] + }, + "ChatCompletionMessageList": { + "type": "object", + "title": "ChatCompletionMessageList", + "description": "An object representing a list of chat completion messages.\n", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "default": "list", + "description": "The type of this object. It is always set to \"list\".\n", + "x-stainless-const": true + }, + "data": { + "type": "array", + "description": "An array of chat completion message objects.\n", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/ChatCompletionResponseMessage" + }, + { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The identifier of the chat message." + }, + "content_parts": { + "type": "array", + "nullable": true, + "description": "If a content parts array was provided, this is an array of `text` and `image_url` parts.\nOtherwise, null.\n", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartText" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartImage" + } + ] + } + } + } + } + ] + } + }, + "first_id": { + "type": "string", + "description": "The identifier of the first chat message in the data array." + }, + "last_id": { + "type": "string", + "description": "The identifier of the last chat message in the data array." + }, + "has_more": { + "type": "boolean", + "description": "Indicates whether there are more chat messages available." + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ], + "x-oaiMeta": { + "name": "The chat completion message list object", + "group": "chat", + "example": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0\",\n \"role\": \"user\",\n \"content\": \"write a haiku about ai\",\n \"name\": null,\n \"content_parts\": null\n }\n ],\n \"first_id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0\",\n \"last_id\": \"chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0\",\n \"has_more\": false\n}\n" + } + }, + "ChatCompletionMessageToolCall": { + "type": "object", + "title": "Function tool call", + "description": "A call to a function tool created by the model.\n", + "properties": { + "id": { + "type": "string", + "description": "The ID of the tool call." + }, + "type": { + "type": "string", + "enum": [ + "function" + ], + "description": "The type of the tool. Currently, only `function` is supported.", + "x-stainless-const": true + }, + "function": { + "type": "object", + "description": "The function that the model called.", + "properties": { + "name": { + "type": "string", + "description": "The name of the function to call." + }, + "arguments": { + "type": "string", + "description": "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + } + }, + "required": [ + "name", + "arguments" + ] + } + }, + "required": [ + "id", + "type", + "function" + ] + }, + "ChatCompletionMessageToolCallChunk": { + "type": "object", + "properties": { + "index": { + "type": "integer" + }, + "id": { + "type": "string", + "description": "The ID of the tool call." + }, + "type": { + "type": "string", + "enum": [ + "function" + ], + "description": "The type of the tool. Currently, only `function` is supported.", + "x-stainless-const": true + }, + "function": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the function to call." + }, + "arguments": { + "type": "string", + "description": "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + } + } + } + }, + "required": [ + "index" + ] + }, + "ChatCompletionMessageToolCalls": { + "type": "array", + "description": "The tool calls generated by the model, such as function calls.", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionMessageToolCall" + }, + { + "$ref": "#/components/schemas/ChatCompletionMessageCustomToolCall" + } + ], + "x-stainless-naming": { + "python": { + "model_name": "chat_completion_message_tool_call_union", + "param_model_name": "chat_completion_message_tool_call_union_param" + } + }, + "discriminator": { + "propertyName": "type" + }, + "x-stainless-go-variant-constructor": "skip" + } + }, + "ChatCompletionModalities": { + "type": "array", + "nullable": true, + "description": "Output types that you would like the model to generate for this request.\nMost models are capable of generating text, which is the default:\n\n`[\"text\"]`\n\nThe `gpt-4o-audio-preview` model can also be used to [generate audio](https://platform.openai.com/docs/guides/audio). To\nrequest that this model generate both text and audio responses, you can\nuse:\n\n`[\"text\", \"audio\"]`\n", + "items": { + "type": "string", + "enum": [ + "text", + "audio" + ] + } + }, + "ChatCompletionNamedToolChoice": { + "type": "object", + "title": "Function tool choice", + "description": "Specifies a tool the model should use. Use to force the model to call a specific function.", + "properties": { + "type": { + "type": "string", + "enum": [ + "function" + ], + "description": "For function calling, the type is always `function`.", + "x-stainless-const": true + }, + "function": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the function to call." + } + }, + "required": [ + "name" + ] + } + }, + "required": [ + "type", + "function" + ] + }, + "ChatCompletionNamedToolChoiceCustom": { + "type": "object", + "title": "Custom tool choice", + "description": "Specifies a tool the model should use. Use to force the model to call a specific custom tool.", + "properties": { + "type": { + "type": "string", + "enum": [ + "custom" + ], + "description": "For custom tool calling, the type is always `custom`.", + "x-stainless-const": true + }, + "custom": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the custom tool to call." + } + }, + "required": [ + "name" + ] + } + }, + "required": [ + "type", + "custom" + ] + }, + "ChatCompletionRequestAssistantMessage": { + "type": "object", + "title": "Assistant message", + "description": "Messages sent by the model in response to user messages.\n", + "properties": { + "content": { + "nullable": true, + "description": "The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified.\n", + "anyOf": [ + { + "type": "string", + "description": "The contents of the assistant message.", + "title": "Text content" + }, + { + "type": "array", + "description": "An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`.", + "title": "Array of content parts", + "items": { + "$ref": "#/components/schemas/ChatCompletionRequestAssistantMessageContentPart" + }, + "minItems": 1 + } + ] + }, + "refusal": { + "nullable": true, + "type": "string", + "description": "The refusal message by the assistant." + }, + "role": { + "type": "string", + "enum": [ + "assistant" + ], + "description": "The role of the messages author, in this case `assistant`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "An optional name for the participant. Provides the model information to differentiate between participants of the same role." + }, + "audio": { + "type": "object", + "nullable": true, + "description": "Data about a previous audio response from the model. \n[Learn more](https://platform.openai.com/docs/guides/audio).\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for a previous audio response from the model.\n" + } + } + }, + "tool_calls": { + "$ref": "#/components/schemas/ChatCompletionMessageToolCalls" + }, + "function_call": { + "type": "object", + "deprecated": true, + "description": "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.", + "nullable": true, + "properties": { + "arguments": { + "type": "string", + "description": "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + }, + "name": { + "type": "string", + "description": "The name of the function to call." + } + }, + "required": [ + "arguments", + "name" + ] + } + }, + "required": [ + "role" + ], + "x-stainless-soft-required": [ + "content" + ] + }, + "ChatCompletionRequestAssistantMessageContentPart": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartText" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartRefusal" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "ChatCompletionRequestDeveloperMessage": { + "type": "object", + "title": "Developer message", + "description": "Developer-provided instructions that the model should follow, regardless of\nmessages sent by the user. With o1 models and newer, `developer` messages\nreplace the previous `system` messages.\n", + "properties": { + "content": { + "description": "The contents of the developer message.", + "anyOf": [ + { + "type": "string", + "description": "The contents of the developer message.", + "title": "Text content" + }, + { + "type": "array", + "description": "An array of content parts with a defined type. For developer messages, only type `text` is supported.", + "title": "Array of content parts", + "items": { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartText" + }, + "minItems": 1 + } + ] + }, + "role": { + "type": "string", + "enum": [ + "developer" + ], + "description": "The role of the messages author, in this case `developer`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "An optional name for the participant. Provides the model information to differentiate between participants of the same role." + } + }, + "required": [ + "content", + "role" + ], + "x-stainless-naming": { + "go": { + "variant_constructor": "DeveloperMessage" + } + } + }, + "ChatCompletionRequestFunctionMessage": { + "type": "object", + "title": "Function message", + "deprecated": true, + "properties": { + "role": { + "type": "string", + "enum": [ + "function" + ], + "description": "The role of the messages author, in this case `function`.", + "x-stainless-const": true + }, + "content": { + "nullable": true, + "type": "string", + "description": "The contents of the function message." + }, + "name": { + "type": "string", + "description": "The name of the function to call." + } + }, + "required": [ + "role", + "content", + "name" + ] + }, + "ChatCompletionRequestMessage": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestDeveloperMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestSystemMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestUserMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestAssistantMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestToolMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestFunctionMessage" + } + ], + "discriminator": { + "propertyName": "role" + } + }, + "ChatCompletionRequestMessageContentPartAudio": { + "type": "object", + "title": "Audio content part", + "description": "Learn about [audio inputs](https://platform.openai.com/docs/guides/audio).\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "input_audio" + ], + "description": "The type of the content part. Always `input_audio`.", + "x-stainless-const": true + }, + "input_audio": { + "type": "object", + "properties": { + "data": { + "type": "string", + "description": "Base64 encoded audio data." + }, + "format": { + "type": "string", + "enum": [ + "wav", + "mp3" + ], + "description": "The format of the encoded audio data. Currently supports \"wav\" and \"mp3\".\n" + } + }, + "required": [ + "data", + "format" + ] + } + }, + "required": [ + "type", + "input_audio" + ], + "x-stainless-naming": { + "go": { + "variant_constructor": "InputAudioContentPart" + } + } + }, + "ChatCompletionRequestMessageContentPartFile": { + "type": "object", + "title": "File content part", + "description": "Learn about [file inputs](https://platform.openai.com/docs/guides/text) for text generation.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "file" + ], + "description": "The type of the content part. Always `file`.", + "x-stainless-const": true + }, + "file": { + "type": "object", + "properties": { + "filename": { + "type": "string", + "description": "The name of the file, used when passing the file to the model as a \nstring.\n" + }, + "file_data": { + "type": "string", + "description": "The base64 encoded file data, used when passing the file to the model \nas a string.\n" + }, + "file_id": { + "type": "string", + "description": "The ID of an uploaded file to use as input.\n" + } + }, + "x-stainless-naming": { + "java": { + "type_name": "FileObject" + }, + "kotlin": { + "type_name": "FileObject" + } + } + } + }, + "required": [ + "type", + "file" + ], + "x-stainless-naming": { + "go": { + "variant_constructor": "FileContentPart" + } + } + }, + "ChatCompletionRequestMessageContentPartImage": { + "type": "object", + "title": "Image content part", + "description": "Learn about [image inputs](https://platform.openai.com/docs/guides/vision).\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "image_url" + ], + "description": "The type of the content part.", + "x-stainless-const": true + }, + "image_url": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "Either a URL of the image or the base64 encoded image data.", + "format": "uri" + }, + "detail": { + "type": "string", + "description": "Specifies the detail level of the image. Learn more in the [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding).", + "enum": [ + "auto", + "low", + "high" + ], + "default": "auto" + } + }, + "required": [ + "url" + ] + } + }, + "required": [ + "type", + "image_url" + ], + "x-stainless-naming": { + "go": { + "variant_constructor": "ImageContentPart" + } + } + }, + "ChatCompletionRequestMessageContentPartRefusal": { + "type": "object", + "title": "Refusal content part", + "properties": { + "type": { + "type": "string", + "enum": [ + "refusal" + ], + "description": "The type of the content part.", + "x-stainless-const": true + }, + "refusal": { + "type": "string", + "description": "The refusal message generated by the model." + } + }, + "required": [ + "type", + "refusal" + ] + }, + "ChatCompletionRequestMessageContentPartText": { + "type": "object", + "title": "Text content part", + "description": "Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation).\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ], + "description": "The type of the content part.", + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text content." + } + }, + "required": [ + "type", + "text" + ], + "x-stainless-naming": { + "go": { + "variant_constructor": "TextContentPart" + } + } + }, + "ChatCompletionRequestSystemMessage": { + "type": "object", + "title": "System message", + "description": "Developer-provided instructions that the model should follow, regardless of\nmessages sent by the user. With o1 models and newer, use `developer` messages\nfor this purpose instead.\n", + "properties": { + "content": { + "description": "The contents of the system message.", + "anyOf": [ + { + "type": "string", + "description": "The contents of the system message.", + "title": "Text content" + }, + { + "type": "array", + "description": "An array of content parts with a defined type. For system messages, only type `text` is supported.", + "title": "Array of content parts", + "items": { + "$ref": "#/components/schemas/ChatCompletionRequestSystemMessageContentPart" + }, + "minItems": 1 + } + ] + }, + "role": { + "type": "string", + "enum": [ + "system" + ], + "description": "The role of the messages author, in this case `system`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "An optional name for the participant. Provides the model information to differentiate between participants of the same role." + } + }, + "required": [ + "content", + "role" + ], + "x-stainless-naming": { + "go": { + "variant_constructor": "SystemMessage" + } + } + }, + "ChatCompletionRequestSystemMessageContentPart": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartText" + } + ] + }, + "ChatCompletionRequestToolMessage": { + "type": "object", + "title": "Tool message", + "properties": { + "role": { + "type": "string", + "enum": [ + "tool" + ], + "description": "The role of the messages author, in this case `tool`.", + "x-stainless-const": true + }, + "content": { + "description": "The contents of the tool message.", + "anyOf": [ + { + "type": "string", + "description": "The contents of the tool message.", + "title": "Text content" + }, + { + "type": "array", + "description": "An array of content parts with a defined type. For tool messages, only type `text` is supported.", + "title": "Array of content parts", + "items": { + "$ref": "#/components/schemas/ChatCompletionRequestToolMessageContentPart" + }, + "minItems": 1 + } + ] + }, + "tool_call_id": { + "type": "string", + "description": "Tool call that this message is responding to." + } + }, + "required": [ + "role", + "content", + "tool_call_id" + ], + "x-stainless-naming": { + "go": { + "variant_constructor": "ToolMessage" + } + } + }, + "ChatCompletionRequestToolMessageContentPart": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartText" + } + ] + }, + "ChatCompletionRequestUserMessage": { + "type": "object", + "title": "User message", + "description": "Messages sent by an end user, containing prompts or additional context\ninformation.\n", + "properties": { + "content": { + "description": "The contents of the user message.\n", + "anyOf": [ + { + "type": "string", + "description": "The text contents of the message.", + "title": "Text content" + }, + { + "type": "array", + "description": "An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text, image, or audio inputs.", + "title": "Array of content parts", + "items": { + "$ref": "#/components/schemas/ChatCompletionRequestUserMessageContentPart" + }, + "minItems": 1 + } + ] + }, + "role": { + "type": "string", + "enum": [ + "user" + ], + "description": "The role of the messages author, in this case `user`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "An optional name for the participant. Provides the model information to differentiate between participants of the same role." + } + }, + "required": [ + "content", + "role" + ], + "x-stainless-naming": { + "go": { + "variant_constructor": "UserMessage" + } + } + }, + "ChatCompletionRequestUserMessageContentPart": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartText" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartImage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartAudio" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartFile" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "ChatCompletionResponseMessage": { + "type": "object", + "description": "A chat completion message generated by the model.", + "properties": { + "content": { + "type": "string", + "description": "The contents of the message.", + "nullable": true + }, + "refusal": { + "type": "string", + "description": "The refusal message generated by the model.", + "nullable": true + }, + "tool_calls": { + "$ref": "#/components/schemas/ChatCompletionMessageToolCalls" + }, + "annotations": { + "type": "array", + "description": "Annotations for the message, when applicable, as when using the\n[web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n", + "items": { + "type": "object", + "description": "A URL citation when using web search.\n", + "required": [ + "type", + "url_citation" + ], + "properties": { + "type": { + "type": "string", + "description": "The type of the URL citation. Always `url_citation`.", + "enum": [ + "url_citation" + ], + "x-stainless-const": true + }, + "url_citation": { + "type": "object", + "description": "A URL citation when using web search.", + "required": [ + "end_index", + "start_index", + "url", + "title" + ], + "properties": { + "end_index": { + "type": "integer", + "description": "The index of the last character of the URL citation in the message." + }, + "start_index": { + "type": "integer", + "description": "The index of the first character of the URL citation in the message." + }, + "url": { + "type": "string", + "description": "The URL of the web resource." + }, + "title": { + "type": "string", + "description": "The title of the web resource." + } + } + } + } + } + }, + "role": { + "type": "string", + "enum": [ + "assistant" + ], + "description": "The role of the author of this message.", + "x-stainless-const": true + }, + "function_call": { + "type": "object", + "deprecated": true, + "description": "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.", + "properties": { + "arguments": { + "type": "string", + "description": "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + }, + "name": { + "type": "string", + "description": "The name of the function to call." + } + }, + "required": [ + "name", + "arguments" + ] + }, + "audio": { + "type": "object", + "nullable": true, + "description": "If the audio output modality is requested, this object contains data\nabout the audio response from the model. [Learn more](https://platform.openai.com/docs/guides/audio).\n", + "required": [ + "id", + "expires_at", + "data", + "transcript" + ], + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for this audio response." + }, + "expires_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when this audio response will\nno longer be accessible on the server for use in multi-turn\nconversations.\n" + }, + "data": { + "type": "string", + "description": "Base64 encoded audio bytes generated by the model, in the format\nspecified in the request.\n" + }, + "transcript": { + "type": "string", + "description": "Transcript of the audio generated by the model." + } + } + } + }, + "required": [ + "role", + "content", + "refusal" + ] + }, + "ChatCompletionRole": { + "type": "string", + "description": "The role of the author of a message", + "enum": [ + "developer", + "system", + "user", + "assistant", + "tool", + "function" + ] + }, + "ChatCompletionStreamOptions": { + "description": "Options for streaming response. Only set this when you set `stream: true`.\n", + "type": "object", + "nullable": true, + "default": null, + "properties": { + "include_usage": { + "type": "boolean", + "description": "If set, an additional chunk will be streamed before the `data: [DONE]`\nmessage. The `usage` field on this chunk shows the token usage statistics\nfor the entire request, and the `choices` field will always be an empty\narray.\n\nAll other chunks will also include a `usage` field, but with a null\nvalue. **NOTE:** If the stream is interrupted, you may not receive the\nfinal usage chunk which contains the total token usage for the request.\n" + }, + "include_obfuscation": { + "type": "boolean", + "description": "When true, stream obfuscation will be enabled. Stream obfuscation adds\nrandom characters to an `obfuscation` field on streaming delta events to\nnormalize payload sizes as a mitigation to certain side-channel attacks.\nThese obfuscation fields are included by default, but add a small amount\nof overhead to the data stream. You can set `include_obfuscation` to\nfalse to optimize for bandwidth if you trust the network links between\nyour application and the OpenAI API.\n" + } + } + }, + "ChatCompletionStreamResponseDelta": { + "type": "object", + "description": "A chat completion delta generated by streamed model responses.", + "properties": { + "content": { + "type": "string", + "description": "The contents of the chunk message.", + "nullable": true + }, + "function_call": { + "deprecated": true, + "type": "object", + "description": "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.", + "properties": { + "arguments": { + "type": "string", + "description": "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + }, + "name": { + "type": "string", + "description": "The name of the function to call." + } + } + }, + "tool_calls": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ChatCompletionMessageToolCallChunk" + } + }, + "role": { + "type": "string", + "enum": [ + "developer", + "system", + "user", + "assistant", + "tool" + ], + "description": "The role of the author of this message." + }, + "refusal": { + "type": "string", + "description": "The refusal message generated by the model.", + "nullable": true + } + } + }, + "ChatCompletionTokenLogprob": { + "type": "object", + "properties": { + "token": { + "description": "The token.", + "type": "string" + }, + "logprob": { + "description": "The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely.", + "type": "number" + }, + "bytes": { + "description": "A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token.", + "type": "array", + "items": { + "type": "integer" + }, + "nullable": true + }, + "top_logprobs": { + "description": "List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned.", + "type": "array", + "items": { + "type": "object", + "properties": { + "token": { + "description": "The token.", + "type": "string" + }, + "logprob": { + "description": "The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely.", + "type": "number" + }, + "bytes": { + "description": "A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token.", + "type": "array", + "items": { + "type": "integer" + }, + "nullable": true + } + }, + "required": [ + "token", + "logprob", + "bytes" + ] + } + } + }, + "required": [ + "token", + "logprob", + "bytes", + "top_logprobs" + ] + }, + "ChatCompletionTool": { + "type": "object", + "title": "Function tool", + "description": "A function tool that can be used to generate a response.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "function" + ], + "description": "The type of the tool. Currently, only `function` is supported.", + "x-stainless-const": true + }, + "function": { + "$ref": "#/components/schemas/FunctionObject" + } + }, + "required": [ + "type", + "function" + ] + }, + "ChatCompletionToolChoiceOption": { + "description": "Controls which (if any) tool is called by the model.\n`none` means the model will not call any tool and instead generates a message.\n`auto` means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools.\nSpecifying a particular tool via `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.\n\n`none` is the default when no tools are present. `auto` is the default if tools are present.\n", + "anyOf": [ + { + "type": "string", + "title": "Auto", + "description": "`none` means the model will not call any tool and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools.\n", + "enum": [ + "none", + "auto", + "required" + ] + }, + { + "$ref": "#/components/schemas/ChatCompletionAllowedToolsChoice" + }, + { + "$ref": "#/components/schemas/ChatCompletionNamedToolChoice" + }, + { + "$ref": "#/components/schemas/ChatCompletionNamedToolChoiceCustom" + } + ], + "x-stainless-go-variant-constructor": { + "naming": "tool_choice_option_{variant}" + } + }, + "ChunkingStrategyRequestParam": { + "type": "object", + "description": "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty.", + "anyOf": [ + { + "$ref": "#/components/schemas/AutoChunkingStrategyRequestParam" + }, + { + "$ref": "#/components/schemas/StaticChunkingStrategyRequestParam" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "Click": { + "type": "object", + "title": "Click", + "description": "A click action.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "click" + ], + "default": "click", + "description": "Specifies the event type. For a click action, this property is \nalways set to `click`.\n", + "x-stainless-const": true + }, + "button": { + "type": "string", + "enum": [ + "left", + "right", + "wheel", + "back", + "forward" + ], + "description": "Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`.\n" + }, + "x": { + "type": "integer", + "description": "The x-coordinate where the click occurred.\n" + }, + "y": { + "type": "integer", + "description": "The y-coordinate where the click occurred.\n" + } + }, + "required": [ + "type", + "button", + "x", + "y" + ] + }, + "CodeInterpreterFileOutput": { + "type": "object", + "title": "Code interpreter file output", + "description": "The output of a code interpreter tool call that is a file.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "files" + ], + "description": "The type of the code interpreter file output. Always `files`.\n", + "x-stainless-const": true + }, + "files": { + "type": "array", + "items": { + "type": "object", + "properties": { + "mime_type": { + "type": "string", + "description": "The MIME type of the file.\n" + }, + "file_id": { + "type": "string", + "description": "The ID of the file.\n" + } + }, + "required": [ + "mime_type", + "file_id" + ] + } + } + }, + "required": [ + "type", + "files" + ] + }, + "CodeInterpreterOutputImage": { + "type": "object", + "title": "Code interpreter output image", + "description": "The image output from the code interpreter.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "image" + ], + "default": "image", + "x-stainless-const": true, + "description": "The type of the output. Always 'image'." + }, + "url": { + "type": "string", + "description": "The URL of the image output from the code interpreter." + } + }, + "required": [ + "type", + "url" + ] + }, + "CodeInterpreterOutputLogs": { + "type": "object", + "title": "Code interpreter output logs", + "description": "The logs output from the code interpreter.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "logs" + ], + "default": "logs", + "x-stainless-const": true, + "description": "The type of the output. Always 'logs'." + }, + "logs": { + "type": "string", + "description": "The logs output from the code interpreter." + } + }, + "required": [ + "type", + "logs" + ] + }, + "CodeInterpreterTextOutput": { + "type": "object", + "title": "Code interpreter text output", + "description": "The output of a code interpreter tool call that is text.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "logs" + ], + "description": "The type of the code interpreter text output. Always `logs`.\n", + "x-stainless-const": true + }, + "logs": { + "type": "string", + "description": "The logs of the code interpreter tool call.\n" + } + }, + "required": [ + "type", + "logs" + ] + }, + "CodeInterpreterTool": { + "type": "object", + "title": "Code interpreter", + "description": "A tool that runs Python code to help generate a response to a prompt.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "code_interpreter" + ], + "description": "The type of the code interpreter tool. Always `code_interpreter`.\n", + "x-stainless-const": true + }, + "container": { + "description": "The code interpreter container. Can be a container ID or an object that\nspecifies uploaded file IDs to make available to your code.\n", + "anyOf": [ + { + "type": "string", + "description": "The container ID." + }, + { + "$ref": "#/components/schemas/CodeInterpreterToolAuto" + } + ] + } + }, + "required": [ + "type", + "container" + ] + }, + "CodeInterpreterToolAuto": { + "type": "object", + "title": "CodeInterpreterContainerAuto", + "description": "Configuration for a code interpreter container. Optionally specify the IDs\nof the files to run the code on.\n", + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "auto" + ], + "description": "Always `auto`.", + "x-stainless-const": true + }, + "file_ids": { + "type": "array", + "items": { + "type": "string" + }, + "description": "An optional list of uploaded files to make available to your code.\n" + } + } + }, + "CodeInterpreterToolCall": { + "type": "object", + "title": "Code interpreter tool call", + "description": "A tool call to run code.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "code_interpreter_call" + ], + "default": "code_interpreter_call", + "x-stainless-const": true, + "description": "The type of the code interpreter tool call. Always `code_interpreter_call`.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the code interpreter tool call.\n" + }, + "status": { + "type": "string", + "enum": [ + "in_progress", + "completed", + "incomplete", + "interpreting", + "failed" + ], + "description": "The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`.\n" + }, + "container_id": { + "type": "string", + "description": "The ID of the container used to run the code.\n" + }, + "code": { + "type": "string", + "nullable": true, + "description": "The code to run, or null if not available.\n" + }, + "outputs": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/CodeInterpreterOutputLogs" + }, + { + "$ref": "#/components/schemas/CodeInterpreterOutputImage" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "discriminator": { + "propertyName": "type" + }, + "nullable": true, + "description": "The outputs generated by the code interpreter, such as logs or images. \nCan be null if no outputs are available.\n" + } + }, + "required": [ + "type", + "id", + "status", + "container_id", + "code", + "outputs" + ] + }, + "ComparisonFilter": { + "type": "object", + "additionalProperties": false, + "title": "Comparison Filter", + "description": "A filter used to compare a specified attribute key to a given value using a defined comparison operation.\n", + "properties": { + "type": { + "type": "string", + "default": "eq", + "enum": [ + "eq", + "ne", + "gt", + "gte", + "lt", + "lte" + ], + "description": "Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`.\n- `eq`: equals\n- `ne`: not equal\n- `gt`: greater than\n- `gte`: greater than or equal\n- `lt`: less than\n- `lte`: less than or equal\n" + }, + "key": { + "type": "string", + "description": "The key to compare against the value." + }, + "value": { + "description": "The value to compare against the attribute key; supports string, number, or boolean types.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + } + ] + } + }, + "required": [ + "type", + "key", + "value" + ], + "x-oaiMeta": { + "name": "ComparisonFilter" + } + }, + "CompleteUploadRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "part_ids": { + "type": "array", + "description": "The ordered list of Part IDs.\n", + "items": { + "type": "string" + } + }, + "md5": { + "description": "The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect.\n", + "type": "string" + } + }, + "required": [ + "part_ids" + ] + }, + "CompletionUsage": { + "type": "object", + "description": "Usage statistics for the completion request.", + "properties": { + "completion_tokens": { + "type": "integer", + "default": 0, + "description": "Number of tokens in the generated completion." + }, + "prompt_tokens": { + "type": "integer", + "default": 0, + "description": "Number of tokens in the prompt." + }, + "total_tokens": { + "type": "integer", + "default": 0, + "description": "Total number of tokens used in the request (prompt + completion)." + }, + "completion_tokens_details": { + "type": "object", + "description": "Breakdown of tokens used in a completion.", + "properties": { + "accepted_prediction_tokens": { + "type": "integer", + "default": 0, + "description": "When using Predicted Outputs, the number of tokens in the\nprediction that appeared in the completion.\n" + }, + "audio_tokens": { + "type": "integer", + "default": 0, + "description": "Audio input tokens generated by the model." + }, + "reasoning_tokens": { + "type": "integer", + "default": 0, + "description": "Tokens generated by the model for reasoning." + }, + "rejected_prediction_tokens": { + "type": "integer", + "default": 0, + "description": "When using Predicted Outputs, the number of tokens in the\nprediction that did not appear in the completion. However, like\nreasoning tokens, these tokens are still counted in the total\ncompletion tokens for purposes of billing, output, and context window\nlimits.\n" + } + } + }, + "prompt_tokens_details": { + "type": "object", + "description": "Breakdown of tokens used in the prompt.", + "properties": { + "audio_tokens": { + "type": "integer", + "default": 0, + "description": "Audio input tokens present in the prompt." + }, + "cached_tokens": { + "type": "integer", + "default": 0, + "description": "Cached tokens present in the prompt." + } + } + } + }, + "required": [ + "prompt_tokens", + "completion_tokens", + "total_tokens" + ] + }, + "CompoundFilter": { + "$recursiveAnchor": true, + "type": "object", + "additionalProperties": false, + "title": "Compound Filter", + "description": "Combine multiple filters using `and` or `or`.", + "properties": { + "type": { + "type": "string", + "description": "Type of operation: `and` or `or`.", + "enum": [ + "and", + "or" + ] + }, + "filters": { + "type": "array", + "description": "Array of filters to combine. Items can be `ComparisonFilter` or `CompoundFilter`.", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ComparisonFilter" + }, + { + "$recursiveRef": "#" + } + ] + } + } + }, + "required": [ + "type", + "filters" + ], + "x-oaiMeta": { + "name": "CompoundFilter" + } + }, + "ComputerAction": { + "anyOf": [ + { + "$ref": "#/components/schemas/Click" + }, + { + "$ref": "#/components/schemas/DoubleClick" + }, + { + "$ref": "#/components/schemas/Drag" + }, + { + "$ref": "#/components/schemas/KeyPress" + }, + { + "$ref": "#/components/schemas/Move" + }, + { + "$ref": "#/components/schemas/Screenshot" + }, + { + "$ref": "#/components/schemas/Scroll" + }, + { + "$ref": "#/components/schemas/Type" + }, + { + "$ref": "#/components/schemas/Wait" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "ComputerScreenshotImage": { + "type": "object", + "description": "A computer screenshot image used with the computer use tool.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "computer_screenshot" + ], + "default": "computer_screenshot", + "description": "Specifies the event type. For a computer screenshot, this property is \nalways set to `computer_screenshot`.\n", + "x-stainless-const": true + }, + "image_url": { + "type": "string", + "description": "The URL of the screenshot image." + }, + "file_id": { + "type": "string", + "description": "The identifier of an uploaded file that contains the screenshot." + } + }, + "required": [ + "type" + ] + }, + "ComputerToolCall": { + "type": "object", + "title": "Computer tool call", + "description": "A tool call to a computer use tool. See the \n[computer use guide](https://platform.openai.com/docs/guides/tools-computer-use) for more information.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the computer call. Always `computer_call`.", + "enum": [ + "computer_call" + ], + "default": "computer_call" + }, + "id": { + "type": "string", + "description": "The unique ID of the computer call." + }, + "call_id": { + "type": "string", + "description": "An identifier used when responding to the tool call with output.\n" + }, + "action": { + "$ref": "#/components/schemas/ComputerAction" + }, + "pending_safety_checks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ComputerToolCallSafetyCheck" + }, + "description": "The pending safety checks for the computer call.\n" + }, + "status": { + "type": "string", + "description": "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n", + "enum": [ + "in_progress", + "completed", + "incomplete" + ] + } + }, + "required": [ + "type", + "id", + "action", + "call_id", + "pending_safety_checks", + "status" + ] + }, + "ComputerToolCallOutput": { + "type": "object", + "title": "Computer tool call output", + "description": "The output of a computer tool call.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the computer tool call output. Always `computer_call_output`.\n", + "enum": [ + "computer_call_output" + ], + "default": "computer_call_output", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The ID of the computer tool call output.\n" + }, + "call_id": { + "type": "string", + "description": "The ID of the computer tool call that produced the output.\n" + }, + "acknowledged_safety_checks": { + "type": "array", + "description": "The safety checks reported by the API that have been acknowledged by the \ndeveloper.\n", + "items": { + "$ref": "#/components/schemas/ComputerToolCallSafetyCheck" + } + }, + "output": { + "$ref": "#/components/schemas/ComputerScreenshotImage" + }, + "status": { + "type": "string", + "description": "The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n", + "enum": [ + "in_progress", + "completed", + "incomplete" + ] + } + }, + "required": [ + "type", + "call_id", + "output" + ] + }, + "ComputerToolCallOutputResource": { + "allOf": [ + { + "$ref": "#/components/schemas/ComputerToolCallOutput" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the computer call tool output.\n" + } + }, + "required": [ + "id" + ] + } + ] + }, + "ComputerToolCallSafetyCheck": { + "type": "object", + "description": "A pending safety check for the computer call.\n", + "properties": { + "id": { + "type": "string", + "description": "The ID of the pending safety check." + }, + "code": { + "type": "string", + "description": "The type of the pending safety check." + }, + "message": { + "type": "string", + "description": "Details about the pending safety check." + } + }, + "required": [ + "id", + "code", + "message" + ] + }, + "ContainerFileListResource": { + "type": "object", + "properties": { + "object": { + "description": "The type of object returned, must be 'list'.", + "const": "list" + }, + "data": { + "type": "array", + "description": "A list of container files.", + "items": { + "$ref": "#/components/schemas/ContainerFileResource" + } + }, + "first_id": { + "type": "string", + "description": "The ID of the first file in the list." + }, + "last_id": { + "type": "string", + "description": "The ID of the last file in the list." + }, + "has_more": { + "type": "boolean", + "description": "Whether there are more files available." + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ContainerFileResource": { + "type": "object", + "title": "The container file object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the file." + }, + "object": { + "type": "string", + "description": "The type of this object (`container.file`).", + "const": "container.file" + }, + "container_id": { + "type": "string", + "description": "The container this file belongs to." + }, + "created_at": { + "type": "integer", + "description": "Unix timestamp (in seconds) when the file was created." + }, + "bytes": { + "type": "integer", + "description": "Size of the file in bytes." + }, + "path": { + "type": "string", + "description": "Path of the file in the container." + }, + "source": { + "type": "string", + "description": "Source of the file (e.g., `user`, `assistant`)." + } + }, + "required": [ + "id", + "object", + "created_at", + "bytes", + "container_id", + "path", + "source" + ], + "x-oaiMeta": { + "name": "The container file object", + "example": "{\n \"id\": \"cfile_682e0e8a43c88191a7978f477a09bdf5\",\n \"object\": \"container.file\",\n \"created_at\": 1747848842,\n \"bytes\": 880,\n \"container_id\": \"cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04\",\n \"path\": \"/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json\",\n \"source\": \"user\"\n}\n" + } + }, + "ContainerListResource": { + "type": "object", + "properties": { + "object": { + "description": "The type of object returned, must be 'list'.", + "const": "list" + }, + "data": { + "type": "array", + "description": "A list of containers.", + "items": { + "$ref": "#/components/schemas/ContainerResource" + } + }, + "first_id": { + "type": "string", + "description": "The ID of the first container in the list." + }, + "last_id": { + "type": "string", + "description": "The ID of the last container in the list." + }, + "has_more": { + "type": "boolean", + "description": "Whether there are more containers available." + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ContainerResource": { + "type": "object", + "title": "The container object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the container." + }, + "object": { + "type": "string", + "description": "The type of this object." + }, + "name": { + "type": "string", + "description": "Name of the container." + }, + "created_at": { + "type": "integer", + "description": "Unix timestamp (in seconds) when the container was created." + }, + "status": { + "type": "string", + "description": "Status of the container (e.g., active, deleted)." + }, + "expires_after": { + "type": "object", + "description": "The container will expire after this time period.\nThe anchor is the reference point for the expiration.\nThe minutes is the number of minutes after the anchor before the container expires.\n", + "properties": { + "anchor": { + "type": "string", + "description": "The reference point for the expiration.", + "enum": [ + "last_active_at" + ] + }, + "minutes": { + "type": "integer", + "description": "The number of minutes after the anchor before the container expires." + } + } + } + }, + "required": [ + "id", + "object", + "name", + "created_at", + "status", + "id", + "name", + "created_at", + "status" + ], + "x-oaiMeta": { + "name": "The container object", + "example": "{\n \"id\": \"cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863\",\n \"object\": \"container\",\n \"created_at\": 1747844794,\n \"status\": \"running\",\n \"expires_after\": {\n \"anchor\": \"last_active_at\",\n \"minutes\": 20\n },\n \"last_active_at\": 1747844794,\n \"name\": \"My Container\"\n}\n" + } + }, + "Content": { + "description": "Multi-modal input and output contents.\n", + "anyOf": [ + { + "title": "Input content types", + "$ref": "#/components/schemas/InputContent" + }, + { + "title": "Output content types", + "$ref": "#/components/schemas/OutputContent" + } + ] + }, + "Conversation": { + "title": "The conversation object", + "allOf": [ + { + "$ref": "#/components/schemas/ConversationResource" + } + ], + "x-oaiMeta": { + "name": "The conversation object", + "group": "conversations" + } + }, + "ConversationItem": { + "title": "Conversation item", + "description": "A single item within a conversation. The set of possible types are the same as the `output` type of a [Response object](https://platform.openai.com/docs/api-reference/responses/object#responses/object-output).", + "discriminator": { + "propertyName": "type" + }, + "x-oaiMeta": { + "name": "The item object", + "group": "conversations" + }, + "anyOf": [ + { + "$ref": "#/components/schemas/Message" + }, + { + "$ref": "#/components/schemas/FunctionToolCallResource" + }, + { + "$ref": "#/components/schemas/FunctionToolCallOutputResource" + }, + { + "$ref": "#/components/schemas/FileSearchToolCall" + }, + { + "$ref": "#/components/schemas/WebSearchToolCall" + }, + { + "$ref": "#/components/schemas/ImageGenToolCall" + }, + { + "$ref": "#/components/schemas/ComputerToolCall" + }, + { + "$ref": "#/components/schemas/ComputerToolCallOutputResource" + }, + { + "$ref": "#/components/schemas/ReasoningItem" + }, + { + "$ref": "#/components/schemas/CodeInterpreterToolCall" + }, + { + "$ref": "#/components/schemas/LocalShellToolCall" + }, + { + "$ref": "#/components/schemas/LocalShellToolCallOutput" + }, + { + "$ref": "#/components/schemas/MCPListTools" + }, + { + "$ref": "#/components/schemas/MCPApprovalRequest" + }, + { + "$ref": "#/components/schemas/MCPApprovalResponseResource" + }, + { + "$ref": "#/components/schemas/MCPToolCall" + }, + { + "$ref": "#/components/schemas/CustomToolCall" + }, + { + "$ref": "#/components/schemas/CustomToolCallOutput" + } + ] + }, + "ConversationItemList": { + "type": "object", + "title": "The conversation item list", + "description": "A list of Conversation items.", + "properties": { + "object": { + "description": "The type of object returned, must be `list`.", + "x-stainless-const": true, + "const": "list" + }, + "data": { + "type": "array", + "description": "A list of conversation items.", + "items": { + "$ref": "#/components/schemas/ConversationItem" + } + }, + "has_more": { + "type": "boolean", + "description": "Whether there are more items available." + }, + "first_id": { + "type": "string", + "description": "The ID of the first item in the list." + }, + "last_id": { + "type": "string", + "description": "The ID of the last item in the list." + } + }, + "required": [ + "object", + "data", + "has_more", + "first_id", + "last_id" + ], + "x-oaiMeta": { + "name": "The item list", + "group": "conversations" + } + }, + "Coordinate": { + "type": "object", + "title": "Coordinate", + "description": "An x/y coordinate pair, e.g. `{ x: 100, y: 200 }`.\n", + "properties": { + "x": { + "type": "integer", + "description": "The x-coordinate.\n" + }, + "y": { + "type": "integer", + "description": "The y-coordinate.\n" + } + }, + "required": [ + "x", + "y" + ] + }, + "CostsResult": { + "type": "object", + "description": "The aggregated costs details of the specific time bucket.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.costs.result" + ], + "x-stainless-const": true + }, + "amount": { + "type": "object", + "description": "The monetary value in its associated currency.", + "properties": { + "value": { + "type": "number", + "description": "The numeric value of the cost." + }, + "currency": { + "type": "string", + "description": "Lowercase ISO-4217 currency e.g. \"usd\"" + } + } + }, + "line_item": { + "type": "string", + "nullable": true, + "description": "When `group_by=line_item`, this field provides the line item of the grouped costs result." + }, + "project_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=project_id`, this field provides the project ID of the grouped costs result." + } + }, + "required": [ + "object" + ], + "x-oaiMeta": { + "name": "Costs object", + "example": "{\n \"object\": \"organization.costs.result\",\n \"amount\": {\n \"value\": 0.06,\n \"currency\": \"usd\"\n },\n \"line_item\": \"Image models\",\n \"project_id\": \"proj_abc\"\n}\n" + } + }, + "CreateAssistantRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "model": { + "description": "ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n", + "example": "gpt-4o", + "anyOf": [ + { + "type": "string" + }, + { + "$ref": "#/components/schemas/AssistantSupportedModels" + } + ], + "x-oaiTypeLabel": "string" + }, + "name": { + "description": "The name of the assistant. The maximum length is 256 characters.\n", + "type": "string", + "nullable": true, + "maxLength": 256 + }, + "description": { + "description": "The description of the assistant. The maximum length is 512 characters.\n", + "type": "string", + "nullable": true, + "maxLength": 512 + }, + "instructions": { + "description": "The system instructions that the assistant uses. The maximum length is 256,000 characters.\n", + "type": "string", + "nullable": true, + "maxLength": 256000 + }, + "reasoning_effort": { + "$ref": "#/components/schemas/ReasoningEffort" + }, + "tools": { + "description": "A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n", + "default": [], + "type": "array", + "maxItems": 128, + "items": { + "$ref": "#/components/schemas/AssistantTool" + } + }, + "tool_resources": { + "type": "object", + "description": "A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n", + "properties": { + "code_interpreter": { + "type": "object", + "properties": { + "file_ids": { + "type": "array", + "description": "A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + "default": [], + "maxItems": 20, + "items": { + "type": "string" + } + } + } + }, + "file_search": { + "type": "object", + "properties": { + "vector_store_ids": { + "type": "array", + "description": "The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + "maxItems": 1, + "items": { + "type": "string" + } + }, + "vector_stores": { + "type": "array", + "description": "A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + "maxItems": 1, + "items": { + "type": "object", + "properties": { + "file_ids": { + "type": "array", + "description": "A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n", + "maxItems": 10000, + "items": { + "type": "string" + } + }, + "chunking_strategy": { + "type": "object", + "description": "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.", + "anyOf": [ + { + "type": "object", + "title": "Auto Chunking Strategy", + "description": "The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`.", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "Always `auto`.", + "enum": [ + "auto" + ], + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + { + "type": "object", + "title": "Static Chunking Strategy", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "Always `static`.", + "enum": [ + "static" + ], + "x-stainless-const": true + }, + "static": { + "type": "object", + "additionalProperties": false, + "properties": { + "max_chunk_size_tokens": { + "type": "integer", + "minimum": 100, + "maximum": 4096, + "description": "The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`." + }, + "chunk_overlap_tokens": { + "type": "integer", + "description": "The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" + } + }, + "required": [ + "max_chunk_size_tokens", + "chunk_overlap_tokens" + ] + } + }, + "required": [ + "type", + "static" + ], + "x-stainless-naming": { + "java": { + "type_name": "StaticObject" + }, + "kotlin": { + "type_name": "StaticObject" + } + } + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + } + } + }, + "anyOf": [ + { + "required": [ + "vector_store_ids" + ] + }, + { + "required": [ + "vector_stores" + ] + } + ] + } + }, + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "temperature": { + "description": "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 1, + "example": 1, + "nullable": true + }, + "top_p": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 1, + "example": 1, + "nullable": true, + "description": "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }, + "response_format": { + "$ref": "#/components/schemas/AssistantsApiResponseFormatOption", + "nullable": true + } + }, + "required": [ + "model" + ] + }, + "CreateChatCompletionRequest": { + "allOf": [ + { + "$ref": "#/components/schemas/CreateModelResponseProperties" + }, + { + "type": "object", + "properties": { + "messages": { + "description": "A list of messages comprising the conversation so far. Depending on the\n[model](https://platform.openai.com/docs/models) you use, different message types (modalities) are\nsupported, like [text](https://platform.openai.com/docs/guides/text-generation),\n[images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio).\n", + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/components/schemas/ChatCompletionRequestMessage" + } + }, + "model": { + "description": "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models)\nto browse and compare available models.\n", + "$ref": "#/components/schemas/ModelIdsShared" + }, + "modalities": { + "$ref": "#/components/schemas/ResponseModalities" + }, + "verbosity": { + "$ref": "#/components/schemas/Verbosity" + }, + "reasoning_effort": { + "$ref": "#/components/schemas/ReasoningEffort" + }, + "max_completion_tokens": { + "description": "An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).\n", + "type": "integer", + "nullable": true + }, + "frequency_penalty": { + "type": "number", + "default": 0, + "minimum": -2, + "maximum": 2, + "nullable": true, + "description": "Number between -2.0 and 2.0. Positive values penalize new tokens based on\ntheir existing frequency in the text so far, decreasing the model's\nlikelihood to repeat the same line verbatim.\n" + }, + "presence_penalty": { + "type": "number", + "default": 0, + "minimum": -2, + "maximum": 2, + "nullable": true, + "description": "Number between -2.0 and 2.0. Positive values penalize new tokens based on\nwhether they appear in the text so far, increasing the model's likelihood\nto talk about new topics.\n" + }, + "web_search_options": { + "type": "object", + "title": "Web search", + "description": "This tool searches the web for relevant results to use in a response.\nLearn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n", + "properties": { + "user_location": { + "type": "object", + "nullable": true, + "required": [ + "type", + "approximate" + ], + "description": "Approximate location parameters for the search.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of location approximation. Always `approximate`.\n", + "enum": [ + "approximate" + ], + "x-stainless-const": true + }, + "approximate": { + "$ref": "#/components/schemas/WebSearchLocation" + } + } + }, + "search_context_size": { + "$ref": "#/components/schemas/WebSearchContextSize" + } + } + }, + "top_logprobs": { + "description": "An integer between 0 and 20 specifying the number of most likely tokens to\nreturn at each token position, each with an associated log probability.\n`logprobs` must be set to `true` if this parameter is used.\n", + "type": "integer", + "minimum": 0, + "maximum": 20, + "nullable": true + }, + "response_format": { + "description": "An object specifying the format that the model must output.\n\nSetting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables\nStructured Outputs which ensures the model will match your supplied JSON\nschema. Learn more in the [Structured Outputs\nguide](https://platform.openai.com/docs/guides/structured-outputs).\n\nSetting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n", + "anyOf": [ + { + "$ref": "#/components/schemas/ResponseFormatText" + }, + { + "$ref": "#/components/schemas/ResponseFormatJsonSchema" + }, + { + "$ref": "#/components/schemas/ResponseFormatJsonObject" + } + ] + }, + "audio": { + "type": "object", + "nullable": true, + "description": "Parameters for audio output. Required when audio output is requested with\n`modalities: [\"audio\"]`. [Learn more](https://platform.openai.com/docs/guides/audio).\n", + "required": [ + "voice", + "format" + ], + "properties": { + "voice": { + "$ref": "#/components/schemas/VoiceIdsShared", + "description": "The voice the model uses to respond. Supported voices are\n`alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`.\n" + }, + "format": { + "type": "string", + "enum": [ + "wav", + "aac", + "mp3", + "flac", + "opus", + "pcm16" + ], + "description": "Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`,\n`opus`, or `pcm16`.\n" + } + } + }, + "store": { + "type": "boolean", + "default": false, + "nullable": true, + "description": "Whether or not to store the output of this chat completion request for\nuse in our [model distillation](https://platform.openai.com/docs/guides/distillation) or\n[evals](https://platform.openai.com/docs/guides/evals) products.\n\nSupports text and image inputs. Note: image inputs over 8MB will be dropped.\n" + }, + "stream": { + "description": "If set to true, the model response data will be streamed to the client\nas it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\nSee the [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming)\nfor more information, along with the [streaming responses](https://platform.openai.com/docs/guides/streaming-responses)\nguide for more information on how to handle the streaming events.\n", + "type": "boolean", + "nullable": true, + "default": false + }, + "stop": { + "$ref": "#/components/schemas/StopConfiguration" + }, + "logit_bias": { + "type": "object", + "x-oaiTypeLabel": "map", + "default": null, + "nullable": true, + "additionalProperties": { + "type": "integer" + }, + "description": "Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the\ntokenizer) to an associated bias value from -100 to 100. Mathematically,\nthe bias is added to the logits generated by the model prior to sampling.\nThe exact effect will vary per model, but values between -1 and 1 should\ndecrease or increase likelihood of selection; values like -100 or 100\nshould result in a ban or exclusive selection of the relevant token.\n" + }, + "logprobs": { + "description": "Whether to return log probabilities of the output tokens or not. If true,\nreturns the log probabilities of each output token returned in the\n`content` of `message`.\n", + "type": "boolean", + "default": false, + "nullable": true + }, + "max_tokens": { + "description": "The maximum number of [tokens](/tokenizer) that can be generated in the\nchat completion. This value can be used to control\n[costs](https://openai.com/api/pricing/) for text generated via API.\n\nThis value is now deprecated in favor of `max_completion_tokens`, and is\nnot compatible with [o-series models](https://platform.openai.com/docs/guides/reasoning).\n", + "type": "integer", + "nullable": true, + "deprecated": true + }, + "n": { + "type": "integer", + "minimum": 1, + "maximum": 128, + "default": 1, + "example": 1, + "nullable": true, + "description": "How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs." + }, + "prediction": { + "nullable": true, + "description": "Configuration for a [Predicted Output](https://platform.openai.com/docs/guides/predicted-outputs),\nwhich can greatly improve response times when large parts of the model\nresponse are known ahead of time. This is most common when you are\nregenerating a file with only minor changes to most of the content.\n", + "anyOf": [ + { + "$ref": "#/components/schemas/PredictionContent" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "seed": { + "type": "integer", + "minimum": -9223372036854776000, + "maximum": 9223372036854776000, + "nullable": true, + "deprecated": true, + "description": "This feature is in Beta.\nIf specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n", + "x-oaiMeta": { + "beta": true + } + }, + "stream_options": { + "$ref": "#/components/schemas/ChatCompletionStreamOptions" + }, + "tools": { + "type": "array", + "description": "A list of tools the model may call. You can provide either\n[custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) or\n[function tools](https://platform.openai.com/docs/guides/function-calling).\n", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionTool" + }, + { + "$ref": "#/components/schemas/CustomToolChatCompletions" + } + ], + "x-stainless-naming": { + "python": { + "model_name": "chat_completion_tool_union", + "param_model_name": "chat_completion_tool_union_param" + } + }, + "discriminator": { + "propertyName": "type" + }, + "x-stainless-go-variant-constructor": { + "naming": "chat_completion_{variant}_tool" + } + } + }, + "tool_choice": { + "$ref": "#/components/schemas/ChatCompletionToolChoiceOption" + }, + "parallel_tool_calls": { + "$ref": "#/components/schemas/ParallelToolCalls" + }, + "function_call": { + "deprecated": true, + "description": "Deprecated in favor of `tool_choice`.\n\nControls which (if any) function is called by the model.\n\n`none` means the model will not call a function and instead generates a\nmessage.\n\n`auto` means the model can pick between generating a message or calling a\nfunction.\n\nSpecifying a particular function via `{\"name\": \"my_function\"}` forces the\nmodel to call that function.\n\n`none` is the default when no functions are present. `auto` is the default\nif functions are present.\n", + "anyOf": [ + { + "type": "string", + "description": "`none` means the model will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function.\n", + "enum": [ + "none", + "auto" + ], + "title": "function call mode" + }, + { + "$ref": "#/components/schemas/ChatCompletionFunctionCallOption" + } + ] + }, + "functions": { + "deprecated": true, + "description": "Deprecated in favor of `tools`.\n\nA list of functions the model may generate JSON inputs for.\n", + "type": "array", + "minItems": 1, + "maxItems": 128, + "items": { + "$ref": "#/components/schemas/ChatCompletionFunctions" + } + } + }, + "required": [ + "model", + "messages" + ] + } + ] + }, + "CreateChatCompletionResponse": { + "type": "object", + "description": "Represents a chat completion response returned by model, based on the provided input.", + "properties": { + "id": { + "type": "string", + "description": "A unique identifier for the chat completion." + }, + "choices": { + "type": "array", + "description": "A list of chat completion choices. Can be more than one if `n` is greater than 1.", + "items": { + "type": "object", + "required": [ + "finish_reason", + "index", + "message", + "logprobs" + ], + "properties": { + "finish_reason": { + "type": "string", + "description": "The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n", + "enum": [ + "stop", + "length", + "tool_calls", + "content_filter", + "function_call" + ] + }, + "index": { + "type": "integer", + "description": "The index of the choice in the list of choices." + }, + "message": { + "$ref": "#/components/schemas/ChatCompletionResponseMessage" + }, + "logprobs": { + "description": "Log probability information for the choice.", + "type": "object", + "nullable": true, + "properties": { + "content": { + "description": "A list of message content tokens with log probability information.", + "type": "array", + "items": { + "$ref": "#/components/schemas/ChatCompletionTokenLogprob" + }, + "nullable": true + }, + "refusal": { + "description": "A list of message refusal tokens with log probability information.", + "type": "array", + "items": { + "$ref": "#/components/schemas/ChatCompletionTokenLogprob" + }, + "nullable": true + } + }, + "required": [ + "content", + "refusal" + ] + } + } + } + }, + "created": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the chat completion was created." + }, + "model": { + "type": "string", + "description": "The model used for the chat completion." + }, + "service_tier": { + "$ref": "#/components/schemas/ServiceTier" + }, + "system_fingerprint": { + "type": "string", + "deprecated": true, + "description": "This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" + }, + "object": { + "type": "string", + "description": "The object type, which is always `chat.completion`.", + "enum": [ + "chat.completion" + ], + "x-stainless-const": true + }, + "usage": { + "$ref": "#/components/schemas/CompletionUsage" + } + }, + "required": [ + "choices", + "created", + "id", + "model", + "object" + ], + "x-oaiMeta": { + "name": "The chat completion object", + "group": "chat", + "example": "{\n \"id\": \"chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG\",\n \"object\": \"chat.completion\",\n \"created\": 1741570283,\n \"model\": \"gpt-4o-2024-08-06\",\n \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\": \"assistant\",\n \"content\": \"The image shows a wooden boardwalk path running through a lush green field or meadow. The sky is bright blue with some scattered clouds, giving the scene a serene and peaceful atmosphere. Trees and shrubs are visible in the background.\",\n \"refusal\": null,\n \"annotations\": []\n },\n \"logprobs\": null,\n \"finish_reason\": \"stop\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 1117,\n \"completion_tokens\": 46,\n \"total_tokens\": 1163,\n \"prompt_tokens_details\": {\n \"cached_tokens\": 0,\n \"audio_tokens\": 0\n },\n \"completion_tokens_details\": {\n \"reasoning_tokens\": 0,\n \"audio_tokens\": 0,\n \"accepted_prediction_tokens\": 0,\n \"rejected_prediction_tokens\": 0\n }\n },\n \"service_tier\": \"default\",\n \"system_fingerprint\": \"fp_fc9f1d7035\"\n}\n" + } + }, + "CreateChatCompletionStreamResponse": { + "type": "object", + "description": "Represents a streamed chunk of a chat completion response returned\nby the model, based on the provided input. \n[Learn more](https://platform.openai.com/docs/guides/streaming-responses).\n", + "properties": { + "id": { + "type": "string", + "description": "A unique identifier for the chat completion. Each chunk has the same ID." + }, + "choices": { + "type": "array", + "description": "A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the\nlast chunk if you set `stream_options: {\"include_usage\": true}`.\n", + "items": { + "type": "object", + "required": [ + "delta", + "finish_reason", + "index" + ], + "properties": { + "delta": { + "$ref": "#/components/schemas/ChatCompletionStreamResponseDelta" + }, + "logprobs": { + "description": "Log probability information for the choice.", + "type": "object", + "nullable": true, + "properties": { + "content": { + "description": "A list of message content tokens with log probability information.", + "type": "array", + "items": { + "$ref": "#/components/schemas/ChatCompletionTokenLogprob" + }, + "nullable": true + }, + "refusal": { + "description": "A list of message refusal tokens with log probability information.", + "type": "array", + "items": { + "$ref": "#/components/schemas/ChatCompletionTokenLogprob" + }, + "nullable": true + } + }, + "required": [ + "content", + "refusal" + ] + }, + "finish_reason": { + "type": "string", + "description": "The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n", + "enum": [ + "stop", + "length", + "tool_calls", + "content_filter", + "function_call" + ], + "nullable": true + }, + "index": { + "type": "integer", + "description": "The index of the choice in the list of choices." + } + } + } + }, + "created": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp." + }, + "model": { + "type": "string", + "description": "The model to generate the completion." + }, + "service_tier": { + "$ref": "#/components/schemas/ServiceTier" + }, + "system_fingerprint": { + "type": "string", + "deprecated": true, + "description": "This fingerprint represents the backend configuration that the model runs with.\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" + }, + "object": { + "type": "string", + "description": "The object type, which is always `chat.completion.chunk`.", + "enum": [ + "chat.completion.chunk" + ], + "x-stainless-const": true + }, + "usage": { + "$ref": "#/components/schemas/CompletionUsage", + "nullable": true, + "description": "An optional field that will only be present when you set\n`stream_options: {\"include_usage\": true}` in your request. When present, it\ncontains a null value **except for the last chunk** which contains the\ntoken usage statistics for the entire request.\n\n**NOTE:** If the stream is interrupted or cancelled, you may not\nreceive the final usage chunk which contains the total token usage for\nthe request.\n" + } + }, + "required": [ + "choices", + "created", + "id", + "model", + "object" + ], + "x-oaiMeta": { + "name": "The chat completion chunk object", + "group": "chat", + "example": "{\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1694268190,\"model\":\"gpt-4o-mini\", \"system_fingerprint\": \"fp_44709d6fcb\", \"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"\"},\"logprobs\":null,\"finish_reason\":null}]}\n\n{\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1694268190,\"model\":\"gpt-4o-mini\", \"system_fingerprint\": \"fp_44709d6fcb\", \"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"},\"logprobs\":null,\"finish_reason\":null}]}\n\n....\n\n{\"id\":\"chatcmpl-123\",\"object\":\"chat.completion.chunk\",\"created\":1694268190,\"model\":\"gpt-4o-mini\", \"system_fingerprint\": \"fp_44709d6fcb\", \"choices\":[{\"index\":0,\"delta\":{},\"logprobs\":null,\"finish_reason\":\"stop\"}]}\n" + } + }, + "CreateCompletionRequest": { + "type": "object", + "properties": { + "model": { + "description": "ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "gpt-3.5-turbo-instruct", + "davinci-002", + "babbage-002" + ], + "title": "Preset" + } + ], + "x-oaiTypeLabel": "string" + }, + "prompt": { + "description": "The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n", + "nullable": true, + "anyOf": [ + { + "type": "string", + "default": "", + "example": "This is a test." + }, + { + "type": "array", + "items": { + "type": "string", + "default": "", + "example": "This is a test." + }, + "title": "Array of strings" + }, + { + "type": "array", + "minItems": 1, + "items": { + "type": "integer" + }, + "title": "Array of tokens" + }, + { + "type": "array", + "minItems": 1, + "items": { + "type": "array", + "minItems": 1, + "items": { + "type": "integer" + } + }, + "title": "Array of token arrays" + } + ] + }, + "best_of": { + "type": "integer", + "default": 1, + "minimum": 0, + "maximum": 20, + "nullable": true, + "description": "Generates `best_of` completions server-side and returns the \"best\" (the one with the highest log probability per token). Results cannot be streamed.\n\nWhen used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n" + }, + "echo": { + "type": "boolean", + "default": false, + "nullable": true, + "description": "Echo back the prompt in addition to the completion\n" + }, + "frequency_penalty": { + "type": "number", + "default": 0, + "minimum": -2, + "maximum": 2, + "nullable": true, + "description": "Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.\n\n[See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)\n" + }, + "logit_bias": { + "type": "object", + "x-oaiTypeLabel": "map", + "default": null, + "nullable": true, + "additionalProperties": { + "type": "integer" + }, + "description": "Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.\n\nAs an example, you can pass `{\"50256\": -100}` to prevent the <|endoftext|> token from being generated.\n" + }, + "logprobs": { + "type": "integer", + "minimum": 0, + "maximum": 5, + "default": null, + "nullable": true, + "description": "Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response.\n\nThe maximum value for `logprobs` is 5.\n" + }, + "max_tokens": { + "type": "integer", + "minimum": 0, + "default": 16, + "example": 16, + "nullable": true, + "description": "The maximum number of [tokens](/tokenizer) that can be generated in the completion.\n\nThe token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n" + }, + "n": { + "type": "integer", + "minimum": 1, + "maximum": 128, + "default": 1, + "example": 1, + "nullable": true, + "description": "How many completions to generate for each prompt.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n" + }, + "presence_penalty": { + "type": "number", + "default": 0, + "minimum": -2, + "maximum": 2, + "nullable": true, + "description": "Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.\n\n[See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)\n" + }, + "seed": { + "type": "integer", + "format": "int64", + "nullable": true, + "description": "If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\n\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n" + }, + "stop": { + "$ref": "#/components/schemas/StopConfiguration" + }, + "stream": { + "description": "Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n", + "type": "boolean", + "nullable": true, + "default": false + }, + "stream_options": { + "$ref": "#/components/schemas/ChatCompletionStreamOptions" + }, + "suffix": { + "description": "The suffix that comes after a completion of inserted text.\n\nThis parameter is only supported for `gpt-3.5-turbo-instruct`.\n", + "default": null, + "nullable": true, + "type": "string", + "example": "test." + }, + "temperature": { + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 1, + "example": 1, + "nullable": true, + "description": "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n\nWe generally recommend altering this or `top_p` but not both.\n" + }, + "top_p": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 1, + "example": 1, + "nullable": true, + "description": "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }, + "user": { + "type": "string", + "example": "user-1234", + "description": "A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n" + } + }, + "required": [ + "model", + "prompt" + ] + }, + "CreateCompletionResponse": { + "type": "object", + "description": "Represents a completion response from the API. Note: both the streamed and non-streamed response objects share the same shape (unlike the chat endpoint).\n", + "properties": { + "id": { + "type": "string", + "description": "A unique identifier for the completion." + }, + "choices": { + "type": "array", + "description": "The list of completion choices the model generated for the input prompt.", + "items": { + "type": "object", + "required": [ + "finish_reason", + "index", + "logprobs", + "text" + ], + "properties": { + "finish_reason": { + "type": "string", + "description": "The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\nor `content_filter` if content was omitted due to a flag from our content filters.\n", + "enum": [ + "stop", + "length", + "content_filter" + ] + }, + "index": { + "type": "integer" + }, + "logprobs": { + "type": "object", + "nullable": true, + "properties": { + "text_offset": { + "type": "array", + "items": { + "type": "integer" + } + }, + "token_logprobs": { + "type": "array", + "items": { + "type": "number" + } + }, + "tokens": { + "type": "array", + "items": { + "type": "string" + } + }, + "top_logprobs": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": { + "type": "number" + } + } + } + } + }, + "text": { + "type": "string" + } + } + } + }, + "created": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the completion was created." + }, + "model": { + "type": "string", + "description": "The model used for completion." + }, + "system_fingerprint": { + "type": "string", + "description": "This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" + }, + "object": { + "type": "string", + "description": "The object type, which is always \"text_completion\"", + "enum": [ + "text_completion" + ], + "x-stainless-const": true + }, + "usage": { + "$ref": "#/components/schemas/CompletionUsage" + } + }, + "required": [ + "id", + "object", + "created", + "model", + "choices" + ], + "x-oaiMeta": { + "name": "The completion object", + "legacy": true, + "example": "{\n \"id\": \"cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7\",\n \"object\": \"text_completion\",\n \"created\": 1589478378,\n \"model\": \"gpt-4-turbo\",\n \"choices\": [\n {\n \"text\": \"\\n\\nThis is indeed a test\",\n \"index\": 0,\n \"logprobs\": null,\n \"finish_reason\": \"length\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 5,\n \"completion_tokens\": 7,\n \"total_tokens\": 12\n }\n}\n" + } + }, + "CreateContainerBody": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Name of the container to create." + }, + "file_ids": { + "type": "array", + "description": "IDs of files to copy to the container.", + "items": { + "type": "string" + } + }, + "expires_after": { + "type": "object", + "description": "Container expiration time in seconds relative to the 'anchor' time.", + "properties": { + "anchor": { + "type": "string", + "enum": [ + "last_active_at" + ], + "description": "Time anchor for the expiration time. Currently only 'last_active_at' is supported." + }, + "minutes": { + "type": "integer" + } + }, + "required": [ + "anchor", + "minutes" + ] + } + }, + "required": [ + "name" + ] + }, + "CreateContainerFileBody": { + "type": "object", + "properties": { + "file_id": { + "type": "string", + "description": "Name of the file to create." + }, + "file": { + "description": "The File object (not file name) to be uploaded.\n", + "type": "string", + "format": "binary" + } + }, + "required": [] + }, + "CreateConversationRequest": { + "type": "object", + "description": "Create a conversation", + "properties": { + "metadata": { + "$ref": "#/components/schemas/Metadata", + "description": "Set of 16 key-value pairs that can be attached to an object. Useful for\nstoring additional information about the object in a structured format.\n" + }, + "items": { + "type": "array", + "description": "Initial items to include in the conversation context.\nYou may add up to 20 items at a time.\n", + "items": { + "$ref": "#/components/schemas/InputItem" + }, + "nullable": true, + "maxItems": 20 + } + }, + "required": [] + }, + "CreateEmbeddingRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "input": { + "description": "Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for all embedding models), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. In addition to the per-input token limit, all embedding models enforce a maximum of 300,000 tokens summed across all inputs in a single request.\n", + "example": "The quick brown fox jumped over the lazy dog", + "anyOf": [ + { + "type": "string", + "title": "string", + "description": "The string that will be turned into an embedding.", + "default": "", + "example": "This is a test." + }, + { + "type": "array", + "title": "Array of strings", + "description": "The array of strings that will be turned into an embedding.", + "minItems": 1, + "maxItems": 2048, + "items": { + "type": "string", + "default": "", + "example": "['This is a test.']" + } + }, + { + "type": "array", + "title": "Array of tokens", + "description": "The array of integers that will be turned into an embedding.", + "minItems": 1, + "maxItems": 2048, + "items": { + "type": "integer" + } + }, + { + "type": "array", + "title": "Array of token arrays", + "description": "The array of arrays containing integers that will be turned into an embedding.", + "minItems": 1, + "maxItems": 2048, + "items": { + "type": "array", + "minItems": 1, + "items": { + "type": "integer" + } + } + } + ] + }, + "model": { + "description": "ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n", + "example": "text-embedding-3-small", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "text-embedding-ada-002", + "text-embedding-3-small", + "text-embedding-3-large" + ], + "x-stainless-nominal": false + } + ], + "x-oaiTypeLabel": "string" + }, + "encoding_format": { + "description": "The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/).", + "example": "float", + "default": "float", + "type": "string", + "enum": [ + "float", + "base64" + ] + }, + "dimensions": { + "description": "The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models.\n", + "type": "integer", + "minimum": 1 + }, + "user": { + "type": "string", + "example": "user-1234", + "description": "A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n" + } + }, + "required": [ + "model", + "input" + ] + }, + "CreateEmbeddingResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "description": "The list of embeddings generated by the model.", + "items": { + "$ref": "#/components/schemas/Embedding" + } + }, + "model": { + "type": "string", + "description": "The name of the model used to generate the embedding." + }, + "object": { + "type": "string", + "description": "The object type, which is always \"list\".", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "usage": { + "type": "object", + "description": "The usage information for the request.", + "properties": { + "prompt_tokens": { + "type": "integer", + "description": "The number of tokens used by the prompt." + }, + "total_tokens": { + "type": "integer", + "description": "The total number of tokens used by the request." + } + }, + "required": [ + "prompt_tokens", + "total_tokens" + ] + } + }, + "required": [ + "object", + "model", + "data", + "usage" + ] + }, + "CreateEvalCompletionsRunDataSource": { + "type": "object", + "title": "CompletionsRunDataSource", + "description": "A CompletionsRunDataSource object describing a model sampling configuration.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "completions" + ], + "default": "completions", + "description": "The type of run data source. Always `completions`." + }, + "input_messages": { + "description": "Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace.", + "anyOf": [ + { + "type": "object", + "title": "TemplateInputMessages", + "properties": { + "type": { + "type": "string", + "enum": [ + "template" + ], + "description": "The type of input messages. Always `template`." + }, + "template": { + "type": "array", + "description": "A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/EasyInputMessage" + }, + { + "$ref": "#/components/schemas/EvalItem" + } + ] + } + } + }, + "required": [ + "type", + "template" + ] + }, + { + "type": "object", + "title": "ItemReferenceInputMessages", + "properties": { + "type": { + "type": "string", + "enum": [ + "item_reference" + ], + "description": "The type of input messages. Always `item_reference`." + }, + "item_reference": { + "type": "string", + "description": "A reference to a variable in the `item` namespace. Ie, \"item.input_trajectory\"" + } + }, + "required": [ + "type", + "item_reference" + ] + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "sampling_params": { + "type": "object", + "properties": { + "temperature": { + "type": "number", + "description": "A higher temperature increases randomness in the outputs.", + "default": 1 + }, + "max_completion_tokens": { + "type": "integer", + "description": "The maximum number of tokens in the generated output." + }, + "top_p": { + "type": "number", + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens.", + "default": 1 + }, + "seed": { + "type": "integer", + "description": "A seed value to initialize the randomness, during sampling.", + "default": 42 + }, + "response_format": { + "description": "An object specifying the format that the model must output.\n\nSetting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables\nStructured Outputs which ensures the model will match your supplied JSON\nschema. Learn more in the [Structured Outputs\nguide](https://platform.openai.com/docs/guides/structured-outputs).\n\nSetting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n", + "anyOf": [ + { + "$ref": "#/components/schemas/ResponseFormatText" + }, + { + "$ref": "#/components/schemas/ResponseFormatJsonSchema" + }, + { + "$ref": "#/components/schemas/ResponseFormatJsonObject" + } + ] + }, + "tools": { + "type": "array", + "description": "A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.\n", + "items": { + "$ref": "#/components/schemas/ChatCompletionTool" + } + } + } + }, + "model": { + "type": "string", + "description": "The name of the model to use for generating completions (e.g. \"o3-mini\")." + }, + "source": { + "description": "Determines what populates the `item` namespace in this run's data source.", + "anyOf": [ + { + "$ref": "#/components/schemas/EvalJsonlFileContentSource" + }, + { + "$ref": "#/components/schemas/EvalJsonlFileIdSource" + }, + { + "$ref": "#/components/schemas/EvalStoredCompletionsSource" + } + ], + "discriminator": { + "propertyName": "type" + } + } + }, + "required": [ + "type", + "source" + ], + "x-oaiMeta": { + "name": "The completions data source object used to configure an individual run", + "group": "eval runs", + "example": "{\n \"name\": \"gpt-4o-mini-2024-07-18\",\n \"data_source\": {\n \"type\": \"completions\",\n \"input_messages\": {\n \"type\": \"item_reference\",\n \"item_reference\": \"item.input\"\n },\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"source\": {\n \"type\": \"stored_completions\",\n \"model\": \"gpt-4o-mini-2024-07-18\"\n }\n }\n}\n" + } + }, + "CreateEvalCustomDataSourceConfig": { + "type": "object", + "title": "CustomDataSourceConfig", + "description": "A CustomDataSourceConfig object that defines the schema for the data source used for the evaluation runs.\nThis schema is used to define the shape of the data that will be:\n- Used to define your testing criteria and\n- What data is required when creating a run\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "custom" + ], + "default": "custom", + "description": "The type of data source. Always `custom`.", + "x-stainless-const": true + }, + "item_schema": { + "type": "object", + "description": "The json schema for each row in the data source.", + "additionalProperties": true + }, + "include_sample_schema": { + "type": "boolean", + "default": false, + "description": "Whether the eval should expect you to populate the sample namespace (ie, by generating responses off of your data source)" + } + }, + "required": [ + "item_schema", + "type" + ], + "x-oaiMeta": { + "name": "The eval file data source config object", + "group": "evals", + "example": "{\n \"type\": \"custom\",\n \"item_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"age\": {\"type\": \"integer\"}\n },\n \"required\": [\"name\", \"age\"]\n },\n \"include_sample_schema\": true\n}\n" + } + }, + "CreateEvalItem": { + "title": "CreateEvalItem", + "description": "A chat message that makes up the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.", + "type": "object", + "x-oaiMeta": { + "name": "The chat message object used to configure an individual run" + }, + "anyOf": [ + { + "type": "object", + "title": "SimpleInputMessage", + "properties": { + "role": { + "type": "string", + "description": "The role of the message (e.g. \"system\", \"assistant\", \"user\")." + }, + "content": { + "type": "string", + "description": "The content of the message." + } + }, + "required": [ + "role", + "content" + ] + }, + { + "$ref": "#/components/schemas/EvalItem" + } + ] + }, + "CreateEvalJsonlRunDataSource": { + "type": "object", + "title": "JsonlRunDataSource", + "description": "A JsonlRunDataSource object with that specifies a JSONL file that matches the eval\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "jsonl" + ], + "default": "jsonl", + "description": "The type of data source. Always `jsonl`.", + "x-stainless-const": true + }, + "source": { + "description": "Determines what populates the `item` namespace in the data source.", + "anyOf": [ + { + "$ref": "#/components/schemas/EvalJsonlFileContentSource" + }, + { + "$ref": "#/components/schemas/EvalJsonlFileIdSource" + } + ], + "discriminator": { + "propertyName": "type" + } + } + }, + "required": [ + "type", + "source" + ], + "x-oaiMeta": { + "name": "The file data source object for the eval run configuration", + "group": "evals", + "example": "{\n \"type\": \"jsonl\",\n \"source\": {\n \"type\": \"file_id\",\n \"id\": \"file-9GYS6xbkWgWhmE7VoLUWFg\"\n }\n}\n" + } + }, + "CreateEvalLabelModelGrader": { + "type": "object", + "title": "LabelModelGrader", + "description": "A LabelModelGrader object which uses a model to assign labels to each item\nin the evaluation.\n", + "properties": { + "type": { + "description": "The object type, which is always `label_model`.", + "type": "string", + "enum": [ + "label_model" + ], + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the grader." + }, + "model": { + "type": "string", + "description": "The model to use for the evaluation. Must support structured outputs." + }, + "input": { + "type": "array", + "description": "A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.", + "items": { + "$ref": "#/components/schemas/CreateEvalItem" + } + }, + "labels": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The labels to classify to each item in the evaluation." + }, + "passing_labels": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The labels that indicate a passing result. Must be a subset of labels." + } + }, + "required": [ + "type", + "model", + "input", + "passing_labels", + "labels", + "name" + ], + "x-oaiMeta": { + "name": "The eval label model grader object", + "group": "evals", + "example": "{\n \"type\": \"label_model\",\n \"model\": \"gpt-4o-2024-08-06\",\n \"input\": [\n {\n \"role\": \"system\",\n \"content\": \"Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Statement: {{item.response}}\"\n }\n ],\n \"passing_labels\": [\"positive\"],\n \"labels\": [\"positive\", \"neutral\", \"negative\"],\n \"name\": \"Sentiment label grader\"\n}\n" + } + }, + "CreateEvalLogsDataSourceConfig": { + "type": "object", + "title": "LogsDataSourceConfig", + "description": "A data source config which specifies the metadata property of your logs query.\nThis is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "logs" + ], + "default": "logs", + "description": "The type of data source. Always `logs`.", + "x-stainless-const": true + }, + "metadata": { + "type": "object", + "description": "Metadata filters for the logs data source.", + "additionalProperties": true + } + }, + "required": [ + "type" + ], + "x-oaiMeta": { + "name": "The logs data source object for evals", + "group": "evals", + "example": "{\n \"type\": \"logs\",\n \"metadata\": {\n \"use_case\": \"customer_support_agent\"\n }\n}\n" + } + }, + "CreateEvalRequest": { + "type": "object", + "title": "CreateEvalRequest", + "properties": { + "name": { + "type": "string", + "description": "The name of the evaluation." + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "data_source_config": { + "type": "object", + "description": "The configuration for the data source used for the evaluation runs. Dictates the schema of the data used in the evaluation.", + "anyOf": [ + { + "$ref": "#/components/schemas/CreateEvalCustomDataSourceConfig" + }, + { + "$ref": "#/components/schemas/CreateEvalLogsDataSourceConfig" + }, + { + "$ref": "#/components/schemas/CreateEvalStoredCompletionsDataSourceConfig" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "testing_criteria": { + "type": "array", + "description": "A list of graders for all eval runs in this group. Graders can reference variables in the data source using double curly braces notation, like `{{item.variable_name}}`. To reference the model's output, use the `sample` namespace (ie, `{{sample.output_text}}`).", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/CreateEvalLabelModelGrader" + }, + { + "$ref": "#/components/schemas/EvalGraderStringCheck" + }, + { + "$ref": "#/components/schemas/EvalGraderTextSimilarity" + }, + { + "$ref": "#/components/schemas/EvalGraderPython" + }, + { + "$ref": "#/components/schemas/EvalGraderScoreModel" + } + ], + "discriminator": { + "propertyName": "type" + } + } + } + }, + "required": [ + "data_source_config", + "testing_criteria" + ] + }, + "CreateEvalResponsesRunDataSource": { + "type": "object", + "title": "ResponsesRunDataSource", + "description": "A ResponsesRunDataSource object describing a model sampling configuration.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "responses" + ], + "default": "responses", + "description": "The type of run data source. Always `responses`." + }, + "input_messages": { + "description": "Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace.", + "anyOf": [ + { + "type": "object", + "title": "InputMessagesTemplate", + "properties": { + "type": { + "type": "string", + "enum": [ + "template" + ], + "description": "The type of input messages. Always `template`." + }, + "template": { + "type": "array", + "description": "A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.", + "items": { + "anyOf": [ + { + "type": "object", + "title": "ChatMessage", + "properties": { + "role": { + "type": "string", + "description": "The role of the message (e.g. \"system\", \"assistant\", \"user\")." + }, + "content": { + "type": "string", + "description": "The content of the message." + } + }, + "required": [ + "role", + "content" + ] + }, + { + "$ref": "#/components/schemas/EvalItem" + } + ] + } + } + }, + "required": [ + "type", + "template" + ] + }, + { + "type": "object", + "title": "InputMessagesItemReference", + "properties": { + "type": { + "type": "string", + "enum": [ + "item_reference" + ], + "description": "The type of input messages. Always `item_reference`." + }, + "item_reference": { + "type": "string", + "description": "A reference to a variable in the `item` namespace. Ie, \"item.name\"" + } + }, + "required": [ + "type", + "item_reference" + ] + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "sampling_params": { + "type": "object", + "properties": { + "temperature": { + "type": "number", + "description": "A higher temperature increases randomness in the outputs.", + "default": 1 + }, + "max_completion_tokens": { + "type": "integer", + "description": "The maximum number of tokens in the generated output." + }, + "top_p": { + "type": "number", + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens.", + "default": 1 + }, + "seed": { + "type": "integer", + "description": "A seed value to initialize the randomness, during sampling.", + "default": 42 + }, + "tools": { + "type": "array", + "description": "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nThe two categories of tools you can provide the model are:\n\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search)\n or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about\n [built-in tools](https://platform.openai.com/docs/guides/tools).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code. Learn more about\n [function calling](https://platform.openai.com/docs/guides/function-calling).\n", + "items": { + "$ref": "#/components/schemas/Tool" + } + }, + "text": { + "type": "object", + "description": "Configuration options for a text response from the model. Can be plain\ntext or structured JSON data. Learn more:\n- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n- [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)\n", + "properties": { + "format": { + "$ref": "#/components/schemas/TextResponseFormatConfiguration" + } + } + } + } + }, + "model": { + "type": "string", + "description": "The name of the model to use for generating completions (e.g. \"o3-mini\")." + }, + "source": { + "description": "Determines what populates the `item` namespace in this run's data source.", + "anyOf": [ + { + "$ref": "#/components/schemas/EvalJsonlFileContentSource" + }, + { + "$ref": "#/components/schemas/EvalJsonlFileIdSource" + }, + { + "$ref": "#/components/schemas/EvalResponsesSource" + } + ], + "discriminator": { + "propertyName": "type" + } + } + }, + "required": [ + "type", + "source" + ], + "x-oaiMeta": { + "name": "The completions data source object used to configure an individual run", + "group": "eval runs", + "example": "{\n \"name\": \"gpt-4o-mini-2024-07-18\",\n \"data_source\": {\n \"type\": \"responses\",\n \"input_messages\": {\n \"type\": \"item_reference\",\n \"item_reference\": \"item.input\"\n },\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"source\": {\n \"type\": \"responses\",\n \"model\": \"gpt-4o-mini-2024-07-18\"\n }\n }\n}\n" + } + }, + "CreateEvalRunRequest": { + "type": "object", + "title": "CreateEvalRunRequest", + "properties": { + "name": { + "type": "string", + "description": "The name of the run." + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "data_source": { + "type": "object", + "description": "Details about the run's data source.", + "anyOf": [ + { + "$ref": "#/components/schemas/CreateEvalJsonlRunDataSource" + }, + { + "$ref": "#/components/schemas/CreateEvalCompletionsRunDataSource" + }, + { + "$ref": "#/components/schemas/CreateEvalResponsesRunDataSource" + } + ] + } + }, + "required": [ + "data_source" + ] + }, + "CreateEvalStoredCompletionsDataSourceConfig": { + "type": "object", + "title": "StoredCompletionsDataSourceConfig", + "description": "Deprecated in favor of LogsDataSourceConfig.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "stored_completions" + ], + "default": "stored_completions", + "description": "The type of data source. Always `stored_completions`.", + "x-stainless-const": true + }, + "metadata": { + "type": "object", + "description": "Metadata filters for the stored completions data source.", + "additionalProperties": true + } + }, + "required": [ + "type" + ], + "deprecated": true, + "x-oaiMeta": { + "name": "The stored completions data source object for evals", + "group": "evals", + "example": "{\n \"type\": \"stored_completions\",\n \"metadata\": {\n \"use_case\": \"customer_support_agent\"\n }\n}\n" + } + }, + "CreateFileRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "file": { + "description": "The File object (not file name) to be uploaded.\n", + "type": "string", + "format": "binary", + "x-oaiMeta": { + "exampleFilePath": "fine-tune.jsonl" + } + }, + "purpose": { + "$ref": "#/components/schemas/FilePurpose" + }, + "expires_after": { + "$ref": "#/components/schemas/FileExpirationAfter" + } + }, + "required": [ + "file", + "purpose" + ] + }, + "CreateFineTuningCheckpointPermissionRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "project_ids": { + "type": "array", + "description": "The project identifiers to grant access to.", + "items": { + "type": "string" + } + } + }, + "required": [ + "project_ids" + ] + }, + "CreateFineTuningJobRequest": { + "type": "object", + "properties": { + "model": { + "description": "The name of the model to fine-tune. You can select one of the\n[supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned).\n", + "example": "gpt-4o-mini", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "babbage-002", + "davinci-002", + "gpt-3.5-turbo", + "gpt-4o-mini" + ], + "title": "Preset" + } + ], + "x-oaiTypeLabel": "string" + }, + "training_file": { + "description": "The ID of an uploaded file that contains training data.\n\nSee [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file.\n\nYour dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`.\n\nThe contents of the file should differ depending on if the model uses the [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) format, or if the fine-tuning method uses the [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) format.\n\nSee the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details.\n", + "type": "string", + "example": "file-abc123" + }, + "hyperparameters": { + "type": "object", + "description": "The hyperparameters used for the fine-tuning job.\nThis value is now deprecated in favor of `method`, and should be passed in under the `method` parameter.\n", + "properties": { + "batch_size": { + "description": "Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true, + "title": "Auto" + }, + { + "type": "integer", + "minimum": 1, + "maximum": 256 + } + ] + }, + "learning_rate_multiplier": { + "description": "Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true, + "title": "Auto" + }, + { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + } + ] + }, + "n_epochs": { + "description": "The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true, + "title": "Auto" + }, + { + "type": "integer", + "minimum": 1, + "maximum": 50 + } + ] + } + }, + "deprecated": true + }, + "suffix": { + "description": "A string of up to 64 characters that will be added to your fine-tuned model name.\n\nFor example, a `suffix` of \"custom-model-name\" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`.\n", + "type": "string", + "minLength": 1, + "maxLength": 64, + "default": null, + "nullable": true + }, + "validation_file": { + "description": "The ID of an uploaded file that contains validation data.\n\nIf you provide this file, the data is used to generate validation\nmetrics periodically during fine-tuning. These metrics can be viewed in\nthe fine-tuning results file.\nThe same data should not be present in both train and validation files.\n\nYour dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`.\n\nSee the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details.\n", + "type": "string", + "nullable": true, + "example": "file-abc123" + }, + "integrations": { + "type": "array", + "description": "A list of integrations to enable for your fine-tuning job.", + "nullable": true, + "items": { + "type": "object", + "required": [ + "type", + "wandb" + ], + "properties": { + "type": { + "description": "The type of integration to enable. Currently, only \"wandb\" (Weights and Biases) is supported.\n", + "anyOf": [ + { + "type": "string", + "enum": [ + "wandb" + ], + "x-stainless-const": true + } + ] + }, + "wandb": { + "type": "object", + "description": "The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n", + "required": [ + "project" + ], + "properties": { + "project": { + "description": "The name of the project that the new run will be created under.\n", + "type": "string", + "example": "my-wandb-project" + }, + "name": { + "description": "A display name to set for the run. If not set, we will use the Job ID as the name.\n", + "nullable": true, + "type": "string" + }, + "entity": { + "description": "The entity to use for the run. This allows you to set the team or username of the WandB user that you would\nlike associated with the run. If not set, the default entity for the registered WandB API key is used.\n", + "nullable": true, + "type": "string" + }, + "tags": { + "description": "A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\ndefault tags are generated by OpenAI: \"openai/finetune\", \"openai/{base-model}\", \"openai/{ftjob-abcdef}\".\n", + "type": "array", + "items": { + "type": "string", + "example": "custom-tag" + } + } + } + } + } + } + }, + "seed": { + "description": "The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases.\nIf a seed is not specified, one will be generated for you.\n", + "type": "integer", + "nullable": true, + "minimum": 0, + "maximum": 2147483647, + "example": 42 + }, + "method": { + "$ref": "#/components/schemas/FineTuneMethod" + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + }, + "required": [ + "model", + "training_file" + ] + }, + "CreateImageEditRequest": { + "type": "object", + "properties": { + "image": { + "anyOf": [ + { + "type": "string", + "format": "binary" + }, + { + "type": "array", + "maxItems": 16, + "items": { + "type": "string", + "format": "binary" + } + } + ], + "description": "The image(s) to edit. Must be a supported image file or an array of images.\n\nFor `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less \nthan 50MB. You can provide up to 16 images.\n\nFor `dall-e-2`, you can only provide one image, and it should be a square \n`png` file less than 4MB.\n", + "x-oaiMeta": { + "exampleFilePath": "otter.png" + } + }, + "prompt": { + "description": "A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for `gpt-image-1`.", + "type": "string", + "example": "A cute baby sea otter wearing a beret" + }, + "mask": { + "description": "An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. If there are multiple images provided, the mask will be applied on the first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`.", + "type": "string", + "format": "binary", + "x-oaiMeta": { + "exampleFilePath": "mask.png" + } + }, + "background": { + "type": "string", + "enum": [ + "transparent", + "opaque", + "auto" + ], + "default": "auto", + "example": "transparent", + "nullable": true, + "description": "Allows to set transparency for the background of the generated image(s). \nThis parameter is only supported for `gpt-image-1`. Must be one of \n`transparent`, `opaque` or `auto` (default value). When `auto` is used, the \nmodel will automatically determine the best background for the image.\n\nIf `transparent`, the output format needs to support transparency, so it \nshould be set to either `png` (default value) or `webp`.\n" + }, + "model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "dall-e-2", + "gpt-image-1" + ], + "x-stainless-const": true + } + ], + "x-oaiTypeLabel": "string", + "nullable": true, + "description": "The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used." + }, + "n": { + "type": "integer", + "minimum": 1, + "maximum": 10, + "default": 1, + "example": 1, + "nullable": true, + "description": "The number of images to generate. Must be between 1 and 10." + }, + "size": { + "type": "string", + "enum": [ + "256x256", + "512x512", + "1024x1024", + "1536x1024", + "1024x1536", + "auto" + ], + "default": "1024x1024", + "example": "1024x1024", + "nullable": true, + "description": "The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`." + }, + "response_format": { + "type": "string", + "enum": [ + "url", + "b64_json" + ], + "default": "url", + "example": "url", + "nullable": true, + "description": "The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` will always return base64-encoded images." + }, + "output_format": { + "type": "string", + "enum": [ + "png", + "jpeg", + "webp" + ], + "default": "png", + "example": "png", + "nullable": true, + "description": "The format in which the generated images are returned. This parameter is\nonly supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.\nThe default value is `png`.\n" + }, + "output_compression": { + "type": "integer", + "default": 100, + "example": 100, + "nullable": true, + "description": "The compression level (0-100%) for the generated images. This parameter \nis only supported for `gpt-image-1` with the `webp` or `jpeg` output \nformats, and defaults to 100.\n" + }, + "user": { + "type": "string", + "example": "user-1234", + "description": "A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n" + }, + "input_fidelity": { + "$ref": "#/components/schemas/ImageInputFidelity" + }, + "stream": { + "type": "boolean", + "default": false, + "example": false, + "nullable": true, + "description": "Edit the image in streaming mode. Defaults to `false`. See the\n[Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information.\n" + }, + "partial_images": { + "$ref": "#/components/schemas/PartialImages" + }, + "quality": { + "type": "string", + "enum": [ + "standard", + "low", + "medium", + "high", + "auto" + ], + "default": "auto", + "example": "high", + "nullable": true, + "description": "The quality of the image that will be generated. `high`, `medium` and `low` are only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. Defaults to `auto`.\n" + } + }, + "required": [ + "prompt", + "image" + ] + }, + "CreateImageRequest": { + "type": "object", + "properties": { + "prompt": { + "description": "A text description of the desired image(s). The maximum length is 32000 characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`.", + "type": "string", + "example": "A cute baby sea otter" + }, + "model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "dall-e-2", + "dall-e-3", + "gpt-image-1" + ], + "x-stainless-nominal": false + } + ], + "x-oaiTypeLabel": "string", + "nullable": true, + "description": "The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used." + }, + "n": { + "type": "integer", + "minimum": 1, + "maximum": 10, + "default": 1, + "example": 1, + "nullable": true, + "description": "The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported." + }, + "quality": { + "type": "string", + "enum": [ + "standard", + "hd", + "low", + "medium", + "high", + "auto" + ], + "default": "auto", + "example": "medium", + "nullable": true, + "description": "The quality of the image that will be generated. \n\n- `auto` (default value) will automatically select the best quality for the given model.\n- `high`, `medium` and `low` are supported for `gpt-image-1`.\n- `hd` and `standard` are supported for `dall-e-3`.\n- `standard` is the only option for `dall-e-2`.\n" + }, + "response_format": { + "type": "string", + "enum": [ + "url", + "b64_json" + ], + "default": "url", + "example": "url", + "nullable": true, + "description": "The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for `gpt-image-1` which will always return base64-encoded images." + }, + "output_format": { + "type": "string", + "enum": [ + "png", + "jpeg", + "webp" + ], + "default": "png", + "example": "png", + "nullable": true, + "description": "The format in which the generated images are returned. This parameter is only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`." + }, + "output_compression": { + "type": "integer", + "default": 100, + "example": 100, + "nullable": true, + "description": "The compression level (0-100%) for the generated images. This parameter is only supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and defaults to 100." + }, + "stream": { + "type": "boolean", + "default": false, + "example": false, + "nullable": true, + "description": "Generate the image in streaming mode. Defaults to `false`. See the\n[Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information.\nThis parameter is only supported for `gpt-image-1`.\n" + }, + "partial_images": { + "$ref": "#/components/schemas/PartialImages" + }, + "size": { + "type": "string", + "enum": [ + "auto", + "1024x1024", + "1536x1024", + "1024x1536", + "256x256", + "512x512", + "1792x1024", + "1024x1792" + ], + "default": "auto", + "example": "1024x1024", + "nullable": true, + "description": "The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`." + }, + "moderation": { + "type": "string", + "enum": [ + "low", + "auto" + ], + "default": "auto", + "example": "low", + "nullable": true, + "description": "Control the content-moderation level for images generated by `gpt-image-1`. Must be either `low` for less restrictive filtering or `auto` (default value)." + }, + "background": { + "type": "string", + "enum": [ + "transparent", + "opaque", + "auto" + ], + "default": "auto", + "example": "transparent", + "nullable": true, + "description": "Allows to set transparency for the background of the generated image(s). \nThis parameter is only supported for `gpt-image-1`. Must be one of \n`transparent`, `opaque` or `auto` (default value). When `auto` is used, the \nmodel will automatically determine the best background for the image.\n\nIf `transparent`, the output format needs to support transparency, so it \nshould be set to either `png` (default value) or `webp`.\n" + }, + "style": { + "type": "string", + "enum": [ + "vivid", + "natural" + ], + "default": "vivid", + "example": "vivid", + "nullable": true, + "description": "The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images." + }, + "user": { + "type": "string", + "example": "user-1234", + "description": "A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n" + } + }, + "required": [ + "prompt" + ] + }, + "CreateImageVariationRequest": { + "type": "object", + "properties": { + "image": { + "description": "The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.", + "type": "string", + "format": "binary", + "x-oaiMeta": { + "exampleFilePath": "otter.png" + } + }, + "model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "dall-e-2" + ], + "x-stainless-const": true + } + ], + "x-oaiTypeLabel": "string", + "nullable": true, + "description": "The model to use for image generation. Only `dall-e-2` is supported at this time." + }, + "n": { + "type": "integer", + "minimum": 1, + "maximum": 10, + "default": 1, + "example": 1, + "nullable": true, + "description": "The number of images to generate. Must be between 1 and 10." + }, + "response_format": { + "type": "string", + "enum": [ + "url", + "b64_json" + ], + "default": "url", + "example": "url", + "nullable": true, + "description": "The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated." + }, + "size": { + "type": "string", + "enum": [ + "256x256", + "512x512", + "1024x1024" + ], + "default": "1024x1024", + "example": "1024x1024", + "nullable": true, + "description": "The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`." + }, + "user": { + "type": "string", + "example": "user-1234", + "description": "A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n" + } + }, + "required": [ + "image" + ] + }, + "CreateMessageRequest": { + "type": "object", + "additionalProperties": false, + "required": [ + "role", + "content" + ], + "properties": { + "role": { + "type": "string", + "enum": [ + "user", + "assistant" + ], + "description": "The role of the entity that is creating the message. Allowed values include:\n- `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages.\n- `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation.\n" + }, + "content": { + "anyOf": [ + { + "type": "string", + "description": "The text contents of the message.", + "title": "Text content" + }, + { + "type": "array", + "description": "An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](https://platform.openai.com/docs/models).", + "title": "Array of content parts", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/MessageContentImageFileObject" + }, + { + "$ref": "#/components/schemas/MessageContentImageUrlObject" + }, + { + "$ref": "#/components/schemas/MessageRequestContentTextObject" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "minItems": 1 + } + ] + }, + "attachments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "file_id": { + "type": "string", + "description": "The ID of the file to attach to the message." + }, + "tools": { + "description": "The tools to add this file to.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/AssistantToolsCode" + }, + { + "$ref": "#/components/schemas/AssistantToolsFileSearchTypeOnly" + } + ], + "discriminator": { + "propertyName": "type" + } + } + } + } + }, + "description": "A list of files attached to the message, and the tools they should be added to.", + "required": [ + "file_id", + "tools" + ], + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + }, + "CreateModelResponseProperties": { + "allOf": [ + { + "$ref": "#/components/schemas/ModelResponseProperties" + }, + { + "type": "object", + "properties": { + "top_logprobs": { + "description": "An integer between 0 and 20 specifying the number of most likely tokens to\nreturn at each token position, each with an associated log probability.\n", + "type": "integer", + "minimum": 0, + "maximum": 20 + } + } + } + ] + }, + "CreateModerationRequest": { + "type": "object", + "properties": { + "input": { + "description": "Input (or inputs) to classify. Can be a single string, an array of strings, or\nan array of multi-modal input objects similar to other models.\n", + "anyOf": [ + { + "type": "string", + "description": "A string of text to classify for moderation.", + "default": "", + "example": "I want to kill them." + }, + { + "type": "array", + "description": "An array of strings to classify for moderation.", + "items": { + "type": "string", + "default": "", + "example": "I want to kill them." + } + }, + { + "type": "array", + "description": "An array of multi-modal inputs to the moderation model.", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModerationImageURLInput" + }, + { + "$ref": "#/components/schemas/ModerationTextInput" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "title": "Moderation Multi Modal Array" + } + ] + }, + "model": { + "description": "The content moderation model you would like to use. Learn more in\n[the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about\navailable models [here](https://platform.openai.com/docs/models#moderation).\n", + "nullable": false, + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "omni-moderation-latest", + "omni-moderation-2024-09-26", + "text-moderation-latest", + "text-moderation-stable" + ], + "x-stainless-nominal": false + } + ], + "x-oaiTypeLabel": "string" + } + }, + "required": [ + "input" + ] + }, + "CreateModerationResponse": { + "type": "object", + "description": "Represents if a given text input is potentially harmful.", + "properties": { + "id": { + "type": "string", + "description": "The unique identifier for the moderation request." + }, + "model": { + "type": "string", + "description": "The model used to generate the moderation results." + }, + "results": { + "type": "array", + "description": "A list of moderation objects.", + "items": { + "type": "object", + "properties": { + "flagged": { + "type": "boolean", + "description": "Whether any of the below categories are flagged." + }, + "categories": { + "type": "object", + "description": "A list of the categories, and whether they are flagged or not.", + "properties": { + "hate": { + "type": "boolean", + "description": "Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment." + }, + "hate/threatening": { + "type": "boolean", + "description": "Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste." + }, + "harassment": { + "type": "boolean", + "description": "Content that expresses, incites, or promotes harassing language towards any target." + }, + "harassment/threatening": { + "type": "boolean", + "description": "Harassment content that also includes violence or serious harm towards any target." + }, + "illicit": { + "type": "boolean", + "nullable": true, + "description": "Content that includes instructions or advice that facilitate the planning or execution of wrongdoing, or that gives advice or instruction on how to commit illicit acts. For example, \"how to shoplift\" would fit this category." + }, + "illicit/violent": { + "type": "boolean", + "nullable": true, + "description": "Content that includes instructions or advice that facilitate the planning or execution of wrongdoing that also includes violence, or that gives advice or instruction on the procurement of any weapon." + }, + "self-harm": { + "type": "boolean", + "description": "Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders." + }, + "self-harm/intent": { + "type": "boolean", + "description": "Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders." + }, + "self-harm/instructions": { + "type": "boolean", + "description": "Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts." + }, + "sexual": { + "type": "boolean", + "description": "Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness)." + }, + "sexual/minors": { + "type": "boolean", + "description": "Sexual content that includes an individual who is under 18 years old." + }, + "violence": { + "type": "boolean", + "description": "Content that depicts death, violence, or physical injury." + }, + "violence/graphic": { + "type": "boolean", + "description": "Content that depicts death, violence, or physical injury in graphic detail." + } + }, + "required": [ + "hate", + "hate/threatening", + "harassment", + "harassment/threatening", + "illicit", + "illicit/violent", + "self-harm", + "self-harm/intent", + "self-harm/instructions", + "sexual", + "sexual/minors", + "violence", + "violence/graphic" + ] + }, + "category_scores": { + "type": "object", + "description": "A list of the categories along with their scores as predicted by model.", + "properties": { + "hate": { + "type": "number", + "description": "The score for the category 'hate'." + }, + "hate/threatening": { + "type": "number", + "description": "The score for the category 'hate/threatening'." + }, + "harassment": { + "type": "number", + "description": "The score for the category 'harassment'." + }, + "harassment/threatening": { + "type": "number", + "description": "The score for the category 'harassment/threatening'." + }, + "illicit": { + "type": "number", + "description": "The score for the category 'illicit'." + }, + "illicit/violent": { + "type": "number", + "description": "The score for the category 'illicit/violent'." + }, + "self-harm": { + "type": "number", + "description": "The score for the category 'self-harm'." + }, + "self-harm/intent": { + "type": "number", + "description": "The score for the category 'self-harm/intent'." + }, + "self-harm/instructions": { + "type": "number", + "description": "The score for the category 'self-harm/instructions'." + }, + "sexual": { + "type": "number", + "description": "The score for the category 'sexual'." + }, + "sexual/minors": { + "type": "number", + "description": "The score for the category 'sexual/minors'." + }, + "violence": { + "type": "number", + "description": "The score for the category 'violence'." + }, + "violence/graphic": { + "type": "number", + "description": "The score for the category 'violence/graphic'." + } + }, + "required": [ + "hate", + "hate/threatening", + "harassment", + "harassment/threatening", + "illicit", + "illicit/violent", + "self-harm", + "self-harm/intent", + "self-harm/instructions", + "sexual", + "sexual/minors", + "violence", + "violence/graphic" + ] + }, + "category_applied_input_types": { + "type": "object", + "description": "A list of the categories along with the input type(s) that the score applies to.", + "properties": { + "hate": { + "type": "array", + "description": "The applied input type(s) for the category 'hate'.", + "items": { + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + } + }, + "hate/threatening": { + "type": "array", + "description": "The applied input type(s) for the category 'hate/threatening'.", + "items": { + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + } + }, + "harassment": { + "type": "array", + "description": "The applied input type(s) for the category 'harassment'.", + "items": { + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + } + }, + "harassment/threatening": { + "type": "array", + "description": "The applied input type(s) for the category 'harassment/threatening'.", + "items": { + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + } + }, + "illicit": { + "type": "array", + "description": "The applied input type(s) for the category 'illicit'.", + "items": { + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + } + }, + "illicit/violent": { + "type": "array", + "description": "The applied input type(s) for the category 'illicit/violent'.", + "items": { + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + } + }, + "self-harm": { + "type": "array", + "description": "The applied input type(s) for the category 'self-harm'.", + "items": { + "type": "string", + "enum": [ + "text", + "image" + ] + } + }, + "self-harm/intent": { + "type": "array", + "description": "The applied input type(s) for the category 'self-harm/intent'.", + "items": { + "type": "string", + "enum": [ + "text", + "image" + ] + } + }, + "self-harm/instructions": { + "type": "array", + "description": "The applied input type(s) for the category 'self-harm/instructions'.", + "items": { + "type": "string", + "enum": [ + "text", + "image" + ] + } + }, + "sexual": { + "type": "array", + "description": "The applied input type(s) for the category 'sexual'.", + "items": { + "type": "string", + "enum": [ + "text", + "image" + ] + } + }, + "sexual/minors": { + "type": "array", + "description": "The applied input type(s) for the category 'sexual/minors'.", + "items": { + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + } + }, + "violence": { + "type": "array", + "description": "The applied input type(s) for the category 'violence'.", + "items": { + "type": "string", + "enum": [ + "text", + "image" + ] + } + }, + "violence/graphic": { + "type": "array", + "description": "The applied input type(s) for the category 'violence/graphic'.", + "items": { + "type": "string", + "enum": [ + "text", + "image" + ] + } + } + }, + "required": [ + "hate", + "hate/threatening", + "harassment", + "harassment/threatening", + "illicit", + "illicit/violent", + "self-harm", + "self-harm/intent", + "self-harm/instructions", + "sexual", + "sexual/minors", + "violence", + "violence/graphic" + ] + } + }, + "required": [ + "flagged", + "categories", + "category_scores", + "category_applied_input_types" + ] + } + } + }, + "required": [ + "id", + "model", + "results" + ], + "x-oaiMeta": { + "name": "The moderation object", + "example": "{\n \"id\": \"modr-0d9740456c391e43c445bf0f010940c7\",\n \"model\": \"omni-moderation-latest\",\n \"results\": [\n {\n \"flagged\": true,\n \"categories\": {\n \"harassment\": true,\n \"harassment/threatening\": true,\n \"sexual\": false,\n \"hate\": false,\n \"hate/threatening\": false,\n \"illicit\": false,\n \"illicit/violent\": false,\n \"self-harm/intent\": false,\n \"self-harm/instructions\": false,\n \"self-harm\": false,\n \"sexual/minors\": false,\n \"violence\": true,\n \"violence/graphic\": true\n },\n \"category_scores\": {\n \"harassment\": 0.8189693396524255,\n \"harassment/threatening\": 0.804985420696006,\n \"sexual\": 1.573112165348997e-6,\n \"hate\": 0.007562942636942845,\n \"hate/threatening\": 0.004208854591835476,\n \"illicit\": 0.030535955153511665,\n \"illicit/violent\": 0.008925306722380033,\n \"self-harm/intent\": 0.00023023930975076432,\n \"self-harm/instructions\": 0.0002293869201073356,\n \"self-harm\": 0.012598046106750154,\n \"sexual/minors\": 2.212566909570261e-8,\n \"violence\": 0.9999992735124786,\n \"violence/graphic\": 0.843064871157054\n },\n \"category_applied_input_types\": {\n \"harassment\": [\n \"text\"\n ],\n \"harassment/threatening\": [\n \"text\"\n ],\n \"sexual\": [\n \"text\",\n \"image\"\n ],\n \"hate\": [\n \"text\"\n ],\n \"hate/threatening\": [\n \"text\"\n ],\n \"illicit\": [\n \"text\"\n ],\n \"illicit/violent\": [\n \"text\"\n ],\n \"self-harm/intent\": [\n \"text\",\n \"image\"\n ],\n \"self-harm/instructions\": [\n \"text\",\n \"image\"\n ],\n \"self-harm\": [\n \"text\",\n \"image\"\n ],\n \"sexual/minors\": [\n \"text\"\n ],\n \"violence\": [\n \"text\",\n \"image\"\n ],\n \"violence/graphic\": [\n \"text\",\n \"image\"\n ]\n }\n }\n ]\n}\n" + } + }, + "CreateResponse": { + "allOf": [ + { + "$ref": "#/components/schemas/CreateModelResponseProperties" + }, + { + "$ref": "#/components/schemas/ResponseProperties" + }, + { + "type": "object", + "properties": { + "input": { + "description": "Text, image, or file inputs to the model, used to generate a response.\n\nLearn more:\n- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n- [Image inputs](https://platform.openai.com/docs/guides/images)\n- [File inputs](https://platform.openai.com/docs/guides/pdf-files)\n- [Conversation state](https://platform.openai.com/docs/guides/conversation-state)\n- [Function calling](https://platform.openai.com/docs/guides/function-calling)\n", + "anyOf": [ + { + "type": "string", + "title": "Text input", + "description": "A text input to the model, equivalent to a text input with the\n`user` role.\n" + }, + { + "type": "array", + "title": "Input item list", + "description": "A list of one or many input items to the model, containing\ndifferent content types.\n", + "items": { + "$ref": "#/components/schemas/InputItem" + } + } + ] + }, + "include": { + "type": "array", + "description": "Specify additional output data to include in the model response. Currently\nsupported values are:\n- `web_search_call.action.sources`: Include the sources of the web search tool call.\n- `code_interpreter_call.outputs`: Includes the outputs of python code execution\n in code interpreter tool call items.\n- `computer_call_output.output.image_url`: Include image urls from the computer call output.\n- `file_search_call.results`: Include the search results of\n the file search tool call.\n- `message.input_image.image_url`: Include image urls from the input message.\n- `message.output_text.logprobs`: Include logprobs with assistant messages.\n- `reasoning.encrypted_content`: Includes an encrypted version of reasoning\n tokens in reasoning item outputs. This enables reasoning items to be used in\n multi-turn conversations when using the Responses API statelessly (like\n when the `store` parameter is set to `false`, or when an organization is\n enrolled in the zero data retention program).\n", + "items": { + "$ref": "#/components/schemas/Includable" + }, + "nullable": true + }, + "parallel_tool_calls": { + "type": "boolean", + "description": "Whether to allow the model to run tool calls in parallel.\n", + "default": true, + "nullable": true + }, + "store": { + "type": "boolean", + "description": "Whether to store the generated model response for later retrieval via\nAPI.\n", + "default": true, + "nullable": true + }, + "instructions": { + "type": "string", + "nullable": true, + "description": "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n" + }, + "stream": { + "description": "If set to true, the model response data will be streamed to the client\nas it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\nSee the [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)\nfor more information.\n", + "type": "boolean", + "nullable": true, + "default": false + }, + "stream_options": { + "$ref": "#/components/schemas/ResponseStreamOptions" + }, + "conversation": { + "description": "The conversation that this response belongs to. Items from this conversation are prepended to `input_items` for this response request.\nInput items and output items from this response are automatically added to this conversation after this response completes.\n", + "nullable": true, + "anyOf": [ + { + "type": "string", + "title": "Conversation ID", + "description": "The unique ID of the conversation.\n" + }, + { + "$ref": "#/components/schemas/ConversationParam" + } + ] + } + } + } + ] + }, + "CreateRunRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "assistant_id": { + "description": "The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.", + "type": "string" + }, + "model": { + "description": "The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.", + "anyOf": [ + { + "type": "string" + }, + { + "$ref": "#/components/schemas/AssistantSupportedModels" + } + ], + "x-oaiTypeLabel": "string", + "nullable": true + }, + "reasoning_effort": { + "$ref": "#/components/schemas/ReasoningEffort" + }, + "instructions": { + "description": "Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis.", + "type": "string", + "nullable": true + }, + "additional_instructions": { + "description": "Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.", + "type": "string", + "nullable": true + }, + "additional_messages": { + "description": "Adds additional messages to the thread before creating the run.", + "type": "array", + "items": { + "$ref": "#/components/schemas/CreateMessageRequest" + }, + "nullable": true + }, + "tools": { + "description": "Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.", + "nullable": true, + "type": "array", + "maxItems": 20, + "items": { + "$ref": "#/components/schemas/AssistantTool" + } + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "temperature": { + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 1, + "example": 1, + "nullable": true, + "description": "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n" + }, + "top_p": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 1, + "example": 1, + "nullable": true, + "description": "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }, + "stream": { + "type": "boolean", + "nullable": true, + "description": "If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" + }, + "max_prompt_tokens": { + "type": "integer", + "nullable": true, + "description": "The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + "minimum": 256 + }, + "max_completion_tokens": { + "type": "integer", + "nullable": true, + "description": "The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + "minimum": 256 + }, + "truncation_strategy": { + "allOf": [ + { + "$ref": "#/components/schemas/TruncationObject" + }, + { + "nullable": true + } + ] + }, + "tool_choice": { + "allOf": [ + { + "$ref": "#/components/schemas/AssistantsApiToolChoiceOption" + }, + { + "nullable": true + } + ] + }, + "parallel_tool_calls": { + "$ref": "#/components/schemas/ParallelToolCalls" + }, + "response_format": { + "$ref": "#/components/schemas/AssistantsApiResponseFormatOption", + "nullable": true + } + }, + "required": [ + "assistant_id" + ] + }, + "CreateSpeechRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "model": { + "description": "One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`.\n", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "tts-1", + "tts-1-hd", + "gpt-4o-mini-tts" + ], + "x-stainless-nominal": false + } + ], + "x-oaiTypeLabel": "string" + }, + "input": { + "type": "string", + "description": "The text to generate audio for. The maximum length is 4096 characters.", + "maxLength": 4096 + }, + "instructions": { + "type": "string", + "description": "Control the voice of your generated audio with additional instructions. Does not work with `tts-1` or `tts-1-hd`.", + "maxLength": 4096 + }, + "voice": { + "description": "The voice to use when generating the audio. Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options).", + "$ref": "#/components/schemas/VoiceIdsShared" + }, + "response_format": { + "description": "The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`.", + "default": "mp3", + "type": "string", + "enum": [ + "mp3", + "opus", + "aac", + "flac", + "wav", + "pcm" + ] + }, + "speed": { + "description": "The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default.", + "type": "number", + "default": 1, + "minimum": 0.25, + "maximum": 4 + }, + "stream_format": { + "description": "The format to stream the audio in. Supported formats are `sse` and `audio`. `sse` is not supported for `tts-1` or `tts-1-hd`.", + "type": "string", + "default": "audio", + "enum": [ + "sse", + "audio" + ] + } + }, + "required": [ + "model", + "input", + "voice" + ] + }, + "CreateSpeechResponseStreamEvent": { + "anyOf": [ + { + "$ref": "#/components/schemas/SpeechAudioDeltaEvent" + }, + { + "$ref": "#/components/schemas/SpeechAudioDoneEvent" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "CreateThreadAndRunRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "assistant_id": { + "description": "The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.", + "type": "string" + }, + "thread": { + "$ref": "#/components/schemas/CreateThreadRequest" + }, + "model": { + "description": "The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "gpt-5", + "gpt-5-mini", + "gpt-5-nano", + "gpt-5-2025-08-07", + "gpt-5-mini-2025-08-07", + "gpt-5-nano-2025-08-07", + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613" + ] + } + ], + "x-oaiTypeLabel": "string", + "nullable": true + }, + "instructions": { + "description": "Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis.", + "type": "string", + "nullable": true + }, + "tools": { + "description": "Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.", + "nullable": true, + "type": "array", + "maxItems": 20, + "items": { + "$ref": "#/components/schemas/AssistantTool" + } + }, + "tool_resources": { + "type": "object", + "description": "A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n", + "properties": { + "code_interpreter": { + "type": "object", + "properties": { + "file_ids": { + "type": "array", + "description": "A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + "default": [], + "maxItems": 20, + "items": { + "type": "string" + } + } + } + }, + "file_search": { + "type": "object", + "properties": { + "vector_store_ids": { + "type": "array", + "description": "The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + "maxItems": 1, + "items": { + "type": "string" + } + } + } + } + }, + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "temperature": { + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 1, + "example": 1, + "nullable": true, + "description": "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n" + }, + "top_p": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 1, + "example": 1, + "nullable": true, + "description": "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }, + "stream": { + "type": "boolean", + "nullable": true, + "description": "If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" + }, + "max_prompt_tokens": { + "type": "integer", + "nullable": true, + "description": "The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + "minimum": 256 + }, + "max_completion_tokens": { + "type": "integer", + "nullable": true, + "description": "The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + "minimum": 256 + }, + "truncation_strategy": { + "allOf": [ + { + "$ref": "#/components/schemas/TruncationObject" + }, + { + "nullable": true + } + ] + }, + "tool_choice": { + "allOf": [ + { + "$ref": "#/components/schemas/AssistantsApiToolChoiceOption" + }, + { + "nullable": true + } + ] + }, + "parallel_tool_calls": { + "$ref": "#/components/schemas/ParallelToolCalls" + }, + "response_format": { + "$ref": "#/components/schemas/AssistantsApiResponseFormatOption", + "nullable": true + } + }, + "required": [ + "assistant_id" + ] + }, + "CreateThreadRequest": { + "type": "object", + "description": "Options to create a new thread. If no thread is provided when running a \nrequest, an empty thread will be created.\n", + "additionalProperties": false, + "properties": { + "messages": { + "description": "A list of [messages](https://platform.openai.com/docs/api-reference/messages) to start the thread with.", + "type": "array", + "items": { + "$ref": "#/components/schemas/CreateMessageRequest" + } + }, + "tool_resources": { + "type": "object", + "description": "A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n", + "properties": { + "code_interpreter": { + "type": "object", + "properties": { + "file_ids": { + "type": "array", + "description": "A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + "default": [], + "maxItems": 20, + "items": { + "type": "string" + } + } + } + }, + "file_search": { + "type": "object", + "properties": { + "vector_store_ids": { + "type": "array", + "description": "The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + "maxItems": 1, + "items": { + "type": "string" + } + }, + "vector_stores": { + "type": "array", + "description": "A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + "maxItems": 1, + "items": { + "type": "object", + "properties": { + "file_ids": { + "type": "array", + "description": "A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n", + "maxItems": 10000, + "items": { + "type": "string" + } + }, + "chunking_strategy": { + "type": "object", + "description": "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.", + "anyOf": [ + { + "type": "object", + "title": "Auto Chunking Strategy", + "description": "The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`.", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "Always `auto`.", + "enum": [ + "auto" + ], + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + { + "type": "object", + "title": "Static Chunking Strategy", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "Always `static`.", + "enum": [ + "static" + ], + "x-stainless-const": true + }, + "static": { + "type": "object", + "additionalProperties": false, + "properties": { + "max_chunk_size_tokens": { + "type": "integer", + "minimum": 100, + "maximum": 4096, + "description": "The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`." + }, + "chunk_overlap_tokens": { + "type": "integer", + "description": "The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" + } + }, + "required": [ + "max_chunk_size_tokens", + "chunk_overlap_tokens" + ] + } + }, + "required": [ + "type", + "static" + ], + "x-stainless-naming": { + "java": { + "type_name": "StaticObject" + }, + "kotlin": { + "type_name": "StaticObject" + } + } + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + } + } + }, + "anyOf": [ + { + "required": [ + "vector_store_ids" + ] + }, + { + "required": [ + "vector_stores" + ] + } + ] + } + }, + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + }, + "CreateTranscriptionRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "file": { + "description": "The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n", + "type": "string", + "x-oaiTypeLabel": "file", + "format": "binary", + "x-oaiMeta": { + "exampleFilePath": "speech.mp3" + } + }, + "model": { + "description": "ID of the model to use. The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source Whisper V2 model).\n", + "example": "gpt-4o-transcribe", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "whisper-1", + "gpt-4o-transcribe", + "gpt-4o-mini-transcribe" + ], + "x-stainless-const": true, + "x-stainless-nominal": false + } + ], + "x-oaiTypeLabel": "string" + }, + "language": { + "description": "The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format will improve accuracy and latency.\n", + "type": "string" + }, + "prompt": { + "description": "An optional text to guide the model's style or continue a previous audio segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should match the audio language.\n", + "type": "string" + }, + "response_format": { + "$ref": "#/components/schemas/AudioResponseFormat" + }, + "temperature": { + "description": "The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n", + "type": "number", + "default": 0 + }, + "stream": { + "description": "If set to true, the model response data will be streamed to the client\nas it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\nSee the [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions)\nfor more information.\n\nNote: Streaming is not supported for the `whisper-1` model and will be ignored.\n", + "type": "boolean", + "nullable": true, + "default": false + }, + "chunking_strategy": { + "$ref": "#/components/schemas/TranscriptionChunkingStrategy" + }, + "timestamp_granularities": { + "description": "The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency.\n", + "type": "array", + "items": { + "type": "string", + "enum": [ + "word", + "segment" + ] + }, + "default": [ + "segment" + ] + }, + "include": { + "description": "Additional information to include in the transcription response. \n`logprobs` will return the log probabilities of the tokens in the \nresponse to understand the model's confidence in the transcription. \n`logprobs` only works with response_format set to `json` and only with \nthe models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`.\n", + "type": "array", + "items": { + "$ref": "#/components/schemas/TranscriptionInclude" + } + } + }, + "required": [ + "file", + "model" + ] + }, + "CreateTranscriptionResponseJson": { + "type": "object", + "description": "Represents a transcription response returned by model, based on the provided input.", + "properties": { + "text": { + "type": "string", + "description": "The transcribed text." + }, + "logprobs": { + "type": "array", + "optional": true, + "description": "The log probabilities of the tokens in the transcription. Only returned with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added to the `include` array.\n", + "items": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "The token in the transcription." + }, + "logprob": { + "type": "number", + "description": "The log probability of the token." + }, + "bytes": { + "type": "array", + "items": { + "type": "number" + }, + "description": "The bytes of the token." + } + } + } + }, + "usage": { + "type": "object", + "description": "Token usage statistics for the request.", + "anyOf": [ + { + "$ref": "#/components/schemas/TranscriptTextUsageTokens", + "title": "Token Usage" + }, + { + "$ref": "#/components/schemas/TranscriptTextUsageDuration", + "title": "Duration Usage" + } + ], + "discriminator": { + "propertyName": "type" + } + } + }, + "required": [ + "text" + ], + "x-oaiMeta": { + "name": "The transcription object (JSON)", + "group": "audio", + "example": "{\n \"text\": \"Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that.\",\n \"usage\": {\n \"type\": \"tokens\",\n \"input_tokens\": 14,\n \"input_token_details\": {\n \"text_tokens\": 10,\n \"audio_tokens\": 4\n },\n \"output_tokens\": 101,\n \"total_tokens\": 115\n }\n}\n" + } + }, + "CreateTranscriptionResponseStreamEvent": { + "anyOf": [ + { + "$ref": "#/components/schemas/TranscriptTextDeltaEvent" + }, + { + "$ref": "#/components/schemas/TranscriptTextDoneEvent" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "CreateTranscriptionResponseVerboseJson": { + "type": "object", + "description": "Represents a verbose json transcription response returned by model, based on the provided input.", + "properties": { + "language": { + "type": "string", + "description": "The language of the input audio." + }, + "duration": { + "type": "number", + "description": "The duration of the input audio." + }, + "text": { + "type": "string", + "description": "The transcribed text." + }, + "words": { + "type": "array", + "description": "Extracted words and their corresponding timestamps.", + "items": { + "$ref": "#/components/schemas/TranscriptionWord" + } + }, + "segments": { + "type": "array", + "description": "Segments of the transcribed text and their corresponding details.", + "items": { + "$ref": "#/components/schemas/TranscriptionSegment" + } + }, + "usage": { + "$ref": "#/components/schemas/TranscriptTextUsageDuration" + } + }, + "required": [ + "language", + "duration", + "text" + ], + "x-oaiMeta": { + "name": "The transcription object (Verbose JSON)", + "group": "audio", + "example": "{\n \"task\": \"transcribe\",\n \"language\": \"english\",\n \"duration\": 8.470000267028809,\n \"text\": \"The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.\",\n \"segments\": [\n {\n \"id\": 0,\n \"seek\": 0,\n \"start\": 0.0,\n \"end\": 3.319999933242798,\n \"text\": \" The beach was a popular spot on a hot summer day.\",\n \"tokens\": [\n 50364, 440, 7534, 390, 257, 3743, 4008, 322, 257, 2368, 4266, 786, 13, 50530\n ],\n \"temperature\": 0.0,\n \"avg_logprob\": -0.2860786020755768,\n \"compression_ratio\": 1.2363636493682861,\n \"no_speech_prob\": 0.00985979475080967\n },\n ...\n ],\n \"usage\": {\n \"type\": \"duration\",\n \"seconds\": 9\n }\n}\n" + } + }, + "CreateTranslationRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "file": { + "description": "The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n", + "type": "string", + "x-oaiTypeLabel": "file", + "format": "binary", + "x-oaiMeta": { + "exampleFilePath": "speech.mp3" + } + }, + "model": { + "description": "ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available.\n", + "example": "whisper-1", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "whisper-1" + ], + "x-stainless-const": true + } + ], + "x-oaiTypeLabel": "string" + }, + "prompt": { + "description": "An optional text to guide the model's style or continue a previous audio segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should be in English.\n", + "type": "string" + }, + "response_format": { + "description": "The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`.\n", + "type": "string", + "enum": [ + "json", + "text", + "srt", + "verbose_json", + "vtt" + ], + "default": "json" + }, + "temperature": { + "description": "The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n", + "type": "number", + "default": 0 + } + }, + "required": [ + "file", + "model" + ] + }, + "CreateTranslationResponseJson": { + "type": "object", + "properties": { + "text": { + "type": "string" + } + }, + "required": [ + "text" + ] + }, + "CreateTranslationResponseVerboseJson": { + "type": "object", + "properties": { + "language": { + "type": "string", + "description": "The language of the output translation (always `english`)." + }, + "duration": { + "type": "number", + "description": "The duration of the input audio." + }, + "text": { + "type": "string", + "description": "The translated text." + }, + "segments": { + "type": "array", + "description": "Segments of the translated text and their corresponding details.", + "items": { + "$ref": "#/components/schemas/TranscriptionSegment" + } + } + }, + "required": [ + "language", + "duration", + "text" + ] + }, + "CreateUploadRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "filename": { + "description": "The name of the file to upload.\n", + "type": "string" + }, + "purpose": { + "description": "The intended purpose of the uploaded file.\n\nSee the [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose).\n", + "type": "string", + "enum": [ + "assistants", + "batch", + "fine-tune", + "vision" + ] + }, + "bytes": { + "description": "The number of bytes in the file you are uploading.\n", + "type": "integer" + }, + "mime_type": { + "description": "The MIME type of the file.\n\nThis must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision.\n", + "type": "string" + }, + "expires_after": { + "$ref": "#/components/schemas/FileExpirationAfter" + } + }, + "required": [ + "filename", + "purpose", + "bytes", + "mime_type" + ] + }, + "CreateVectorStoreFileBatchRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "file_ids": { + "description": "A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files.", + "type": "array", + "minItems": 1, + "maxItems": 500, + "items": { + "type": "string" + } + }, + "chunking_strategy": { + "$ref": "#/components/schemas/ChunkingStrategyRequestParam" + }, + "attributes": { + "$ref": "#/components/schemas/VectorStoreFileAttributes" + } + }, + "required": [ + "file_ids" + ] + }, + "CreateVectorStoreFileRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "file_id": { + "description": "A [File](https://platform.openai.com/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files.", + "type": "string" + }, + "chunking_strategy": { + "$ref": "#/components/schemas/ChunkingStrategyRequestParam" + }, + "attributes": { + "$ref": "#/components/schemas/VectorStoreFileAttributes" + } + }, + "required": [ + "file_id" + ] + }, + "CreateVectorStoreRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "file_ids": { + "description": "A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files.", + "type": "array", + "maxItems": 500, + "items": { + "type": "string" + } + }, + "name": { + "description": "The name of the vector store.", + "type": "string" + }, + "expires_after": { + "$ref": "#/components/schemas/VectorStoreExpirationAfter" + }, + "chunking_strategy": { + "$ref": "#/components/schemas/ChunkingStrategyRequestParam" + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + }, + "CustomTool": { + "type": "object", + "title": "Custom tool", + "description": "A custom tool that processes input using a specified format. Learn more about\n[custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools).\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "custom" + ], + "description": "The type of the custom tool. Always `custom`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the custom tool, used to identify it in tool calls." + }, + "description": { + "type": "string", + "description": "Optional description of the custom tool, used to provide more context.\n" + }, + "format": { + "description": "The input format for the custom tool. Default is unconstrained text.\n", + "anyOf": [ + { + "type": "object", + "title": "Text format", + "description": "Unconstrained free-form text.", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ], + "description": "Unconstrained text format. Always `text`.", + "x-stainless-const": true + } + }, + "required": [ + "type" + ], + "additionalProperties": false + }, + { + "type": "object", + "title": "Grammar format", + "description": "A grammar defined by the user.", + "properties": { + "type": { + "type": "string", + "enum": [ + "grammar" + ], + "description": "Grammar format. Always `grammar`.", + "x-stainless-const": true + }, + "definition": { + "type": "string", + "description": "The grammar definition." + }, + "syntax": { + "type": "string", + "description": "The syntax of the grammar definition. One of `lark` or `regex`.", + "enum": [ + "lark", + "regex" + ] + } + }, + "required": [ + "type", + "definition", + "syntax" + ], + "additionalProperties": false + } + ], + "discriminator": { + "propertyName": "type" + } + } + }, + "required": [ + "type", + "name" + ] + }, + "CustomToolCall": { + "type": "object", + "title": "Custom tool call", + "description": "A call to a custom tool created by the model.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "custom_tool_call" + ], + "x-stainless-const": true, + "description": "The type of the custom tool call. Always `custom_tool_call`.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the custom tool call in the OpenAI platform.\n" + }, + "call_id": { + "type": "string", + "description": "An identifier used to map this custom tool call to a tool call output.\n" + }, + "name": { + "type": "string", + "description": "The name of the custom tool being called.\n" + }, + "input": { + "type": "string", + "description": "The input for the custom tool call generated by the model.\n" + } + }, + "required": [ + "type", + "call_id", + "name", + "input" + ] + }, + "CustomToolCallOutput": { + "type": "object", + "title": "Custom tool call output", + "description": "The output of a custom tool call from your code, being sent back to the model.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "custom_tool_call_output" + ], + "x-stainless-const": true, + "description": "The type of the custom tool call output. Always `custom_tool_call_output`.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the custom tool call output in the OpenAI platform.\n" + }, + "call_id": { + "type": "string", + "description": "The call ID, used to map this custom tool call output to a custom tool call.\n" + }, + "output": { + "type": "string", + "description": "The output from the custom tool call generated by your code.\n" + } + }, + "required": [ + "type", + "call_id", + "output" + ] + }, + "CustomToolChatCompletions": { + "type": "object", + "title": "Custom tool", + "description": "A custom tool that processes input using a specified format.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "custom" + ], + "description": "The type of the custom tool. Always `custom`.", + "x-stainless-const": true + }, + "custom": { + "type": "object", + "title": "Custom tool properties", + "description": "Properties of the custom tool.\n", + "properties": { + "name": { + "type": "string", + "description": "The name of the custom tool, used to identify it in tool calls." + }, + "description": { + "type": "string", + "description": "Optional description of the custom tool, used to provide more context.\n" + }, + "format": { + "description": "The input format for the custom tool. Default is unconstrained text.\n", + "anyOf": [ + { + "type": "object", + "title": "Text format", + "description": "Unconstrained free-form text.", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ], + "description": "Unconstrained text format. Always `text`.", + "x-stainless-const": true + } + }, + "required": [ + "type" + ], + "additionalProperties": false + }, + { + "type": "object", + "title": "Grammar format", + "description": "A grammar defined by the user.", + "properties": { + "type": { + "type": "string", + "enum": [ + "grammar" + ], + "description": "Grammar format. Always `grammar`.", + "x-stainless-const": true + }, + "grammar": { + "type": "object", + "title": "Grammar format", + "description": "Your chosen grammar.", + "properties": { + "definition": { + "type": "string", + "description": "The grammar definition." + }, + "syntax": { + "type": "string", + "description": "The syntax of the grammar definition. One of `lark` or `regex`.", + "enum": [ + "lark", + "regex" + ] + } + }, + "required": [ + "definition", + "syntax" + ] + } + }, + "required": [ + "type", + "grammar" + ], + "additionalProperties": false + } + ], + "discriminator": { + "propertyName": "type" + } + } + }, + "required": [ + "name" + ] + } + }, + "required": [ + "type", + "custom" + ] + }, + "DeleteAssistantResponse": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + }, + "object": { + "type": "string", + "enum": [ + "assistant.deleted" + ], + "x-stainless-const": true + } + }, + "required": [ + "id", + "object", + "deleted" + ] + }, + "DeleteCertificateResponse": { + "type": "object", + "properties": { + "object": { + "description": "The object type, must be `certificate.deleted`.", + "x-stainless-const": true, + "const": "certificate.deleted" + }, + "id": { + "type": "string", + "description": "The ID of the certificate that was deleted." + } + }, + "required": [ + "object", + "id" + ] + }, + "DeleteFileResponse": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "object": { + "type": "string", + "enum": [ + "file" + ], + "x-stainless-const": true + }, + "deleted": { + "type": "boolean" + } + }, + "required": [ + "id", + "object", + "deleted" + ] + }, + "DeleteFineTuningCheckpointPermissionResponse": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The ID of the fine-tuned model checkpoint permission that was deleted." + }, + "object": { + "type": "string", + "description": "The object type, which is always \"checkpoint.permission\".", + "enum": [ + "checkpoint.permission" + ], + "x-stainless-const": true + }, + "deleted": { + "type": "boolean", + "description": "Whether the fine-tuned model checkpoint permission was successfully deleted." + } + }, + "required": [ + "id", + "object", + "deleted" + ] + }, + "DeleteMessageResponse": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + }, + "object": { + "type": "string", + "enum": [ + "thread.message.deleted" + ], + "x-stainless-const": true + } + }, + "required": [ + "id", + "object", + "deleted" + ] + }, + "DeleteModelResponse": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + }, + "object": { + "type": "string" + } + }, + "required": [ + "id", + "object", + "deleted" + ] + }, + "DeleteThreadResponse": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + }, + "object": { + "type": "string", + "enum": [ + "thread.deleted" + ], + "x-stainless-const": true + } + }, + "required": [ + "id", + "object", + "deleted" + ] + }, + "DeleteVectorStoreFileResponse": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + }, + "object": { + "type": "string", + "enum": [ + "vector_store.file.deleted" + ], + "x-stainless-const": true + } + }, + "required": [ + "id", + "object", + "deleted" + ] + }, + "DeleteVectorStoreResponse": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + }, + "object": { + "type": "string", + "enum": [ + "vector_store.deleted" + ], + "x-stainless-const": true + } + }, + "required": [ + "id", + "object", + "deleted" + ] + }, + "DeletedConversation": { + "title": "The deleted conversation object", + "allOf": [ + { + "$ref": "#/components/schemas/DeletedConversationResource" + } + ], + "x-oaiMeta": { + "name": "The deleted conversation object", + "group": "conversations" + } + }, + "DoneEvent": { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "done" + ], + "x-stainless-const": true + }, + "data": { + "type": "string", + "enum": [ + "[DONE]" + ], + "x-stainless-const": true + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a stream ends.", + "x-oaiMeta": { + "dataDescription": "`data` is `[DONE]`" + } + }, + "DoubleClick": { + "type": "object", + "title": "DoubleClick", + "description": "A double click action.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "double_click" + ], + "default": "double_click", + "description": "Specifies the event type. For a double click action, this property is \nalways set to `double_click`.\n", + "x-stainless-const": true + }, + "x": { + "type": "integer", + "description": "The x-coordinate where the double click occurred.\n" + }, + "y": { + "type": "integer", + "description": "The y-coordinate where the double click occurred.\n" + } + }, + "required": [ + "type", + "x", + "y" + ] + }, + "Drag": { + "type": "object", + "title": "Drag", + "description": "A drag action.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "drag" + ], + "default": "drag", + "description": "Specifies the event type. For a drag action, this property is \nalways set to `drag`.\n", + "x-stainless-const": true + }, + "path": { + "type": "array", + "description": "An array of coordinates representing the path of the drag action. Coordinates will appear as an array\nof objects, eg\n```\n[ { x: 100, y: 200 },\n { x: 200, y: 300 }\n]\n```\n", + "items": { + "title": "Drag path coordinates", + "description": "A series of x/y coordinate pairs in the drag path.\n", + "$ref": "#/components/schemas/Coordinate" + } + } + }, + "required": [ + "type", + "path" + ] + }, + "EasyInputMessage": { + "type": "object", + "title": "Input message", + "description": "A message input to the model with a role indicating instruction following\nhierarchy. Instructions given with the `developer` or `system` role take\nprecedence over instructions given with the `user` role. Messages with the\n`assistant` role are presumed to have been generated by the model in previous\ninteractions.\n", + "properties": { + "role": { + "type": "string", + "description": "The role of the message input. One of `user`, `assistant`, `system`, or\n`developer`.\n", + "enum": [ + "user", + "assistant", + "system", + "developer" + ] + }, + "content": { + "description": "Text, image, or audio input to the model, used to generate a response.\nCan also contain previous assistant responses.\n", + "anyOf": [ + { + "type": "string", + "title": "Text input", + "description": "A text input to the model.\n" + }, + { + "$ref": "#/components/schemas/InputMessageContentList" + } + ] + }, + "type": { + "type": "string", + "description": "The type of the message input. Always `message`.\n", + "enum": [ + "message" + ], + "x-stainless-const": true + } + }, + "required": [ + "role", + "content" + ] + }, + "Embedding": { + "type": "object", + "description": "Represents an embedding vector returned by embedding endpoint.\n", + "properties": { + "index": { + "type": "integer", + "description": "The index of the embedding in the list of embeddings." + }, + "embedding": { + "type": "array", + "description": "The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](https://platform.openai.com/docs/guides/embeddings).\n", + "items": { + "type": "number", + "format": "float" + } + }, + "object": { + "type": "string", + "description": "The object type, which is always \"embedding\".", + "enum": [ + "embedding" + ], + "x-stainless-const": true + } + }, + "required": [ + "index", + "object", + "embedding" + ], + "x-oaiMeta": { + "name": "The embedding object", + "example": "{\n \"object\": \"embedding\",\n \"embedding\": [\n 0.0023064255,\n -0.009327292,\n .... (1536 floats total for ada-002)\n -0.0028842222,\n ],\n \"index\": 0\n}\n" + } + }, + "Error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "nullable": true + }, + "message": { + "type": "string", + "nullable": false + }, + "param": { + "type": "string", + "nullable": true + }, + "type": { + "type": "string", + "nullable": false + } + }, + "required": [ + "type", + "message", + "param", + "code" + ] + }, + "ErrorEvent": { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "error" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/Error" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when an [error](https://platform.openai.com/docs/guides/error-codes#api-errors) occurs. This can happen due to an internal server error or a timeout.", + "x-oaiMeta": { + "dataDescription": "`data` is an [error](/docs/guides/error-codes#api-errors)" + } + }, + "ErrorResponse": { + "type": "object", + "properties": { + "error": { + "$ref": "#/components/schemas/Error" + } + }, + "required": [ + "error" + ] + }, + "Eval": { + "type": "object", + "title": "Eval", + "description": "An Eval object with a data source config and testing criteria.\nAn Eval represents a task to be done for your LLM integration.\nLike:\n - Improve the quality of my chatbot\n - See how well my chatbot handles customer support\n - Check if o4-mini is better at my usecase than gpt-4o\n", + "properties": { + "object": { + "type": "string", + "enum": [ + "eval" + ], + "default": "eval", + "description": "The object type.", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "Unique identifier for the evaluation." + }, + "name": { + "type": "string", + "description": "The name of the evaluation.", + "example": "Chatbot effectiveness Evaluation" + }, + "data_source_config": { + "type": "object", + "description": "Configuration of data sources used in runs of the evaluation.", + "anyOf": [ + { + "$ref": "#/components/schemas/EvalCustomDataSourceConfig" + }, + { + "$ref": "#/components/schemas/EvalLogsDataSourceConfig" + }, + { + "$ref": "#/components/schemas/EvalStoredCompletionsDataSourceConfig" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "testing_criteria": { + "description": "A list of testing criteria.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/EvalGraderLabelModel" + }, + { + "$ref": "#/components/schemas/EvalGraderStringCheck" + }, + { + "$ref": "#/components/schemas/EvalGraderTextSimilarity" + }, + { + "$ref": "#/components/schemas/EvalGraderPython" + }, + { + "$ref": "#/components/schemas/EvalGraderScoreModel" + } + ] + } + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the eval was created." + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + }, + "required": [ + "id", + "data_source_config", + "object", + "testing_criteria", + "name", + "created_at", + "metadata" + ], + "x-oaiMeta": { + "name": "The eval object", + "group": "evals", + "example": "{\n \"object\": \"eval\",\n \"id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"data_source_config\": {\n \"type\": \"custom\",\n \"item_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"label\": {\"type\": \"string\"},\n },\n \"required\": [\"label\"]\n },\n \"include_sample_schema\": true\n },\n \"testing_criteria\": [\n {\n \"name\": \"My string check grader\",\n \"type\": \"string_check\",\n \"input\": \"{{sample.output_text}}\",\n \"reference\": \"{{item.label}}\",\n \"operation\": \"eq\",\n }\n ],\n \"name\": \"External Data Eval\",\n \"created_at\": 1739314509,\n \"metadata\": {\n \"test\": \"synthetics\",\n }\n}\n" + } + }, + "EvalApiError": { + "type": "object", + "title": "EvalApiError", + "description": "An object representing an error response from the Eval API.\n", + "properties": { + "code": { + "type": "string", + "description": "The error code." + }, + "message": { + "type": "string", + "description": "The error message." + } + }, + "required": [ + "code", + "message" + ], + "x-oaiMeta": { + "name": "The API error object", + "group": "evals", + "example": "{\n \"code\": \"internal_error\",\n \"message\": \"The eval run failed due to an internal error.\"\n}\n" + } + }, + "EvalCustomDataSourceConfig": { + "type": "object", + "title": "CustomDataSourceConfig", + "description": "A CustomDataSourceConfig which specifies the schema of your `item` and optionally `sample` namespaces.\nThe response schema defines the shape of the data that will be:\n- Used to define your testing criteria and\n- What data is required when creating a run\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "custom" + ], + "default": "custom", + "description": "The type of data source. Always `custom`.", + "x-stainless-const": true + }, + "schema": { + "type": "object", + "description": "The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n", + "additionalProperties": true + } + }, + "required": [ + "type", + "schema" + ], + "x-oaiMeta": { + "name": "The eval custom data source config object", + "group": "evals", + "example": "{\n \"type\": \"custom\",\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"item\": {\n \"type\": \"object\",\n \"properties\": {\n \"label\": {\"type\": \"string\"},\n },\n \"required\": [\"label\"]\n }\n },\n \"required\": [\"item\"]\n }\n}\n" + } + }, + "EvalGraderLabelModel": { + "type": "object", + "title": "LabelModelGrader", + "allOf": [ + { + "$ref": "#/components/schemas/GraderLabelModel" + } + ] + }, + "EvalGraderPython": { + "type": "object", + "title": "PythonGrader", + "allOf": [ + { + "$ref": "#/components/schemas/GraderPython" + }, + { + "type": "object", + "properties": { + "pass_threshold": { + "type": "number", + "description": "The threshold for the score." + } + }, + "x-oaiMeta": { + "name": "Eval Python Grader", + "group": "graders", + "example": "{\n \"type\": \"python\",\n \"name\": \"Example python grader\",\n \"image_tag\": \"2025-05-08\",\n \"source\": \"\"\"\ndef grade(sample: dict, item: dict) -> float:\n \\\"\"\"\n Returns 1.0 if `output_text` equals `label`, otherwise 0.0.\n \\\"\"\"\n output = sample.get(\"output_text\")\n label = item.get(\"label\")\n return 1.0 if output == label else 0.0\n\"\"\",\n \"pass_threshold\": 0.8\n}\n" + } + } + ] + }, + "EvalGraderScoreModel": { + "type": "object", + "title": "ScoreModelGrader", + "allOf": [ + { + "$ref": "#/components/schemas/GraderScoreModel" + }, + { + "type": "object", + "properties": { + "pass_threshold": { + "type": "number", + "description": "The threshold for the score." + } + } + } + ] + }, + "EvalGraderStringCheck": { + "type": "object", + "title": "StringCheckGrader", + "allOf": [ + { + "$ref": "#/components/schemas/GraderStringCheck" + } + ] + }, + "EvalGraderTextSimilarity": { + "type": "object", + "title": "TextSimilarityGrader", + "allOf": [ + { + "$ref": "#/components/schemas/GraderTextSimilarity" + }, + { + "type": "object", + "properties": { + "pass_threshold": { + "type": "number", + "description": "The threshold for the score." + } + }, + "required": [ + "pass_threshold" + ], + "x-oaiMeta": { + "name": "Text Similarity Grader", + "group": "graders", + "example": "{\n \"type\": \"text_similarity\",\n \"name\": \"Example text similarity grader\",\n \"input\": \"{{sample.output_text}}\",\n \"reference\": \"{{item.label}}\",\n \"pass_threshold\": 0.8,\n \"evaluation_metric\": \"fuzzy_match\"\n}\n" + } + } + ] + }, + "EvalItem": { + "type": "object", + "title": "Eval message object", + "description": "A message input to the model with a role indicating instruction following\nhierarchy. Instructions given with the `developer` or `system` role take\nprecedence over instructions given with the `user` role. Messages with the\n`assistant` role are presumed to have been generated by the model in previous\ninteractions.\n", + "properties": { + "role": { + "type": "string", + "description": "The role of the message input. One of `user`, `assistant`, `system`, or\n`developer`.\n", + "enum": [ + "user", + "assistant", + "system", + "developer" + ] + }, + "content": { + "description": "Inputs to the model - can contain template strings.\n", + "anyOf": [ + { + "type": "string", + "title": "Text input", + "description": "A text input to the model.\n" + }, + { + "$ref": "#/components/schemas/InputTextContent" + }, + { + "type": "object", + "title": "Output text", + "description": "A text output from the model.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the output text. Always `output_text`.\n", + "enum": [ + "output_text" + ], + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text output from the model.\n" + } + }, + "required": [ + "type", + "text" + ] + }, + { + "type": "object", + "title": "Input image", + "description": "An image input to the model.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the image input. Always `input_image`.\n", + "enum": [ + "input_image" + ], + "x-stainless-const": true + }, + "image_url": { + "type": "string", + "description": "The URL of the image input.\n" + }, + "detail": { + "type": "string", + "description": "The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`.\n" + } + }, + "required": [ + "type", + "image_url" + ] + }, + { + "$ref": "#/components/schemas/InputAudio" + }, + { + "type": "array", + "title": "An array of Input text, Input image, and Input audio", + "description": "A list of inputs, each of which may be either an input text, input image, or input audio object.\n" + } + ] + }, + "type": { + "type": "string", + "description": "The type of the message input. Always `message`.\n", + "enum": [ + "message" + ], + "x-stainless-const": true + } + }, + "required": [ + "role", + "content" + ] + }, + "EvalJsonlFileContentSource": { + "type": "object", + "title": "EvalJsonlFileContentSource", + "properties": { + "type": { + "type": "string", + "enum": [ + "file_content" + ], + "default": "file_content", + "description": "The type of jsonl source. Always `file_content`.", + "x-stainless-const": true + }, + "content": { + "type": "array", + "items": { + "type": "object", + "properties": { + "item": { + "type": "object", + "additionalProperties": true + }, + "sample": { + "type": "object", + "additionalProperties": true + } + }, + "required": [ + "item" + ] + }, + "description": "The content of the jsonl file." + } + }, + "required": [ + "type", + "content" + ] + }, + "EvalJsonlFileIdSource": { + "type": "object", + "title": "EvalJsonlFileIdSource", + "properties": { + "type": { + "type": "string", + "enum": [ + "file_id" + ], + "default": "file_id", + "description": "The type of jsonl source. Always `file_id`.", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The identifier of the file." + } + }, + "required": [ + "type", + "id" + ] + }, + "EvalList": { + "type": "object", + "title": "EvalList", + "description": "An object representing a list of evals.\n", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "default": "list", + "description": "The type of this object. It is always set to \"list\".\n", + "x-stainless-const": true + }, + "data": { + "type": "array", + "description": "An array of eval objects.\n", + "items": { + "$ref": "#/components/schemas/Eval" + } + }, + "first_id": { + "type": "string", + "description": "The identifier of the first eval in the data array." + }, + "last_id": { + "type": "string", + "description": "The identifier of the last eval in the data array." + }, + "has_more": { + "type": "boolean", + "description": "Indicates whether there are more evals available." + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ], + "x-oaiMeta": { + "name": "The eval list object", + "group": "evals", + "example": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"eval\",\n \"id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"data_source_config\": {\n \"type\": \"custom\",\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"item\": {\n \"type\": \"object\",\n \"properties\": {\n \"input\": {\n \"type\": \"string\"\n },\n \"ground_truth\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"input\",\n \"ground_truth\"\n ]\n }\n },\n \"required\": [\n \"item\"\n ]\n }\n },\n \"testing_criteria\": [\n {\n \"name\": \"String check\",\n \"id\": \"String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2\",\n \"type\": \"string_check\",\n \"input\": \"{{item.input}}\",\n \"reference\": \"{{item.ground_truth}}\",\n \"operation\": \"eq\"\n }\n ],\n \"name\": \"External Data Eval\",\n \"created_at\": 1739314509,\n \"metadata\": {},\n }\n ],\n \"first_id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"last_id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"has_more\": true\n}\n" + } + }, + "EvalLogsDataSourceConfig": { + "type": "object", + "title": "LogsDataSourceConfig", + "description": "A LogsDataSourceConfig which specifies the metadata property of your logs query.\nThis is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc.\nThe schema returned by this data source config is used to defined what variables are available in your evals.\n`item` and `sample` are both defined when using this data source config.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "logs" + ], + "default": "logs", + "description": "The type of data source. Always `logs`.", + "x-stainless-const": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "schema": { + "type": "object", + "description": "The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n", + "additionalProperties": true + } + }, + "required": [ + "type", + "schema" + ], + "x-oaiMeta": { + "name": "The logs data source object for evals", + "group": "evals", + "example": "{\n \"type\": \"logs\",\n \"metadata\": {\n \"language\": \"english\"\n },\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"item\": {\n \"type\": \"object\"\n },\n \"sample\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"item\",\n \"sample\"\n }\n}\n" + } + }, + "EvalResponsesSource": { + "type": "object", + "title": "EvalResponsesSource", + "description": "A EvalResponsesSource object describing a run data source configuration.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "responses" + ], + "description": "The type of run data source. Always `responses`." + }, + "metadata": { + "type": "object", + "nullable": true, + "description": "Metadata filter for the responses. This is a query parameter used to select responses." + }, + "model": { + "type": "string", + "nullable": true, + "description": "The name of the model to find responses for. This is a query parameter used to select responses." + }, + "instructions_search": { + "type": "string", + "nullable": true, + "description": "Optional string to search the 'instructions' field. This is a query parameter used to select responses." + }, + "created_after": { + "type": "integer", + "minimum": 0, + "nullable": true, + "description": "Only include items created after this timestamp (inclusive). This is a query parameter used to select responses." + }, + "created_before": { + "type": "integer", + "minimum": 0, + "nullable": true, + "description": "Only include items created before this timestamp (inclusive). This is a query parameter used to select responses." + }, + "reasoning_effort": { + "$ref": "#/components/schemas/ReasoningEffort", + "nullable": true, + "description": "Optional reasoning effort parameter. This is a query parameter used to select responses." + }, + "temperature": { + "type": "number", + "nullable": true, + "description": "Sampling temperature. This is a query parameter used to select responses." + }, + "top_p": { + "type": "number", + "nullable": true, + "description": "Nucleus sampling parameter. This is a query parameter used to select responses." + }, + "users": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true, + "description": "List of user identifiers. This is a query parameter used to select responses." + }, + "tools": { + "type": "array", + "items": { + "type": "string" + }, + "nullable": true, + "description": "List of tool names. This is a query parameter used to select responses." + } + }, + "required": [ + "type" + ], + "x-oaiMeta": { + "name": "The run data source object used to configure an individual run", + "group": "eval runs", + "example": "{\n \"type\": \"responses\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"temperature\": 0.7,\n \"top_p\": 1.0,\n \"users\": [\"user1\", \"user2\"],\n \"tools\": [\"tool1\", \"tool2\"],\n \"instructions_search\": \"You are a coding assistant\"\n}\n" + } + }, + "EvalRun": { + "type": "object", + "title": "EvalRun", + "description": "A schema representing an evaluation run.\n", + "properties": { + "object": { + "type": "string", + "enum": [ + "eval.run" + ], + "default": "eval.run", + "description": "The type of the object. Always \"eval.run\".", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "Unique identifier for the evaluation run." + }, + "eval_id": { + "type": "string", + "description": "The identifier of the associated evaluation." + }, + "status": { + "type": "string", + "description": "The status of the evaluation run." + }, + "model": { + "type": "string", + "description": "The model that is evaluated, if applicable." + }, + "name": { + "type": "string", + "description": "The name of the evaluation run." + }, + "created_at": { + "type": "integer", + "description": "Unix timestamp (in seconds) when the evaluation run was created." + }, + "report_url": { + "type": "string", + "description": "The URL to the rendered evaluation run report on the UI dashboard." + }, + "result_counts": { + "type": "object", + "description": "Counters summarizing the outcomes of the evaluation run.", + "properties": { + "total": { + "type": "integer", + "description": "Total number of executed output items." + }, + "errored": { + "type": "integer", + "description": "Number of output items that resulted in an error." + }, + "failed": { + "type": "integer", + "description": "Number of output items that failed to pass the evaluation." + }, + "passed": { + "type": "integer", + "description": "Number of output items that passed the evaluation." + } + }, + "required": [ + "total", + "errored", + "failed", + "passed" + ] + }, + "per_model_usage": { + "type": "array", + "description": "Usage statistics for each model during the evaluation run.", + "items": { + "type": "object", + "properties": { + "model_name": { + "type": "string", + "description": "The name of the model.", + "x-stainless-naming": { + "python": { + "property_name": "run_model_name" + } + } + }, + "invocation_count": { + "type": "integer", + "description": "The number of invocations." + }, + "prompt_tokens": { + "type": "integer", + "description": "The number of prompt tokens used." + }, + "completion_tokens": { + "type": "integer", + "description": "The number of completion tokens generated." + }, + "total_tokens": { + "type": "integer", + "description": "The total number of tokens used." + }, + "cached_tokens": { + "type": "integer", + "description": "The number of tokens retrieved from cache." + } + }, + "required": [ + "model_name", + "invocation_count", + "prompt_tokens", + "completion_tokens", + "total_tokens", + "cached_tokens" + ] + } + }, + "per_testing_criteria_results": { + "type": "array", + "description": "Results per testing criteria applied during the evaluation run.", + "items": { + "type": "object", + "properties": { + "testing_criteria": { + "type": "string", + "description": "A description of the testing criteria." + }, + "passed": { + "type": "integer", + "description": "Number of tests passed for this criteria." + }, + "failed": { + "type": "integer", + "description": "Number of tests failed for this criteria." + } + }, + "required": [ + "testing_criteria", + "passed", + "failed" + ] + } + }, + "data_source": { + "type": "object", + "description": "Information about the run's data source.", + "anyOf": [ + { + "$ref": "#/components/schemas/CreateEvalJsonlRunDataSource" + }, + { + "$ref": "#/components/schemas/CreateEvalCompletionsRunDataSource" + }, + { + "$ref": "#/components/schemas/CreateEvalResponsesRunDataSource" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "error": { + "$ref": "#/components/schemas/EvalApiError" + } + }, + "required": [ + "object", + "id", + "eval_id", + "status", + "model", + "name", + "created_at", + "report_url", + "result_counts", + "per_model_usage", + "per_testing_criteria_results", + "data_source", + "metadata", + "error" + ], + "x-oaiMeta": { + "name": "The eval run object", + "group": "evals", + "example": "{\n \"object\": \"eval.run\",\n \"id\": \"evalrun_67e57965b480819094274e3a32235e4c\",\n \"eval_id\": \"eval_67e579652b548190aaa83ada4b125f47\",\n \"report_url\": \"https://platform.openai.com/evaluations/eval_67e579652b548190aaa83ada4b125f47?run_id=evalrun_67e57965b480819094274e3a32235e4c\",\n \"status\": \"queued\",\n \"model\": \"gpt-4o-mini\",\n \"name\": \"gpt-4o-mini\",\n \"created_at\": 1743092069,\n \"result_counts\": {\n \"total\": 0,\n \"errored\": 0,\n \"failed\": 0,\n \"passed\": 0\n },\n \"per_model_usage\": null,\n \"per_testing_criteria_results\": null,\n \"data_source\": {\n \"type\": \"completions\",\n \"source\": {\n \"type\": \"file_content\",\n \"content\": [\n {\n \"item\": {\n \"input\": \"Tech Company Launches Advanced Artificial Intelligence Platform\",\n \"ground_truth\": \"Technology\"\n }\n },\n {\n \"item\": {\n \"input\": \"Central Bank Increases Interest Rates Amid Inflation Concerns\",\n \"ground_truth\": \"Markets\"\n }\n },\n {\n \"item\": {\n \"input\": \"International Summit Addresses Climate Change Strategies\",\n \"ground_truth\": \"World\"\n }\n },\n {\n \"item\": {\n \"input\": \"Major Retailer Reports Record-Breaking Holiday Sales\",\n \"ground_truth\": \"Business\"\n }\n },\n {\n \"item\": {\n \"input\": \"National Team Qualifies for World Championship Finals\",\n \"ground_truth\": \"Sports\"\n }\n },\n {\n \"item\": {\n \"input\": \"Stock Markets Rally After Positive Economic Data Released\",\n \"ground_truth\": \"Markets\"\n }\n },\n {\n \"item\": {\n \"input\": \"Global Manufacturer Announces Merger with Competitor\",\n \"ground_truth\": \"Business\"\n }\n },\n {\n \"item\": {\n \"input\": \"Breakthrough in Renewable Energy Technology Unveiled\",\n \"ground_truth\": \"Technology\"\n }\n },\n {\n \"item\": {\n \"input\": \"World Leaders Sign Historic Climate Agreement\",\n \"ground_truth\": \"World\"\n }\n },\n {\n \"item\": {\n \"input\": \"Professional Athlete Sets New Record in Championship Event\",\n \"ground_truth\": \"Sports\"\n }\n },\n {\n \"item\": {\n \"input\": \"Financial Institutions Adapt to New Regulatory Requirements\",\n \"ground_truth\": \"Business\"\n }\n },\n {\n \"item\": {\n \"input\": \"Tech Conference Showcases Advances in Artificial Intelligence\",\n \"ground_truth\": \"Technology\"\n }\n },\n {\n \"item\": {\n \"input\": \"Global Markets Respond to Oil Price Fluctuations\",\n \"ground_truth\": \"Markets\"\n }\n },\n {\n \"item\": {\n \"input\": \"International Cooperation Strengthened Through New Treaty\",\n \"ground_truth\": \"World\"\n }\n },\n {\n \"item\": {\n \"input\": \"Sports League Announces Revised Schedule for Upcoming Season\",\n \"ground_truth\": \"Sports\"\n }\n }\n ]\n },\n \"input_messages\": {\n \"type\": \"template\",\n \"template\": [\n {\n \"type\": \"message\",\n \"role\": \"developer\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\\n\\n# Steps\\n\\n1. Analyze the content of the news headline to understand its primary focus.\\n2. Extract the subject matter, identifying any key indicators or keywords.\\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\\n4. Ensure only one category is selected per headline.\\n\\n# Output Format\\n\\nRespond with the chosen category as a single word. For instance: \\\"Technology\\\", \\\"Markets\\\", \\\"World\\\", \\\"Business\\\", or \\\"Sports\\\".\\n\\n# Examples\\n\\n**Input**: \\\"Apple Unveils New iPhone Model, Featuring Advanced AI Features\\\" \\n**Output**: \\\"Technology\\\"\\n\\n**Input**: \\\"Global Stocks Mixed as Investors Await Central Bank Decisions\\\" \\n**Output**: \\\"Markets\\\"\\n\\n**Input**: \\\"War in Ukraine: Latest Updates on Negotiation Status\\\" \\n**Output**: \\\"World\\\"\\n\\n**Input**: \\\"Microsoft in Talks to Acquire Gaming Company for $2 Billion\\\" \\n**Output**: \\\"Business\\\"\\n\\n**Input**: \\\"Manchester United Secures Win in Premier League Football Match\\\" \\n**Output**: \\\"Sports\\\" \\n\\n# Notes\\n\\n- If the headline appears to fit into more than one category, choose the most dominant theme.\\n- Keywords or phrases such as \\\"stocks\\\", \\\"company acquisition\\\", \\\"match\\\", or technological brands can be good indicators for classification.\\n\"\n }\n },\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"{{item.input}}\"\n }\n }\n ]\n },\n \"model\": \"gpt-4o-mini\",\n \"sampling_params\": {\n \"seed\": 42,\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_completions_tokens\": 2048\n }\n },\n \"error\": null,\n \"metadata\": {}\n}\n" + } + }, + "EvalRunList": { + "type": "object", + "title": "EvalRunList", + "description": "An object representing a list of runs for an evaluation.\n", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "default": "list", + "description": "The type of this object. It is always set to \"list\".\n", + "x-stainless-const": true + }, + "data": { + "type": "array", + "description": "An array of eval run objects.\n", + "items": { + "$ref": "#/components/schemas/EvalRun" + } + }, + "first_id": { + "type": "string", + "description": "The identifier of the first eval run in the data array." + }, + "last_id": { + "type": "string", + "description": "The identifier of the last eval run in the data array." + }, + "has_more": { + "type": "boolean", + "description": "Indicates whether there are more evals available." + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ], + "x-oaiMeta": { + "name": "The eval run list object", + "group": "evals", + "example": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"eval.run\",\n \"id\": \"evalrun_67b7fbdad46c819092f6fe7a14189620\",\n \"eval_id\": \"eval_67b7fa9a81a88190ab4aa417e397ea21\",\n \"report_url\": \"https://platform.openai.com/evaluations/eval_67b7fa9a81a88190ab4aa417e397ea21?run_id=evalrun_67b7fbdad46c819092f6fe7a14189620\",\n \"status\": \"completed\",\n \"model\": \"o3-mini\",\n \"name\": \"Academic Assistant\",\n \"created_at\": 1740110812,\n \"result_counts\": {\n \"total\": 171,\n \"errored\": 0,\n \"failed\": 80,\n \"passed\": 91\n },\n \"per_model_usage\": null,\n \"per_testing_criteria_results\": [\n {\n \"testing_criteria\": \"String check grader\",\n \"passed\": 91,\n \"failed\": 80\n }\n ],\n \"run_data_source\": {\n \"type\": \"completions\",\n \"template_messages\": [\n {\n \"type\": \"message\",\n \"role\": \"system\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"You are a helpful assistant.\"\n }\n },\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"Hello, can you help me with my homework?\"\n }\n }\n ],\n \"datasource_reference\": null,\n \"model\": \"o3-mini\",\n \"max_completion_tokens\": null,\n \"seed\": null,\n \"temperature\": null,\n \"top_p\": null\n },\n \"error\": null,\n \"metadata\": {\"test\": \"synthetics\"}\n }\n ],\n \"first_id\": \"evalrun_67abd54d60ec8190832b46859da808f7\",\n \"last_id\": \"evalrun_67abd54d60ec8190832b46859da808f7\",\n \"has_more\": false\n}\n" + } + }, + "EvalRunOutputItem": { + "type": "object", + "title": "EvalRunOutputItem", + "description": "A schema representing an evaluation run output item.\n", + "properties": { + "object": { + "type": "string", + "enum": [ + "eval.run.output_item" + ], + "default": "eval.run.output_item", + "description": "The type of the object. Always \"eval.run.output_item\".", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "Unique identifier for the evaluation run output item." + }, + "run_id": { + "type": "string", + "description": "The identifier of the evaluation run associated with this output item." + }, + "eval_id": { + "type": "string", + "description": "The identifier of the evaluation group." + }, + "created_at": { + "type": "integer", + "description": "Unix timestamp (in seconds) when the evaluation run was created." + }, + "status": { + "type": "string", + "description": "The status of the evaluation run." + }, + "datasource_item_id": { + "type": "integer", + "description": "The identifier for the data source item." + }, + "datasource_item": { + "type": "object", + "description": "Details of the input data source item.", + "additionalProperties": true + }, + "results": { + "type": "array", + "description": "A list of results from the evaluation run.", + "items": { + "type": "object", + "description": "A result object.", + "additionalProperties": true + } + }, + "sample": { + "type": "object", + "description": "A sample containing the input and output of the evaluation run.", + "properties": { + "input": { + "type": "array", + "description": "An array of input messages.", + "items": { + "type": "object", + "description": "An input message.", + "properties": { + "role": { + "type": "string", + "description": "The role of the message sender (e.g., system, user, developer)." + }, + "content": { + "type": "string", + "description": "The content of the message." + } + }, + "required": [ + "role", + "content" + ] + } + }, + "output": { + "type": "array", + "description": "An array of output messages.", + "items": { + "type": "object", + "properties": { + "role": { + "type": "string", + "description": "The role of the message (e.g. \"system\", \"assistant\", \"user\")." + }, + "content": { + "type": "string", + "description": "The content of the message." + } + } + } + }, + "finish_reason": { + "type": "string", + "description": "The reason why the sample generation was finished." + }, + "model": { + "type": "string", + "description": "The model used for generating the sample." + }, + "usage": { + "type": "object", + "description": "Token usage details for the sample.", + "properties": { + "total_tokens": { + "type": "integer", + "description": "The total number of tokens used." + }, + "completion_tokens": { + "type": "integer", + "description": "The number of completion tokens generated." + }, + "prompt_tokens": { + "type": "integer", + "description": "The number of prompt tokens used." + }, + "cached_tokens": { + "type": "integer", + "description": "The number of tokens retrieved from cache." + } + }, + "required": [ + "total_tokens", + "completion_tokens", + "prompt_tokens", + "cached_tokens" + ] + }, + "error": { + "$ref": "#/components/schemas/EvalApiError" + }, + "temperature": { + "type": "number", + "description": "The sampling temperature used." + }, + "max_completion_tokens": { + "type": "integer", + "description": "The maximum number of tokens allowed for completion." + }, + "top_p": { + "type": "number", + "description": "The top_p value used for sampling." + }, + "seed": { + "type": "integer", + "description": "The seed used for generating the sample." + } + }, + "required": [ + "input", + "output", + "finish_reason", + "model", + "usage", + "error", + "temperature", + "max_completion_tokens", + "top_p", + "seed" + ] + } + }, + "required": [ + "object", + "id", + "run_id", + "eval_id", + "created_at", + "status", + "datasource_item_id", + "datasource_item", + "results", + "sample" + ], + "x-oaiMeta": { + "name": "The eval run output item object", + "group": "evals", + "example": "{\n \"object\": \"eval.run.output_item\",\n \"id\": \"outputitem_67abd55eb6548190bb580745d5644a33\",\n \"run_id\": \"evalrun_67abd54d60ec8190832b46859da808f7\",\n \"eval_id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"created_at\": 1739314509,\n \"status\": \"pass\",\n \"datasource_item_id\": 137,\n \"datasource_item\": {\n \"teacher\": \"To grade essays, I only check for style, content, and grammar.\",\n \"student\": \"I am a student who is trying to write the best essay.\"\n },\n \"results\": [\n {\n \"name\": \"String Check Grader\",\n \"type\": \"string-check-grader\",\n \"score\": 1.0,\n \"passed\": true,\n }\n ],\n \"sample\": {\n \"input\": [\n {\n \"role\": \"system\",\n \"content\": \"You are an evaluator bot...\"\n },\n {\n \"role\": \"user\",\n \"content\": \"You are assessing...\"\n }\n ],\n \"output\": [\n {\n \"role\": \"assistant\",\n \"content\": \"The rubric is not clear nor concise.\"\n }\n ],\n \"finish_reason\": \"stop\",\n \"model\": \"gpt-4o-2024-08-06\",\n \"usage\": {\n \"total_tokens\": 521,\n \"completion_tokens\": 2,\n \"prompt_tokens\": 519,\n \"cached_tokens\": 0\n },\n \"error\": null,\n \"temperature\": 1.0,\n \"max_completion_tokens\": 2048,\n \"top_p\": 1.0,\n \"seed\": 42\n }\n}\n" + } + }, + "EvalRunOutputItemList": { + "type": "object", + "title": "EvalRunOutputItemList", + "description": "An object representing a list of output items for an evaluation run.\n", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "default": "list", + "description": "The type of this object. It is always set to \"list\".\n", + "x-stainless-const": true + }, + "data": { + "type": "array", + "description": "An array of eval run output item objects.\n", + "items": { + "$ref": "#/components/schemas/EvalRunOutputItem" + } + }, + "first_id": { + "type": "string", + "description": "The identifier of the first eval run output item in the data array." + }, + "last_id": { + "type": "string", + "description": "The identifier of the last eval run output item in the data array." + }, + "has_more": { + "type": "boolean", + "description": "Indicates whether there are more eval run output items available." + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ], + "x-oaiMeta": { + "name": "The eval run output item list object", + "group": "evals", + "example": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"object\": \"eval.run.output_item\",\n \"id\": \"outputitem_67abd55eb6548190bb580745d5644a33\",\n \"run_id\": \"evalrun_67abd54d60ec8190832b46859da808f7\",\n \"eval_id\": \"eval_67abd54d9b0081909a86353f6fb9317a\",\n \"created_at\": 1739314509,\n \"status\": \"pass\",\n \"datasource_item_id\": 137,\n \"datasource_item\": {\n \"teacher\": \"To grade essays, I only check for style, content, and grammar.\",\n \"student\": \"I am a student who is trying to write the best essay.\"\n },\n \"results\": [\n {\n \"name\": \"String Check Grader\",\n \"type\": \"string-check-grader\",\n \"score\": 1.0,\n \"passed\": true,\n }\n ],\n \"sample\": {\n \"input\": [\n {\n \"role\": \"system\",\n \"content\": \"You are an evaluator bot...\"\n },\n {\n \"role\": \"user\",\n \"content\": \"You are assessing...\"\n }\n ],\n \"output\": [\n {\n \"role\": \"assistant\",\n \"content\": \"The rubric is not clear nor concise.\"\n }\n ],\n \"finish_reason\": \"stop\",\n \"model\": \"gpt-4o-2024-08-06\",\n \"usage\": {\n \"total_tokens\": 521,\n \"completion_tokens\": 2,\n \"prompt_tokens\": 519,\n \"cached_tokens\": 0\n },\n \"error\": null,\n \"temperature\": 1.0,\n \"max_completion_tokens\": 2048,\n \"top_p\": 1.0,\n \"seed\": 42\n }\n },\n ],\n \"first_id\": \"outputitem_67abd55eb6548190bb580745d5644a33\",\n \"last_id\": \"outputitem_67abd55eb6548190bb580745d5644a33\",\n \"has_more\": false\n}\n" + } + }, + "EvalStoredCompletionsDataSourceConfig": { + "type": "object", + "title": "StoredCompletionsDataSourceConfig", + "description": "Deprecated in favor of LogsDataSourceConfig.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "stored_completions" + ], + "default": "stored_completions", + "description": "The type of data source. Always `stored_completions`.", + "x-stainless-const": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "schema": { + "type": "object", + "description": "The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n", + "additionalProperties": true + } + }, + "required": [ + "type", + "schema" + ], + "deprecated": true, + "x-oaiMeta": { + "name": "The stored completions data source object for evals", + "group": "evals", + "example": "{\n \"type\": \"stored_completions\",\n \"metadata\": {\n \"language\": \"english\"\n },\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"item\": {\n \"type\": \"object\"\n },\n \"sample\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"item\",\n \"sample\"\n }\n}\n" + } + }, + "EvalStoredCompletionsSource": { + "type": "object", + "title": "StoredCompletionsRunDataSource", + "description": "A StoredCompletionsRunDataSource configuration describing a set of filters\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "stored_completions" + ], + "default": "stored_completions", + "description": "The type of source. Always `stored_completions`.", + "x-stainless-const": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "model": { + "type": "string", + "nullable": true, + "description": "An optional model to filter by (e.g., 'gpt-4o')." + }, + "created_after": { + "type": "integer", + "nullable": true, + "description": "An optional Unix timestamp to filter items created after this time." + }, + "created_before": { + "type": "integer", + "nullable": true, + "description": "An optional Unix timestamp to filter items created before this time." + }, + "limit": { + "type": "integer", + "nullable": true, + "description": "An optional maximum number of items to return." + } + }, + "required": [ + "type" + ], + "x-oaiMeta": { + "name": "The stored completions data source object used to configure an individual run", + "group": "eval runs", + "example": "{\n \"type\": \"stored_completions\",\n \"model\": \"gpt-4o\",\n \"created_after\": 1668124800,\n \"created_before\": 1668124900,\n \"limit\": 100,\n \"metadata\": {}\n}\n" + } + }, + "FileExpirationAfter": { + "type": "object", + "title": "File expiration policy", + "description": "The expiration policy for a file. By default, files with `purpose=batch` expire after 30 days and all other files are persisted until they are manually deleted.", + "properties": { + "anchor": { + "description": "Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`.", + "type": "string", + "enum": [ + "created_at" + ], + "x-stainless-const": true + }, + "seconds": { + "description": "The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days).", + "type": "integer", + "minimum": 3600, + "maximum": 2592000 + } + }, + "required": [ + "anchor", + "seconds" + ] + }, + "FilePath": { + "type": "object", + "title": "File path", + "description": "A path to a file.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the file path. Always `file_path`.\n", + "enum": [ + "file_path" + ], + "x-stainless-const": true + }, + "file_id": { + "type": "string", + "description": "The ID of the file.\n" + }, + "index": { + "type": "integer", + "description": "The index of the file in the list of files.\n" + } + }, + "required": [ + "type", + "file_id", + "index" + ] + }, + "FileSearchRanker": { + "type": "string", + "description": "The ranker to use for the file search. If not specified will use the `auto` ranker.", + "enum": [ + "auto", + "default_2024_08_21" + ] + }, + "FileSearchRankingOptions": { + "title": "File search tool call ranking options", + "type": "object", + "description": "The ranking options for the file search. If not specified, the file search tool will use the `auto` ranker and a score_threshold of 0.\n\nSee the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n", + "properties": { + "ranker": { + "$ref": "#/components/schemas/FileSearchRanker" + }, + "score_threshold": { + "type": "number", + "description": "The score threshold for the file search. All values must be a floating point number between 0 and 1.", + "minimum": 0, + "maximum": 1 + } + }, + "required": [ + "score_threshold" + ] + }, + "FileSearchToolCall": { + "type": "object", + "title": "File search tool call", + "description": "The results of a file search tool call. See the \n[file search guide](https://platform.openai.com/docs/guides/tools-file-search) for more information.\n", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the file search tool call.\n" + }, + "type": { + "type": "string", + "enum": [ + "file_search_call" + ], + "description": "The type of the file search tool call. Always `file_search_call`.\n", + "x-stainless-const": true + }, + "status": { + "type": "string", + "description": "The status of the file search tool call. One of `in_progress`, \n`searching`, `incomplete` or `failed`,\n", + "enum": [ + "in_progress", + "searching", + "completed", + "incomplete", + "failed" + ] + }, + "queries": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The queries used to search for files.\n" + }, + "results": { + "type": "array", + "description": "The results of the file search tool call.\n", + "items": { + "type": "object", + "properties": { + "file_id": { + "type": "string", + "description": "The unique ID of the file.\n" + }, + "text": { + "type": "string", + "description": "The text that was retrieved from the file.\n" + }, + "filename": { + "type": "string", + "description": "The name of the file.\n" + }, + "attributes": { + "$ref": "#/components/schemas/VectorStoreFileAttributes" + }, + "score": { + "type": "number", + "format": "float", + "description": "The relevance score of the file - a value between 0 and 1.\n" + } + } + }, + "nullable": true + } + }, + "required": [ + "id", + "type", + "status", + "queries" + ] + }, + "FineTuneChatCompletionRequestAssistantMessage": { + "allOf": [ + { + "type": "object", + "title": "Assistant message", + "deprecated": false, + "properties": { + "weight": { + "type": "integer", + "enum": [ + 0, + 1 + ], + "description": "Controls whether the assistant message is trained against (0 or 1)" + } + } + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestAssistantMessage" + } + ], + "required": [ + "role" + ] + }, + "FineTuneChatRequestInput": { + "type": "object", + "description": "The per-line training example of a fine-tuning input file for chat models using the supervised method.\nInput messages may contain text or image content only. Audio and file input messages\nare not currently supported for fine-tuning.\n", + "properties": { + "messages": { + "type": "array", + "minItems": 1, + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestSystemMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestUserMessage" + }, + { + "$ref": "#/components/schemas/FineTuneChatCompletionRequestAssistantMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestToolMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestFunctionMessage" + } + ] + } + }, + "tools": { + "type": "array", + "description": "A list of tools the model may generate JSON inputs for.", + "items": { + "$ref": "#/components/schemas/ChatCompletionTool" + } + }, + "parallel_tool_calls": { + "$ref": "#/components/schemas/ParallelToolCalls" + }, + "functions": { + "deprecated": true, + "description": "A list of functions the model may generate JSON inputs for.", + "type": "array", + "minItems": 1, + "maxItems": 128, + "items": { + "$ref": "#/components/schemas/ChatCompletionFunctions" + } + } + }, + "x-oaiMeta": { + "name": "Training format for chat models using the supervised method", + "example": "{\n \"messages\": [\n { \"role\": \"user\", \"content\": \"What is the weather in San Francisco?\" },\n {\n \"role\": \"assistant\",\n \"tool_calls\": [\n {\n \"id\": \"call_id\",\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_current_weather\",\n \"arguments\": \"{\\\"location\\\": \\\"San Francisco, USA\\\", \\\"format\\\": \\\"celsius\\\"}\"\n }\n }\n ]\n }\n ],\n \"parallel_tool_calls\": false,\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_current_weather\",\n \"description\": \"Get the current weather\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and country, eg. San Francisco, USA\"\n },\n \"format\": { \"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"] }\n },\n \"required\": [\"location\", \"format\"]\n }\n }\n }\n ]\n}\n" + } + }, + "FineTuneDPOHyperparameters": { + "type": "object", + "description": "The hyperparameters used for the DPO fine-tuning job.", + "properties": { + "beta": { + "description": "The beta value for the DPO method. A higher beta value will increase the weight of the penalty between the policy and reference model.\n", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "number", + "minimum": 0, + "maximum": 2, + "exclusiveMinimum": true + } + ] + }, + "batch_size": { + "description": "Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "integer", + "minimum": 1, + "maximum": 256 + } + ] + }, + "learning_rate_multiplier": { + "description": "Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + } + ] + }, + "n_epochs": { + "description": "The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "integer", + "minimum": 1, + "maximum": 50 + } + ] + } + } + }, + "FineTuneDPOMethod": { + "type": "object", + "description": "Configuration for the DPO fine-tuning method.", + "properties": { + "hyperparameters": { + "$ref": "#/components/schemas/FineTuneDPOHyperparameters" + } + } + }, + "FineTuneMethod": { + "type": "object", + "description": "The method used for fine-tuning.", + "properties": { + "type": { + "type": "string", + "description": "The type of method. Is either `supervised`, `dpo`, or `reinforcement`.", + "enum": [ + "supervised", + "dpo", + "reinforcement" + ] + }, + "supervised": { + "$ref": "#/components/schemas/FineTuneSupervisedMethod" + }, + "dpo": { + "$ref": "#/components/schemas/FineTuneDPOMethod" + }, + "reinforcement": { + "$ref": "#/components/schemas/FineTuneReinforcementMethod" + } + }, + "required": [ + "type" + ] + }, + "FineTunePreferenceRequestInput": { + "type": "object", + "description": "The per-line training example of a fine-tuning input file for chat models using the dpo method.\nInput messages may contain text or image content only. Audio and file input messages\nare not currently supported for fine-tuning.\n", + "properties": { + "input": { + "type": "object", + "properties": { + "messages": { + "type": "array", + "minItems": 1, + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestSystemMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestUserMessage" + }, + { + "$ref": "#/components/schemas/FineTuneChatCompletionRequestAssistantMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestToolMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestFunctionMessage" + } + ] + } + }, + "tools": { + "type": "array", + "description": "A list of tools the model may generate JSON inputs for.", + "items": { + "$ref": "#/components/schemas/ChatCompletionTool" + } + }, + "parallel_tool_calls": { + "$ref": "#/components/schemas/ParallelToolCalls" + } + } + }, + "preferred_output": { + "type": "array", + "description": "The preferred completion message for the output.", + "maxItems": 1, + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestAssistantMessage" + } + ] + } + }, + "non_preferred_output": { + "type": "array", + "description": "The non-preferred completion message for the output.", + "maxItems": 1, + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestAssistantMessage" + } + ] + } + } + }, + "x-oaiMeta": { + "name": "Training format for chat models using the preference method", + "example": "{\n \"input\": {\n \"messages\": [\n { \"role\": \"user\", \"content\": \"What is the weather in San Francisco?\" }\n ]\n },\n \"preferred_output\": [\n {\n \"role\": \"assistant\",\n \"content\": \"The weather in San Francisco is 70 degrees Fahrenheit.\"\n }\n ],\n \"non_preferred_output\": [\n {\n \"role\": \"assistant\",\n \"content\": \"The weather in San Francisco is 21 degrees Celsius.\"\n }\n ]\n}\n" + } + }, + "FineTuneReinforcementHyperparameters": { + "type": "object", + "description": "The hyperparameters used for the reinforcement fine-tuning job.", + "properties": { + "batch_size": { + "description": "Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "integer", + "minimum": 1, + "maximum": 256 + } + ] + }, + "learning_rate_multiplier": { + "description": "Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + } + ] + }, + "n_epochs": { + "description": "The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "integer", + "minimum": 1, + "maximum": 50 + } + ] + }, + "reasoning_effort": { + "description": "Level of reasoning effort.\n", + "type": "string", + "enum": [ + "default", + "low", + "medium", + "high" + ], + "default": "default" + }, + "compute_multiplier": { + "description": "Multiplier on amount of compute used for exploring search space during training.\n", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "number", + "minimum": 0.00001, + "maximum": 10, + "exclusiveMinimum": true + } + ] + }, + "eval_interval": { + "description": "The number of training steps between evaluation runs.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "integer", + "minimum": 1 + } + ] + }, + "eval_samples": { + "description": "Number of evaluation samples to generate per training step.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "integer", + "minimum": 1 + } + ] + } + } + }, + "FineTuneReinforcementMethod": { + "type": "object", + "description": "Configuration for the reinforcement fine-tuning method.", + "properties": { + "grader": { + "type": "object", + "description": "The grader used for the fine-tuning job.", + "anyOf": [ + { + "$ref": "#/components/schemas/GraderStringCheck" + }, + { + "$ref": "#/components/schemas/GraderTextSimilarity" + }, + { + "$ref": "#/components/schemas/GraderPython" + }, + { + "$ref": "#/components/schemas/GraderScoreModel" + }, + { + "$ref": "#/components/schemas/GraderMulti" + } + ] + }, + "hyperparameters": { + "$ref": "#/components/schemas/FineTuneReinforcementHyperparameters" + } + }, + "required": [ + "grader" + ] + }, + "FineTuneReinforcementRequestInput": { + "type": "object", + "unevaluatedProperties": true, + "description": "Per-line training example for reinforcement fine-tuning. Note that `messages` and `tools` are the only reserved keywords.\nAny other arbitrary key-value data can be included on training datapoints and will be available to reference during grading under the `{{ item.XXX }}` template variable.\nInput messages may contain text or image content only. Audio and file input messages\nare not currently supported for fine-tuning.\n", + "required": [ + "messages" + ], + "properties": { + "messages": { + "type": "array", + "minItems": 1, + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChatCompletionRequestDeveloperMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestUserMessage" + }, + { + "$ref": "#/components/schemas/FineTuneChatCompletionRequestAssistantMessage" + }, + { + "$ref": "#/components/schemas/ChatCompletionRequestToolMessage" + } + ] + } + }, + "tools": { + "type": "array", + "description": "A list of tools the model may generate JSON inputs for.", + "items": { + "$ref": "#/components/schemas/ChatCompletionTool" + } + } + }, + "x-oaiMeta": { + "name": "Training format for reasoning models using the reinforcement method", + "example": "{\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Your task is to take a chemical in SMILES format and predict the number of hydrobond bond donors and acceptors according to Lipinkski's rule. CCN(CC)CCC(=O)c1sc(N)nc1C\"\n },\n ],\n \"reference_answer\": {\n \"donor_bond_counts\": 5,\n \"acceptor_bond_counts\": 7\n }\n}\n" + } + }, + "FineTuneSupervisedHyperparameters": { + "type": "object", + "description": "The hyperparameters used for the fine-tuning job.", + "properties": { + "batch_size": { + "description": "Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "integer", + "minimum": 1, + "maximum": 256 + } + ] + }, + "learning_rate_multiplier": { + "description": "Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + } + ] + }, + "n_epochs": { + "description": "The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "integer", + "minimum": 1, + "maximum": 50 + } + ] + } + } + }, + "FineTuneSupervisedMethod": { + "type": "object", + "description": "Configuration for the supervised fine-tuning method.", + "properties": { + "hyperparameters": { + "$ref": "#/components/schemas/FineTuneSupervisedHyperparameters" + } + } + }, + "FineTuningCheckpointPermission": { + "type": "object", + "title": "FineTuningCheckpointPermission", + "description": "The `checkpoint.permission` object represents a permission for a fine-tuned model checkpoint.\n", + "properties": { + "id": { + "type": "string", + "description": "The permission identifier, which can be referenced in the API endpoints." + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the permission was created." + }, + "project_id": { + "type": "string", + "description": "The project identifier that the permission is for." + }, + "object": { + "type": "string", + "description": "The object type, which is always \"checkpoint.permission\".", + "enum": [ + "checkpoint.permission" + ], + "x-stainless-const": true + } + }, + "required": [ + "created_at", + "id", + "object", + "project_id" + ], + "x-oaiMeta": { + "name": "The fine-tuned model checkpoint permission object", + "example": "{\n \"object\": \"checkpoint.permission\",\n \"id\": \"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n \"created_at\": 1712211699,\n \"project_id\": \"proj_abGMw1llN8IrBb6SvvY5A1iH\"\n}\n" + } + }, + "FineTuningIntegration": { + "type": "object", + "title": "Fine-Tuning Job Integration", + "required": [ + "type", + "wandb" + ], + "properties": { + "type": { + "type": "string", + "description": "The type of the integration being enabled for the fine-tuning job", + "enum": [ + "wandb" + ], + "x-stainless-const": true + }, + "wandb": { + "type": "object", + "description": "The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n", + "required": [ + "project" + ], + "properties": { + "project": { + "description": "The name of the project that the new run will be created under.\n", + "type": "string", + "example": "my-wandb-project" + }, + "name": { + "description": "A display name to set for the run. If not set, we will use the Job ID as the name.\n", + "nullable": true, + "type": "string" + }, + "entity": { + "description": "The entity to use for the run. This allows you to set the team or username of the WandB user that you would\nlike associated with the run. If not set, the default entity for the registered WandB API key is used.\n", + "nullable": true, + "type": "string" + }, + "tags": { + "description": "A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\ndefault tags are generated by OpenAI: \"openai/finetune\", \"openai/{base-model}\", \"openai/{ftjob-abcdef}\".\n", + "type": "array", + "items": { + "type": "string", + "example": "custom-tag" + } + } + } + } + } + }, + "FineTuningJob": { + "type": "object", + "title": "FineTuningJob", + "description": "The `fine_tuning.job` object represents a fine-tuning job that has been created through the API.\n", + "properties": { + "id": { + "type": "string", + "description": "The object identifier, which can be referenced in the API endpoints." + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the fine-tuning job was created." + }, + "error": { + "type": "object", + "nullable": true, + "description": "For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure.", + "properties": { + "code": { + "type": "string", + "description": "A machine-readable error code." + }, + "message": { + "type": "string", + "description": "A human-readable error message." + }, + "param": { + "type": "string", + "description": "The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific.", + "nullable": true + } + }, + "required": [ + "code", + "message", + "param" + ] + }, + "fine_tuned_model": { + "type": "string", + "nullable": true, + "description": "The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running." + }, + "finished_at": { + "type": "integer", + "nullable": true, + "description": "The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running." + }, + "hyperparameters": { + "type": "object", + "description": "The hyperparameters used for the fine-tuning job. This value will only be returned when running `supervised` jobs.", + "properties": { + "batch_size": { + "nullable": true, + "description": "Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true, + "title": "Auto" + }, + { + "type": "integer", + "minimum": 1, + "maximum": 256, + "title": "Manual" + } + ] + }, + "learning_rate_multiplier": { + "description": "Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true, + "title": "Auto" + }, + { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + } + ] + }, + "n_epochs": { + "description": "The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n", + "default": "auto", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "x-stainless-const": true, + "title": "Auto" + }, + { + "type": "integer", + "minimum": 1, + "maximum": 50 + } + ] + } + } + }, + "model": { + "type": "string", + "description": "The base model that is being fine-tuned." + }, + "object": { + "type": "string", + "description": "The object type, which is always \"fine_tuning.job\".", + "enum": [ + "fine_tuning.job" + ], + "x-stainless-const": true + }, + "organization_id": { + "type": "string", + "description": "The organization that owns the fine-tuning job." + }, + "result_files": { + "type": "array", + "description": "The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents).", + "items": { + "type": "string", + "example": "file-abc123" + } + }, + "status": { + "type": "string", + "description": "The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`.", + "enum": [ + "validating_files", + "queued", + "running", + "succeeded", + "failed", + "cancelled" + ] + }, + "trained_tokens": { + "type": "integer", + "nullable": true, + "description": "The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running." + }, + "training_file": { + "type": "string", + "description": "The file ID used for training. You can retrieve the training data with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents)." + }, + "validation_file": { + "type": "string", + "nullable": true, + "description": "The file ID used for validation. You can retrieve the validation results with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents)." + }, + "integrations": { + "type": "array", + "nullable": true, + "description": "A list of integrations to enable for this fine-tuning job.", + "maxItems": 5, + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/FineTuningIntegration" + } + ], + "discriminator": { + "propertyName": "type" + } + } + }, + "seed": { + "type": "integer", + "description": "The seed used for the fine-tuning job." + }, + "estimated_finish": { + "type": "integer", + "nullable": true, + "description": "The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value will be null if the fine-tuning job is not running." + }, + "method": { + "$ref": "#/components/schemas/FineTuneMethod" + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + }, + "required": [ + "created_at", + "error", + "finished_at", + "fine_tuned_model", + "hyperparameters", + "id", + "model", + "object", + "organization_id", + "result_files", + "status", + "trained_tokens", + "training_file", + "validation_file", + "seed" + ], + "x-oaiMeta": { + "name": "The fine-tuning job object", + "example": "{\n \"object\": \"fine_tuning.job\",\n \"id\": \"ftjob-abc123\",\n \"model\": \"davinci-002\",\n \"created_at\": 1692661014,\n \"finished_at\": 1692661190,\n \"fine_tuned_model\": \"ft:davinci-002:my-org:custom_suffix:7q8mpxmy\",\n \"organization_id\": \"org-123\",\n \"result_files\": [\n \"file-abc123\"\n ],\n \"status\": \"succeeded\",\n \"validation_file\": null,\n \"training_file\": \"file-abc123\",\n \"hyperparameters\": {\n \"n_epochs\": 4,\n \"batch_size\": 1,\n \"learning_rate_multiplier\": 1.0\n },\n \"trained_tokens\": 5768,\n \"integrations\": [],\n \"seed\": 0,\n \"estimated_finish\": 0,\n \"method\": {\n \"type\": \"supervised\",\n \"supervised\": {\n \"hyperparameters\": {\n \"n_epochs\": 4,\n \"batch_size\": 1,\n \"learning_rate_multiplier\": 1.0\n }\n }\n },\n \"metadata\": {\n \"key\": \"value\"\n }\n}\n" + } + }, + "FineTuningJobCheckpoint": { + "type": "object", + "title": "FineTuningJobCheckpoint", + "description": "The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that is ready to use.\n", + "properties": { + "id": { + "type": "string", + "description": "The checkpoint identifier, which can be referenced in the API endpoints." + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the checkpoint was created." + }, + "fine_tuned_model_checkpoint": { + "type": "string", + "description": "The name of the fine-tuned checkpoint model that is created." + }, + "step_number": { + "type": "integer", + "description": "The step number that the checkpoint was created at." + }, + "metrics": { + "type": "object", + "description": "Metrics at the step number during the fine-tuning job.", + "properties": { + "step": { + "type": "number" + }, + "train_loss": { + "type": "number" + }, + "train_mean_token_accuracy": { + "type": "number" + }, + "valid_loss": { + "type": "number" + }, + "valid_mean_token_accuracy": { + "type": "number" + }, + "full_valid_loss": { + "type": "number" + }, + "full_valid_mean_token_accuracy": { + "type": "number" + } + } + }, + "fine_tuning_job_id": { + "type": "string", + "description": "The name of the fine-tuning job that this checkpoint was created from." + }, + "object": { + "type": "string", + "description": "The object type, which is always \"fine_tuning.job.checkpoint\".", + "enum": [ + "fine_tuning.job.checkpoint" + ], + "x-stainless-const": true + } + }, + "required": [ + "created_at", + "fine_tuning_job_id", + "fine_tuned_model_checkpoint", + "id", + "metrics", + "object", + "step_number" + ], + "x-oaiMeta": { + "name": "The fine-tuning job checkpoint object", + "example": "{\n \"object\": \"fine_tuning.job.checkpoint\",\n \"id\": \"ftckpt_qtZ5Gyk4BLq1SfLFWp3RtO3P\",\n \"created_at\": 1712211699,\n \"fine_tuned_model_checkpoint\": \"ft:gpt-4o-mini-2024-07-18:my-org:custom_suffix:9ABel2dg:ckpt-step-88\",\n \"fine_tuning_job_id\": \"ftjob-fpbNQ3H1GrMehXRf8cO97xTN\",\n \"metrics\": {\n \"step\": 88,\n \"train_loss\": 0.478,\n \"train_mean_token_accuracy\": 0.924,\n \"valid_loss\": 10.112,\n \"valid_mean_token_accuracy\": 0.145,\n \"full_valid_loss\": 0.567,\n \"full_valid_mean_token_accuracy\": 0.944\n },\n \"step_number\": 88\n}\n" + } + }, + "FineTuningJobEvent": { + "type": "object", + "description": "Fine-tuning job event object", + "properties": { + "object": { + "type": "string", + "description": "The object type, which is always \"fine_tuning.job.event\".", + "enum": [ + "fine_tuning.job.event" + ], + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The object identifier." + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the fine-tuning job was created." + }, + "level": { + "type": "string", + "description": "The log level of the event.", + "enum": [ + "info", + "warn", + "error" + ] + }, + "message": { + "type": "string", + "description": "The message of the event." + }, + "type": { + "type": "string", + "description": "The type of event.", + "enum": [ + "message", + "metrics" + ] + }, + "data": { + "type": "object", + "description": "The data associated with the event." + } + }, + "required": [ + "id", + "object", + "created_at", + "level", + "message" + ], + "x-oaiMeta": { + "name": "The fine-tuning job event object", + "example": "{\n \"object\": \"fine_tuning.job.event\",\n \"id\": \"ftevent-abc123\"\n \"created_at\": 1677610602,\n \"level\": \"info\",\n \"message\": \"Created fine-tuning job\",\n \"data\": {},\n \"type\": \"message\"\n}\n" + } + }, + "FunctionObject": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A description of what the function does, used by the model to choose when and how to call the function." + }, + "name": { + "type": "string", + "description": "The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64." + }, + "parameters": { + "$ref": "#/components/schemas/FunctionParameters" + }, + "strict": { + "type": "boolean", + "nullable": true, + "default": false, + "description": "Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](https://platform.openai.com/docs/guides/function-calling)." + } + }, + "required": [ + "name" + ] + }, + "FunctionParameters": { + "type": "object", + "description": "The parameters the functions accepts, described as a JSON Schema object. See the [guide](https://platform.openai.com/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.\n\nOmitting `parameters` defines a function with an empty parameter list.", + "additionalProperties": true + }, + "FunctionToolCall": { + "type": "object", + "title": "Function tool call", + "description": "A tool call to run a function. See the\n[function calling guide](https://platform.openai.com/docs/guides/function-calling) for more information.\n", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the function tool call.\n" + }, + "type": { + "type": "string", + "enum": [ + "function_call" + ], + "description": "The type of the function tool call. Always `function_call`.\n", + "x-stainless-const": true + }, + "call_id": { + "type": "string", + "description": "The unique ID of the function tool call generated by the model.\n" + }, + "name": { + "type": "string", + "description": "The name of the function to run.\n" + }, + "arguments": { + "type": "string", + "description": "A JSON string of the arguments to pass to the function.\n" + }, + "status": { + "type": "string", + "description": "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n", + "enum": [ + "in_progress", + "completed", + "incomplete" + ] + } + }, + "required": [ + "type", + "call_id", + "name", + "arguments" + ] + }, + "FunctionToolCallOutput": { + "type": "object", + "title": "Function tool call output", + "description": "The output of a function tool call.\n", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the function tool call output. Populated when this item\nis returned via API.\n" + }, + "type": { + "type": "string", + "enum": [ + "function_call_output" + ], + "description": "The type of the function tool call output. Always `function_call_output`.\n", + "x-stainless-const": true + }, + "call_id": { + "type": "string", + "description": "The unique ID of the function tool call generated by the model.\n" + }, + "output": { + "type": "string", + "description": "A JSON string of the output of the function tool call.\n" + }, + "status": { + "type": "string", + "description": "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n", + "enum": [ + "in_progress", + "completed", + "incomplete" + ] + } + }, + "required": [ + "type", + "call_id", + "output" + ] + }, + "FunctionToolCallOutputResource": { + "allOf": [ + { + "$ref": "#/components/schemas/FunctionToolCallOutput" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the function call tool output.\n" + } + }, + "required": [ + "id" + ] + } + ] + }, + "FunctionToolCallResource": { + "allOf": [ + { + "$ref": "#/components/schemas/FunctionToolCall" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the function tool call.\n" + } + }, + "required": [ + "id" + ] + } + ] + }, + "GraderLabelModel": { + "type": "object", + "title": "LabelModelGrader", + "description": "A LabelModelGrader object which uses a model to assign labels to each item\nin the evaluation.\n", + "properties": { + "type": { + "description": "The object type, which is always `label_model`.", + "type": "string", + "enum": [ + "label_model" + ], + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the grader." + }, + "model": { + "type": "string", + "description": "The model to use for the evaluation. Must support structured outputs." + }, + "input": { + "type": "array", + "items": { + "$ref": "#/components/schemas/EvalItem" + } + }, + "labels": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The labels to assign to each item in the evaluation." + }, + "passing_labels": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The labels that indicate a passing result. Must be a subset of labels." + } + }, + "required": [ + "type", + "model", + "input", + "passing_labels", + "labels", + "name" + ], + "x-oaiMeta": { + "name": "Label Model Grader", + "group": "graders", + "example": "{\n \"name\": \"First label grader\",\n \"type\": \"label_model\",\n \"model\": \"gpt-4o-2024-08-06\",\n \"input\": [\n {\n \"type\": \"message\",\n \"role\": \"system\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"Classify the sentiment of the following statement as one of positive, neutral, or negative\"\n }\n },\n {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": {\n \"type\": \"input_text\",\n \"text\": \"Statement: {{item.response}}\"\n }\n }\n ],\n \"passing_labels\": [\n \"positive\"\n ],\n \"labels\": [\n \"positive\",\n \"neutral\",\n \"negative\"\n ]\n}\n" + } + }, + "GraderMulti": { + "type": "object", + "title": "MultiGrader", + "description": "A MultiGrader object combines the output of multiple graders to produce a single score.", + "properties": { + "type": { + "type": "string", + "enum": [ + "multi" + ], + "default": "multi", + "description": "The object type, which is always `multi`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the grader." + }, + "graders": { + "anyOf": [ + { + "$ref": "#/components/schemas/GraderStringCheck" + }, + { + "$ref": "#/components/schemas/GraderTextSimilarity" + }, + { + "$ref": "#/components/schemas/GraderPython" + }, + { + "$ref": "#/components/schemas/GraderScoreModel" + }, + { + "$ref": "#/components/schemas/GraderLabelModel" + } + ] + }, + "calculate_output": { + "type": "string", + "description": "A formula to calculate the output based on grader results." + } + }, + "required": [ + "name", + "type", + "graders", + "calculate_output" + ], + "x-oaiMeta": { + "name": "Multi Grader", + "group": "graders", + "example": "{\n \"type\": \"multi\",\n \"name\": \"example multi grader\",\n \"graders\": [\n {\n \"type\": \"text_similarity\",\n \"name\": \"example text similarity grader\",\n \"input\": \"The graded text\",\n \"reference\": \"The reference text\",\n \"evaluation_metric\": \"fuzzy_match\"\n },\n {\n \"type\": \"string_check\",\n \"name\": \"Example string check grader\",\n \"input\": \"{{sample.output_text}}\",\n \"reference\": \"{{item.label}}\",\n \"operation\": \"eq\"\n }\n ],\n \"calculate_output\": \"0.5 * text_similarity_score + 0.5 * string_check_score)\"\n}\n" + } + }, + "GraderPython": { + "type": "object", + "title": "PythonGrader", + "description": "A PythonGrader object that runs a python script on the input.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "python" + ], + "description": "The object type, which is always `python`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the grader." + }, + "source": { + "type": "string", + "description": "The source code of the python script." + }, + "image_tag": { + "type": "string", + "description": "The image tag to use for the python script." + } + }, + "required": [ + "type", + "name", + "source" + ], + "x-oaiMeta": { + "name": "Python Grader", + "group": "graders", + "example": "{\n \"type\": \"python\",\n \"name\": \"Example python grader\",\n \"image_tag\": \"2025-05-08\",\n \"source\": \"\"\"\ndef grade(sample: dict, item: dict) -> float:\n \\\"\"\"\n Returns 1.0 if `output_text` equals `label`, otherwise 0.0.\n \\\"\"\"\n output = sample.get(\"output_text\")\n label = item.get(\"label\")\n return 1.0 if output == label else 0.0\n\"\"\",\n}\n" + } + }, + "GraderScoreModel": { + "type": "object", + "title": "ScoreModelGrader", + "description": "A ScoreModelGrader object that uses a model to assign a score to the input.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "score_model" + ], + "description": "The object type, which is always `score_model`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the grader." + }, + "model": { + "type": "string", + "description": "The model to use for the evaluation." + }, + "sampling_params": { + "type": "object", + "description": "The sampling parameters for the model." + }, + "input": { + "type": "array", + "items": { + "$ref": "#/components/schemas/EvalItem" + }, + "description": "The input text. This may include template strings." + }, + "range": { + "type": "array", + "items": { + "type": "number", + "min_items": 2, + "max_items": 2 + }, + "description": "The range of the score. Defaults to `[0, 1]`." + } + }, + "required": [ + "type", + "name", + "input", + "model" + ], + "x-oaiMeta": { + "name": "Score Model Grader", + "group": "graders", + "example": "{\n \"type\": \"score_model\",\n \"name\": \"Example score model grader\",\n \"input\": [\n {\n \"role\": \"user\",\n \"content\": (\n \"Score how close the reference answer is to the model answer. Score 1.0 if they are the same and 0.0 if they are different.\"\n \" Return just a floating point score\\n\\n\"\n \" Reference answer: {{item.label}}\\n\\n\"\n \" Model answer: {{sample.output_text}}\"\n ),\n }\n ],\n \"model\": \"gpt-4o-2024-08-06\",\n \"sampling_params\": {\n \"temperature\": 1,\n \"top_p\": 1,\n \"seed\": 42,\n },\n}\n" + } + }, + "GraderStringCheck": { + "type": "object", + "title": "StringCheckGrader", + "description": "A StringCheckGrader object that performs a string comparison between input and reference using a specified operation.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "string_check" + ], + "description": "The object type, which is always `string_check`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the grader." + }, + "input": { + "type": "string", + "description": "The input text. This may include template strings." + }, + "reference": { + "type": "string", + "description": "The reference text. This may include template strings." + }, + "operation": { + "type": "string", + "enum": [ + "eq", + "ne", + "like", + "ilike" + ], + "description": "The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`." + } + }, + "required": [ + "type", + "name", + "input", + "reference", + "operation" + ], + "x-oaiMeta": { + "name": "String Check Grader", + "group": "graders", + "example": "{\n \"type\": \"string_check\",\n \"name\": \"Example string check grader\",\n \"input\": \"{{sample.output_text}}\",\n \"reference\": \"{{item.label}}\",\n \"operation\": \"eq\"\n}\n" + } + }, + "GraderTextSimilarity": { + "type": "object", + "title": "TextSimilarityGrader", + "description": "A TextSimilarityGrader object which grades text based on similarity metrics.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "text_similarity" + ], + "default": "text_similarity", + "description": "The type of grader.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the grader." + }, + "input": { + "type": "string", + "description": "The text being graded." + }, + "reference": { + "type": "string", + "description": "The text being graded against." + }, + "evaluation_metric": { + "type": "string", + "enum": [ + "cosine", + "fuzzy_match", + "bleu", + "gleu", + "meteor", + "rouge_1", + "rouge_2", + "rouge_3", + "rouge_4", + "rouge_5", + "rouge_l" + ], + "description": "The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, \n`gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, \nor `rouge_l`.\n" + } + }, + "required": [ + "type", + "name", + "input", + "reference", + "evaluation_metric" + ], + "x-oaiMeta": { + "name": "Text Similarity Grader", + "group": "graders", + "example": "{\n \"type\": \"text_similarity\",\n \"name\": \"Example text similarity grader\",\n \"input\": \"{{sample.output_text}}\",\n \"reference\": \"{{item.label}}\",\n \"evaluation_metric\": \"fuzzy_match\"\n}\n" + } + }, + "Image": { + "type": "object", + "description": "Represents the content or the URL of an image generated by the OpenAI API.", + "properties": { + "b64_json": { + "type": "string", + "description": "The base64-encoded JSON of the generated image. Default value for `gpt-image-1`, and only present if `response_format` is set to `b64_json` for `dall-e-2` and `dall-e-3`." + }, + "url": { + "type": "string", + "description": "When using `dall-e-2` or `dall-e-3`, the URL of the generated image if `response_format` is set to `url` (default value). Unsupported for `gpt-image-1`." + }, + "revised_prompt": { + "type": "string", + "description": "For `dall-e-3` only, the revised prompt that was used to generate the image." + } + } + }, + "ImageEditCompletedEvent": { + "type": "object", + "description": "Emitted when image editing has completed and the final image is available.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `image_edit.completed`.\n", + "enum": [ + "image_edit.completed" + ], + "x-stainless-const": true + }, + "b64_json": { + "type": "string", + "description": "Base64-encoded final edited image data, suitable for rendering as an image.\n" + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp when the event was created.\n" + }, + "size": { + "type": "string", + "description": "The size of the edited image.\n", + "enum": [ + "1024x1024", + "1024x1536", + "1536x1024", + "auto" + ] + }, + "quality": { + "type": "string", + "description": "The quality setting for the edited image.\n", + "enum": [ + "low", + "medium", + "high", + "auto" + ] + }, + "background": { + "type": "string", + "description": "The background setting for the edited image.\n", + "enum": [ + "transparent", + "opaque", + "auto" + ] + }, + "output_format": { + "type": "string", + "description": "The output format for the edited image.\n", + "enum": [ + "png", + "webp", + "jpeg" + ] + }, + "usage": { + "$ref": "#/components/schemas/ImagesUsage" + } + }, + "required": [ + "type", + "b64_json", + "created_at", + "size", + "quality", + "background", + "output_format", + "usage" + ], + "x-oaiMeta": { + "name": "image_edit.completed", + "group": "images", + "example": "{\n \"type\": \"image_edit.completed\",\n \"b64_json\": \"...\",\n \"created_at\": 1620000000,\n \"size\": \"1024x1024\",\n \"quality\": \"high\",\n \"background\": \"transparent\",\n \"output_format\": \"png\",\n \"usage\": {\n \"total_tokens\": 100,\n \"input_tokens\": 50,\n \"output_tokens\": 50,\n \"input_tokens_details\": {\n \"text_tokens\": 10,\n \"image_tokens\": 40\n }\n }\n}\n" + } + }, + "ImageEditPartialImageEvent": { + "type": "object", + "description": "Emitted when a partial image is available during image editing streaming.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `image_edit.partial_image`.\n", + "enum": [ + "image_edit.partial_image" + ], + "x-stainless-const": true + }, + "b64_json": { + "type": "string", + "description": "Base64-encoded partial image data, suitable for rendering as an image.\n" + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp when the event was created.\n" + }, + "size": { + "type": "string", + "description": "The size of the requested edited image.\n", + "enum": [ + "1024x1024", + "1024x1536", + "1536x1024", + "auto" + ] + }, + "quality": { + "type": "string", + "description": "The quality setting for the requested edited image.\n", + "enum": [ + "low", + "medium", + "high", + "auto" + ] + }, + "background": { + "type": "string", + "description": "The background setting for the requested edited image.\n", + "enum": [ + "transparent", + "opaque", + "auto" + ] + }, + "output_format": { + "type": "string", + "description": "The output format for the requested edited image.\n", + "enum": [ + "png", + "webp", + "jpeg" + ] + }, + "partial_image_index": { + "type": "integer", + "description": "0-based index for the partial image (streaming).\n" + } + }, + "required": [ + "type", + "b64_json", + "created_at", + "size", + "quality", + "background", + "output_format", + "partial_image_index" + ], + "x-oaiMeta": { + "name": "image_edit.partial_image", + "group": "images", + "example": "{\n \"type\": \"image_edit.partial_image\",\n \"b64_json\": \"...\",\n \"created_at\": 1620000000,\n \"size\": \"1024x1024\",\n \"quality\": \"high\",\n \"background\": \"transparent\",\n \"output_format\": \"png\",\n \"partial_image_index\": 0\n}\n" + } + }, + "ImageEditStreamEvent": { + "anyOf": [ + { + "$ref": "#/components/schemas/ImageEditPartialImageEvent" + }, + { + "$ref": "#/components/schemas/ImageEditCompletedEvent" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "ImageGenCompletedEvent": { + "type": "object", + "description": "Emitted when image generation has completed and the final image is available.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `image_generation.completed`.\n", + "enum": [ + "image_generation.completed" + ], + "x-stainless-const": true + }, + "b64_json": { + "type": "string", + "description": "Base64-encoded image data, suitable for rendering as an image.\n" + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp when the event was created.\n" + }, + "size": { + "type": "string", + "description": "The size of the generated image.\n", + "enum": [ + "1024x1024", + "1024x1536", + "1536x1024", + "auto" + ] + }, + "quality": { + "type": "string", + "description": "The quality setting for the generated image.\n", + "enum": [ + "low", + "medium", + "high", + "auto" + ] + }, + "background": { + "type": "string", + "description": "The background setting for the generated image.\n", + "enum": [ + "transparent", + "opaque", + "auto" + ] + }, + "output_format": { + "type": "string", + "description": "The output format for the generated image.\n", + "enum": [ + "png", + "webp", + "jpeg" + ] + }, + "usage": { + "$ref": "#/components/schemas/ImagesUsage" + } + }, + "required": [ + "type", + "b64_json", + "created_at", + "size", + "quality", + "background", + "output_format", + "usage" + ], + "x-oaiMeta": { + "name": "image_generation.completed", + "group": "images", + "example": "{\n \"type\": \"image_generation.completed\",\n \"b64_json\": \"...\",\n \"created_at\": 1620000000,\n \"size\": \"1024x1024\",\n \"quality\": \"high\",\n \"background\": \"transparent\",\n \"output_format\": \"png\",\n \"usage\": {\n \"total_tokens\": 100,\n \"input_tokens\": 50,\n \"output_tokens\": 50,\n \"input_tokens_details\": {\n \"text_tokens\": 10,\n \"image_tokens\": 40\n }\n }\n}\n" + } + }, + "ImageGenPartialImageEvent": { + "type": "object", + "description": "Emitted when a partial image is available during image generation streaming.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `image_generation.partial_image`.\n", + "enum": [ + "image_generation.partial_image" + ], + "x-stainless-const": true + }, + "b64_json": { + "type": "string", + "description": "Base64-encoded partial image data, suitable for rendering as an image.\n" + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp when the event was created.\n" + }, + "size": { + "type": "string", + "description": "The size of the requested image.\n", + "enum": [ + "1024x1024", + "1024x1536", + "1536x1024", + "auto" + ] + }, + "quality": { + "type": "string", + "description": "The quality setting for the requested image.\n", + "enum": [ + "low", + "medium", + "high", + "auto" + ] + }, + "background": { + "type": "string", + "description": "The background setting for the requested image.\n", + "enum": [ + "transparent", + "opaque", + "auto" + ] + }, + "output_format": { + "type": "string", + "description": "The output format for the requested image.\n", + "enum": [ + "png", + "webp", + "jpeg" + ] + }, + "partial_image_index": { + "type": "integer", + "description": "0-based index for the partial image (streaming).\n" + } + }, + "required": [ + "type", + "b64_json", + "created_at", + "size", + "quality", + "background", + "output_format", + "partial_image_index" + ], + "x-oaiMeta": { + "name": "image_generation.partial_image", + "group": "images", + "example": "{\n \"type\": \"image_generation.partial_image\",\n \"b64_json\": \"...\",\n \"created_at\": 1620000000,\n \"size\": \"1024x1024\",\n \"quality\": \"high\",\n \"background\": \"transparent\",\n \"output_format\": \"png\",\n \"partial_image_index\": 0\n}\n" + } + }, + "ImageGenStreamEvent": { + "anyOf": [ + { + "$ref": "#/components/schemas/ImageGenPartialImageEvent" + }, + { + "$ref": "#/components/schemas/ImageGenCompletedEvent" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "ImageGenTool": { + "type": "object", + "title": "Image generation tool", + "description": "A tool that generates images using a model like `gpt-image-1`.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "image_generation" + ], + "description": "The type of the image generation tool. Always `image_generation`.\n", + "x-stainless-const": true + }, + "model": { + "type": "string", + "enum": [ + "gpt-image-1" + ], + "description": "The image generation model to use. Default: `gpt-image-1`.\n", + "default": "gpt-image-1" + }, + "quality": { + "type": "string", + "enum": [ + "low", + "medium", + "high", + "auto" + ], + "description": "The quality of the generated image. One of `low`, `medium`, `high`, \nor `auto`. Default: `auto`.\n", + "default": "auto" + }, + "size": { + "type": "string", + "enum": [ + "1024x1024", + "1024x1536", + "1536x1024", + "auto" + ], + "description": "The size of the generated image. One of `1024x1024`, `1024x1536`, \n`1536x1024`, or `auto`. Default: `auto`.\n", + "default": "auto" + }, + "output_format": { + "type": "string", + "enum": [ + "png", + "webp", + "jpeg" + ], + "description": "The output format of the generated image. One of `png`, `webp`, or \n`jpeg`. Default: `png`.\n", + "default": "png" + }, + "output_compression": { + "type": "integer", + "minimum": 0, + "maximum": 100, + "description": "Compression level for the output image. Default: 100.\n", + "default": 100 + }, + "moderation": { + "type": "string", + "enum": [ + "auto", + "low" + ], + "description": "Moderation level for the generated image. Default: `auto`.\n", + "default": "auto" + }, + "background": { + "type": "string", + "enum": [ + "transparent", + "opaque", + "auto" + ], + "description": "Background type for the generated image. One of `transparent`, \n`opaque`, or `auto`. Default: `auto`.\n", + "default": "auto" + }, + "input_fidelity": { + "$ref": "#/components/schemas/ImageInputFidelity" + }, + "input_image_mask": { + "type": "object", + "description": "Optional mask for inpainting. Contains `image_url` \n(string, optional) and `file_id` (string, optional).\n", + "properties": { + "image_url": { + "type": "string", + "description": "Base64-encoded mask image.\n" + }, + "file_id": { + "type": "string", + "description": "File ID for the mask image.\n" + } + }, + "required": [], + "additionalProperties": false + }, + "partial_images": { + "type": "integer", + "minimum": 0, + "maximum": 3, + "description": "Number of partial images to generate in streaming mode, from 0 (default value) to 3.\n", + "default": 0 + } + }, + "required": [ + "type" + ] + }, + "ImageGenToolCall": { + "type": "object", + "title": "Image generation call", + "description": "An image generation request made by the model.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "image_generation_call" + ], + "description": "The type of the image generation call. Always `image_generation_call`.\n", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the image generation call.\n" + }, + "status": { + "type": "string", + "enum": [ + "in_progress", + "completed", + "generating", + "failed" + ], + "description": "The status of the image generation call.\n" + }, + "result": { + "type": "string", + "description": "The generated image encoded in base64.\n", + "nullable": true + } + }, + "required": [ + "type", + "id", + "status", + "result" + ] + }, + "ImageInputFidelity": { + "type": "string", + "enum": [ + "high", + "low" + ], + "default": "low", + "nullable": true, + "description": "Control how much effort the model will exert to match the style and features,\nespecially facial features, of input images. This parameter is only supported\nfor `gpt-image-1`. Supports `high` and `low`. Defaults to `low`.\n" + }, + "ImagesResponse": { + "type": "object", + "title": "Image generation response", + "description": "The response from the image generation endpoint.", + "properties": { + "created": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the image was created." + }, + "data": { + "type": "array", + "description": "The list of generated images.", + "items": { + "$ref": "#/components/schemas/Image" + } + }, + "background": { + "type": "string", + "description": "The background parameter used for the image generation. Either `transparent` or `opaque`.", + "enum": [ + "transparent", + "opaque" + ] + }, + "output_format": { + "type": "string", + "description": "The output format of the image generation. Either `png`, `webp`, or `jpeg`.", + "enum": [ + "png", + "webp", + "jpeg" + ] + }, + "size": { + "type": "string", + "description": "The size of the image generated. Either `1024x1024`, `1024x1536`, or `1536x1024`.", + "enum": [ + "1024x1024", + "1024x1536", + "1536x1024" + ] + }, + "quality": { + "type": "string", + "description": "The quality of the image generated. Either `low`, `medium`, or `high`.", + "enum": [ + "low", + "medium", + "high" + ] + }, + "usage": { + "$ref": "#/components/schemas/ImageGenUsage" + } + }, + "required": [ + "created" + ], + "x-oaiMeta": { + "name": "The image generation response", + "group": "images", + "example": "{\n \"created\": 1713833628,\n \"data\": [\n {\n \"b64_json\": \"...\"\n }\n ],\n \"background\": \"transparent\",\n \"output_format\": \"png\",\n \"size\": \"1024x1024\",\n \"quality\": \"high\",\n \"usage\": {\n \"total_tokens\": 100,\n \"input_tokens\": 50,\n \"output_tokens\": 50,\n \"input_tokens_details\": {\n \"text_tokens\": 10,\n \"image_tokens\": 40\n }\n }\n}\n" + } + }, + "ImagesUsage": { + "type": "object", + "description": "For `gpt-image-1` only, the token usage information for the image generation.\n", + "required": [ + "total_tokens", + "input_tokens", + "output_tokens", + "input_tokens_details" + ], + "properties": { + "total_tokens": { + "type": "integer", + "description": "The total number of tokens (images and text) used for the image generation.\n" + }, + "input_tokens": { + "type": "integer", + "description": "The number of tokens (images and text) in the input prompt." + }, + "output_tokens": { + "type": "integer", + "description": "The number of image tokens in the output image." + }, + "input_tokens_details": { + "type": "object", + "description": "The input tokens detailed information for the image generation.", + "required": [ + "text_tokens", + "image_tokens" + ], + "properties": { + "text_tokens": { + "type": "integer", + "description": "The number of text tokens in the input prompt." + }, + "image_tokens": { + "type": "integer", + "description": "The number of image tokens in the input prompt." + } + } + } + } + }, + "Includable": { + "type": "string", + "description": "Specify additional output data to include in the model response. Currently\nsupported values are:\n- `web_search_call.action.sources`: Include the sources of the web search tool call.\n- `code_interpreter_call.outputs`: Includes the outputs of python code execution\n in code interpreter tool call items.\n- `computer_call_output.output.image_url`: Include image urls from the computer call output.\n- `file_search_call.results`: Include the search results of\n the file search tool call.\n- `message.input_image.image_url`: Include image urls from the input message.\n- `message.output_text.logprobs`: Include logprobs with assistant messages.\n- `reasoning.encrypted_content`: Includes an encrypted version of reasoning\n tokens in reasoning item outputs. This enables reasoning items to be used in\n multi-turn conversations when using the Responses API statelessly (like\n when the `store` parameter is set to `false`, or when an organization is\n enrolled in the zero data retention program).\n", + "enum": [ + "code_interpreter_call.outputs", + "computer_call_output.output.image_url", + "file_search_call.results", + "message.input_image.image_url", + "message.output_text.logprobs", + "reasoning.encrypted_content" + ] + }, + "InputAudio": { + "type": "object", + "title": "Input audio", + "description": "An audio input to the model.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the input item. Always `input_audio`.\n", + "enum": [ + "input_audio" + ], + "x-stainless-const": true + }, + "input_audio": { + "type": "object", + "properties": { + "data": { + "type": "string", + "description": "Base64-encoded audio data.\n" + }, + "format": { + "type": "string", + "description": "The format of the audio data. Currently supported formats are `mp3` and\n`wav`.\n", + "enum": [ + "mp3", + "wav" + ] + } + }, + "required": [ + "data", + "format" + ] + } + }, + "required": [ + "type", + "input_audio" + ] + }, + "InputContent": { + "anyOf": [ + { + "$ref": "#/components/schemas/InputTextContent" + }, + { + "$ref": "#/components/schemas/InputImageContent" + }, + { + "$ref": "#/components/schemas/InputFileContent" + }, + { + "$ref": "#/components/schemas/InputAudio" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "InputItem": { + "discriminator": { + "propertyName": "type" + }, + "anyOf": [ + { + "$ref": "#/components/schemas/EasyInputMessage" + }, + { + "type": "object", + "title": "Item", + "description": "An item representing part of the context for the response to be \ngenerated by the model. Can contain text, images, and audio inputs,\nas well as previous assistant responses and tool call outputs.\n", + "$ref": "#/components/schemas/Item" + }, + { + "$ref": "#/components/schemas/ItemReferenceParam" + } + ] + }, + "InputMessage": { + "type": "object", + "title": "Input message", + "description": "A message input to the model with a role indicating instruction following\nhierarchy. Instructions given with the `developer` or `system` role take\nprecedence over instructions given with the `user` role.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the message input. Always set to `message`.\n", + "enum": [ + "message" + ], + "x-stainless-const": true + }, + "role": { + "type": "string", + "description": "The role of the message input. One of `user`, `system`, or `developer`.\n", + "enum": [ + "user", + "system", + "developer" + ] + }, + "status": { + "type": "string", + "description": "The status of item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n", + "enum": [ + "in_progress", + "completed", + "incomplete" + ] + }, + "content": { + "$ref": "#/components/schemas/InputMessageContentList" + } + }, + "required": [ + "role", + "content" + ] + }, + "InputMessageContentList": { + "type": "array", + "title": "Input item content list", + "description": "A list of one or many input items to the model, containing different content \ntypes.\n", + "items": { + "$ref": "#/components/schemas/InputContent" + } + }, + "InputMessageResource": { + "allOf": [ + { + "$ref": "#/components/schemas/InputMessage" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the message input.\n" + } + }, + "required": [ + "id" + ] + } + ] + }, + "Invite": { + "type": "object", + "description": "Represents an individual `invite` to the organization.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.invite" + ], + "description": "The object type, which is always `organization.invite`", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The identifier, which can be referenced in API endpoints" + }, + "email": { + "type": "string", + "description": "The email address of the individual to whom the invite was sent" + }, + "role": { + "type": "string", + "enum": [ + "owner", + "reader" + ], + "description": "`owner` or `reader`" + }, + "status": { + "type": "string", + "enum": [ + "accepted", + "expired", + "pending" + ], + "description": "`accepted`,`expired`, or `pending`" + }, + "invited_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the invite was sent." + }, + "expires_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the invite expires." + }, + "accepted_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the invite was accepted." + }, + "projects": { + "type": "array", + "description": "The projects that were granted membership upon acceptance of the invite.", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Project's public ID" + }, + "role": { + "type": "string", + "enum": [ + "member", + "owner" + ], + "description": "Project membership role" + } + } + } + } + }, + "required": [ + "object", + "id", + "email", + "role", + "status", + "invited_at", + "expires_at" + ], + "x-oaiMeta": { + "name": "The invite object", + "example": "{\n \"object\": \"organization.invite\",\n \"id\": \"invite-abc\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"status\": \"accepted\",\n \"invited_at\": 1711471533,\n \"expires_at\": 1711471533,\n \"accepted_at\": 1711471533,\n \"projects\": [\n {\n \"id\": \"project-xyz\",\n \"role\": \"member\"\n }\n ]\n}\n" + } + }, + "InviteDeleteResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.invite.deleted" + ], + "description": "The object type, which is always `organization.invite.deleted`", + "x-stainless-const": true + }, + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + } + }, + "required": [ + "object", + "id", + "deleted" + ] + }, + "InviteListResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "description": "The object type, which is always `list`", + "x-stainless-const": true + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Invite" + } + }, + "first_id": { + "type": "string", + "description": "The first `invite_id` in the retrieved `list`" + }, + "last_id": { + "type": "string", + "description": "The last `invite_id` in the retrieved `list`" + }, + "has_more": { + "type": "boolean", + "description": "The `has_more` property is used for pagination to indicate there are additional results." + } + }, + "required": [ + "object", + "data" + ] + }, + "InviteRequest": { + "type": "object", + "properties": { + "email": { + "type": "string", + "description": "Send an email to this address" + }, + "role": { + "type": "string", + "enum": [ + "reader", + "owner" + ], + "description": "`owner` or `reader`" + }, + "projects": { + "type": "array", + "description": "An array of projects to which membership is granted at the same time the org invite is accepted. If omitted, the user will be invited to the default project for compatibility with legacy behavior.", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Project's public ID" + }, + "role": { + "type": "string", + "enum": [ + "member", + "owner" + ], + "description": "Project membership role" + } + }, + "required": [ + "id", + "role" + ] + } + } + }, + "required": [ + "email", + "role" + ] + }, + "Item": { + "type": "object", + "description": "Content item used to generate a response.\n", + "discriminator": { + "propertyName": "type" + }, + "anyOf": [ + { + "$ref": "#/components/schemas/InputMessage" + }, + { + "$ref": "#/components/schemas/OutputMessage" + }, + { + "$ref": "#/components/schemas/FileSearchToolCall" + }, + { + "$ref": "#/components/schemas/ComputerToolCall" + }, + { + "$ref": "#/components/schemas/ComputerCallOutputItemParam" + }, + { + "$ref": "#/components/schemas/WebSearchToolCall" + }, + { + "$ref": "#/components/schemas/FunctionToolCall" + }, + { + "$ref": "#/components/schemas/FunctionCallOutputItemParam" + }, + { + "$ref": "#/components/schemas/ReasoningItem" + }, + { + "$ref": "#/components/schemas/ImageGenToolCall" + }, + { + "$ref": "#/components/schemas/CodeInterpreterToolCall" + }, + { + "$ref": "#/components/schemas/LocalShellToolCall" + }, + { + "$ref": "#/components/schemas/LocalShellToolCallOutput" + }, + { + "$ref": "#/components/schemas/MCPListTools" + }, + { + "$ref": "#/components/schemas/MCPApprovalRequest" + }, + { + "$ref": "#/components/schemas/MCPApprovalResponse" + }, + { + "$ref": "#/components/schemas/MCPToolCall" + }, + { + "$ref": "#/components/schemas/CustomToolCallOutput" + }, + { + "$ref": "#/components/schemas/CustomToolCall" + } + ] + }, + "ItemResource": { + "description": "Content item used to generate a response.\n", + "discriminator": { + "propertyName": "type" + }, + "anyOf": [ + { + "$ref": "#/components/schemas/InputMessageResource" + }, + { + "$ref": "#/components/schemas/OutputMessage" + }, + { + "$ref": "#/components/schemas/FileSearchToolCall" + }, + { + "$ref": "#/components/schemas/ComputerToolCall" + }, + { + "$ref": "#/components/schemas/ComputerToolCallOutputResource" + }, + { + "$ref": "#/components/schemas/WebSearchToolCall" + }, + { + "$ref": "#/components/schemas/FunctionToolCallResource" + }, + { + "$ref": "#/components/schemas/FunctionToolCallOutputResource" + }, + { + "$ref": "#/components/schemas/ImageGenToolCall" + }, + { + "$ref": "#/components/schemas/CodeInterpreterToolCall" + }, + { + "$ref": "#/components/schemas/LocalShellToolCall" + }, + { + "$ref": "#/components/schemas/LocalShellToolCallOutput" + }, + { + "$ref": "#/components/schemas/MCPListTools" + }, + { + "$ref": "#/components/schemas/MCPApprovalRequest" + }, + { + "$ref": "#/components/schemas/MCPApprovalResponseResource" + }, + { + "$ref": "#/components/schemas/MCPToolCall" + } + ] + }, + "KeyPress": { + "type": "object", + "title": "KeyPress", + "description": "A collection of keypresses the model would like to perform.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "keypress" + ], + "default": "keypress", + "description": "Specifies the event type. For a keypress action, this property is \nalways set to `keypress`.\n", + "x-stainless-const": true + }, + "keys": { + "type": "array", + "items": { + "type": "string", + "description": "One of the keys the model is requesting to be pressed.\n" + }, + "description": "The combination of keys the model is requesting to be pressed. This is an\narray of strings, each representing a key.\n" + } + }, + "required": [ + "type", + "keys" + ] + }, + "ListAssistantsResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "example": "list" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AssistantObject" + } + }, + "first_id": { + "type": "string", + "example": "asst_abc123" + }, + "last_id": { + "type": "string", + "example": "asst_abc456" + }, + "has_more": { + "type": "boolean", + "example": false + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ], + "x-oaiMeta": { + "name": "List assistants response object", + "group": "chat", + "example": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"asst_abc123\",\n \"object\": \"assistant\",\n \"created_at\": 1698982736,\n \"name\": \"Coding Tutor\",\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You are a helpful assistant designed to make me better at coding!\",\n \"tools\": [],\n \"tool_resources\": {},\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n },\n {\n \"id\": \"asst_abc456\",\n \"object\": \"assistant\",\n \"created_at\": 1698982718,\n \"name\": \"My Assistant\",\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": \"You are a helpful assistant designed to make me better at coding!\",\n \"tools\": [],\n \"tool_resources\": {},\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n },\n {\n \"id\": \"asst_abc789\",\n \"object\": \"assistant\",\n \"created_at\": 1698982643,\n \"name\": null,\n \"description\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": null,\n \"tools\": [],\n \"tool_resources\": {},\n \"metadata\": {},\n \"top_p\": 1.0,\n \"temperature\": 1.0,\n \"response_format\": \"auto\"\n }\n ],\n \"first_id\": \"asst_abc123\",\n \"last_id\": \"asst_abc789\",\n \"has_more\": false\n}\n" + } + }, + "ListAuditLogsResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AuditLog" + } + }, + "first_id": { + "type": "string", + "example": "audit_log-defb456h8dks" + }, + "last_id": { + "type": "string", + "example": "audit_log-hnbkd8s93s" + }, + "has_more": { + "type": "boolean" + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ListBatchesResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Batch" + } + }, + "first_id": { + "type": "string", + "example": "batch_abc123" + }, + "last_id": { + "type": "string", + "example": "batch_abc456" + }, + "has_more": { + "type": "boolean" + }, + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + } + }, + "required": [ + "object", + "data", + "has_more" + ] + }, + "ListCertificatesResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Certificate" + } + }, + "first_id": { + "type": "string", + "example": "cert_abc" + }, + "last_id": { + "type": "string", + "example": "cert_abc" + }, + "has_more": { + "type": "boolean" + }, + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + } + }, + "required": [ + "object", + "data", + "has_more" + ] + }, + "ListFilesResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "example": "list" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OpenAIFile" + } + }, + "first_id": { + "type": "string", + "example": "file-abc123" + }, + "last_id": { + "type": "string", + "example": "file-abc456" + }, + "has_more": { + "type": "boolean", + "example": false + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ListFineTuningCheckpointPermissionResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FineTuningCheckpointPermission" + } + }, + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "first_id": { + "type": "string", + "nullable": true + }, + "last_id": { + "type": "string", + "nullable": true + }, + "has_more": { + "type": "boolean" + } + }, + "required": [ + "object", + "data", + "has_more" + ] + }, + "ListFineTuningJobCheckpointsResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FineTuningJobCheckpoint" + } + }, + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "first_id": { + "type": "string", + "nullable": true + }, + "last_id": { + "type": "string", + "nullable": true + }, + "has_more": { + "type": "boolean" + } + }, + "required": [ + "object", + "data", + "has_more" + ] + }, + "ListFineTuningJobEventsResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FineTuningJobEvent" + } + }, + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "has_more": { + "type": "boolean" + } + }, + "required": [ + "object", + "data", + "has_more" + ] + }, + "ListMessagesResponse": { + "properties": { + "object": { + "type": "string", + "example": "list" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MessageObject" + } + }, + "first_id": { + "type": "string", + "example": "msg_abc123" + }, + "last_id": { + "type": "string", + "example": "msg_abc123" + }, + "has_more": { + "type": "boolean", + "example": false + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ListModelsResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Model" + } + } + }, + "required": [ + "object", + "data" + ] + }, + "ListPaginatedFineTuningJobsResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FineTuningJob" + } + }, + "has_more": { + "type": "boolean" + }, + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + } + }, + "required": [ + "object", + "data", + "has_more" + ] + }, + "ListRunStepsResponse": { + "properties": { + "object": { + "type": "string", + "example": "list" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RunStepObject" + } + }, + "first_id": { + "type": "string", + "example": "step_abc123" + }, + "last_id": { + "type": "string", + "example": "step_abc456" + }, + "has_more": { + "type": "boolean", + "example": false + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ListRunsResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "example": "list" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RunObject" + } + }, + "first_id": { + "type": "string", + "example": "run_abc123" + }, + "last_id": { + "type": "string", + "example": "run_abc456" + }, + "has_more": { + "type": "boolean", + "example": false + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ListVectorStoreFilesResponse": { + "properties": { + "object": { + "type": "string", + "example": "list" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VectorStoreFileObject" + } + }, + "first_id": { + "type": "string", + "example": "file-abc123" + }, + "last_id": { + "type": "string", + "example": "file-abc456" + }, + "has_more": { + "type": "boolean", + "example": false + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ListVectorStoresResponse": { + "properties": { + "object": { + "type": "string", + "example": "list" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VectorStoreObject" + } + }, + "first_id": { + "type": "string", + "example": "vs_abc123" + }, + "last_id": { + "type": "string", + "example": "vs_abc456" + }, + "has_more": { + "type": "boolean", + "example": false + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "LocalShellExecAction": { + "type": "object", + "title": "Local shell exec action", + "description": "Execute a shell command on the server.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "exec" + ], + "description": "The type of the local shell action. Always `exec`.\n", + "x-stainless-const": true + }, + "command": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The command to run.\n" + }, + "timeout_ms": { + "type": "integer", + "description": "Optional timeout in milliseconds for the command.\n", + "nullable": true + }, + "working_directory": { + "type": "string", + "description": "Optional working directory to run the command in.\n", + "nullable": true + }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables to set for the command.\n" + }, + "user": { + "type": "string", + "description": "Optional user to run the command as.\n", + "nullable": true + } + }, + "required": [ + "type", + "command", + "env" + ] + }, + "LocalShellTool": { + "type": "object", + "title": "Local shell tool", + "description": "A tool that allows the model to execute shell commands in a local environment.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "local_shell" + ], + "description": "The type of the local shell tool. Always `local_shell`.", + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + "LocalShellToolCall": { + "type": "object", + "title": "Local shell call", + "description": "A tool call to run a command on the local shell.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "local_shell_call" + ], + "description": "The type of the local shell call. Always `local_shell_call`.\n", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the local shell call.\n" + }, + "call_id": { + "type": "string", + "description": "The unique ID of the local shell tool call generated by the model.\n" + }, + "action": { + "$ref": "#/components/schemas/LocalShellExecAction" + }, + "status": { + "type": "string", + "enum": [ + "in_progress", + "completed", + "incomplete" + ], + "description": "The status of the local shell call.\n" + } + }, + "required": [ + "type", + "id", + "call_id", + "action", + "status" + ] + }, + "LocalShellToolCallOutput": { + "type": "object", + "title": "Local shell call output", + "description": "The output of a local shell tool call.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "local_shell_call_output" + ], + "description": "The type of the local shell tool call output. Always `local_shell_call_output`.\n", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the local shell tool call generated by the model.\n" + }, + "output": { + "type": "string", + "description": "A JSON string of the output of the local shell tool call.\n" + }, + "status": { + "type": "string", + "enum": [ + "in_progress", + "completed", + "incomplete" + ], + "description": "The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n", + "nullable": true + } + }, + "required": [ + "id", + "type", + "call_id", + "output" + ] + }, + "LogProbProperties": { + "type": "object", + "description": "A log probability object.\n", + "properties": { + "token": { + "type": "string", + "description": "The token that was used to generate the log probability.\n" + }, + "logprob": { + "type": "number", + "description": "The log probability of the token.\n" + }, + "bytes": { + "type": "array", + "items": { + "type": "integer" + }, + "description": "The bytes that were used to generate the log probability.\n" + } + }, + "required": [ + "token", + "logprob", + "bytes" + ] + }, + "MCPApprovalRequest": { + "type": "object", + "title": "MCP approval request", + "description": "A request for human approval of a tool invocation.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp_approval_request" + ], + "description": "The type of the item. Always `mcp_approval_request`.\n", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the approval request.\n" + }, + "server_label": { + "type": "string", + "description": "The label of the MCP server making the request.\n" + }, + "name": { + "type": "string", + "description": "The name of the tool to run.\n" + }, + "arguments": { + "type": "string", + "description": "A JSON string of arguments for the tool.\n" + } + }, + "required": [ + "type", + "id", + "server_label", + "name", + "arguments" + ] + }, + "MCPApprovalResponse": { + "type": "object", + "title": "MCP approval response", + "description": "A response to an MCP approval request.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp_approval_response" + ], + "description": "The type of the item. Always `mcp_approval_response`.\n", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the approval response\n", + "nullable": true + }, + "approval_request_id": { + "type": "string", + "description": "The ID of the approval request being answered.\n" + }, + "approve": { + "type": "boolean", + "description": "Whether the request was approved.\n" + }, + "reason": { + "type": "string", + "description": "Optional reason for the decision.\n", + "nullable": true + } + }, + "required": [ + "type", + "request_id", + "approve", + "approval_request_id" + ] + }, + "MCPApprovalResponseResource": { + "type": "object", + "title": "MCP approval response", + "description": "A response to an MCP approval request.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp_approval_response" + ], + "description": "The type of the item. Always `mcp_approval_response`.\n", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the approval response\n" + }, + "approval_request_id": { + "type": "string", + "description": "The ID of the approval request being answered.\n" + }, + "approve": { + "type": "boolean", + "description": "Whether the request was approved.\n" + }, + "reason": { + "type": "string", + "description": "Optional reason for the decision.\n", + "nullable": true + } + }, + "required": [ + "type", + "id", + "request_id", + "approve", + "approval_request_id" + ] + }, + "MCPListTools": { + "type": "object", + "title": "MCP list tools", + "description": "A list of tools available on an MCP server.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp_list_tools" + ], + "description": "The type of the item. Always `mcp_list_tools`.\n", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the list.\n" + }, + "server_label": { + "type": "string", + "description": "The label of the MCP server.\n" + }, + "tools": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MCPListToolsTool" + }, + "description": "The tools available on the server.\n" + }, + "error": { + "type": "string", + "description": "Error message if the server could not list tools.\n", + "nullable": true + } + }, + "required": [ + "type", + "id", + "server_label", + "tools" + ] + }, + "MCPListToolsTool": { + "type": "object", + "title": "MCP list tools tool", + "description": "A tool available on an MCP server.\n", + "properties": { + "name": { + "type": "string", + "description": "The name of the tool.\n" + }, + "description": { + "type": "string", + "description": "The description of the tool.\n", + "nullable": true + }, + "input_schema": { + "type": "object", + "description": "The JSON schema describing the tool's input.\n" + }, + "annotations": { + "type": "object", + "description": "Additional annotations about the tool.\n", + "nullable": true + } + }, + "required": [ + "name", + "input_schema" + ] + }, + "MCPTool": { + "type": "object", + "title": "MCP tool", + "description": "Give the model access to additional tools via remote Model Context Protocol \n(MCP) servers. [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp).\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp" + ], + "description": "The type of the MCP tool. Always `mcp`.", + "x-stainless-const": true + }, + "server_label": { + "type": "string", + "description": "A label for this MCP server, used to identify it in tool calls.\n" + }, + "server_url": { + "type": "string", + "description": "The URL for the MCP server. One of `server_url` or `connector_id` must be \nprovided.\n" + }, + "connector_id": { + "type": "string", + "enum": [ + "connector_dropbox", + "connector_gmail", + "connector_googlecalendar", + "connector_googledrive", + "connector_microsoftteams", + "connector_outlookcalendar", + "connector_outlookemail", + "connector_sharepoint" + ], + "description": "Identifier for service connectors, like those available in ChatGPT. One of\n`server_url` or `connector_id` must be provided. Learn more about service\nconnectors [here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors).\n\nCurrently supported `connector_id` values are:\n\n- Dropbox: `connector_dropbox`\n- Gmail: `connector_gmail`\n- Google Calendar: `connector_googlecalendar`\n- Google Drive: `connector_googledrive`\n- Microsoft Teams: `connector_microsoftteams`\n- Outlook Calendar: `connector_outlookcalendar`\n- Outlook Email: `connector_outlookemail`\n- SharePoint: `connector_sharepoint`\n" + }, + "authorization": { + "type": "string", + "description": "An OAuth access token that can be used with a remote MCP server, either \nwith a custom MCP server URL or a service connector. Your application\nmust handle the OAuth authorization flow and provide the token here.\n" + }, + "server_description": { + "type": "string", + "description": "Optional description of the MCP server, used to provide more context.\n" + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "nullable": true, + "description": "Optional HTTP headers to send to the MCP server. Use for authentication\nor other purposes.\n" + }, + "allowed_tools": { + "description": "List of allowed tool names or a filter object.\n", + "nullable": true, + "anyOf": [ + { + "type": "array", + "title": "MCP allowed tools", + "description": "A string array of allowed tool names", + "items": { + "type": "string" + } + }, + { + "$ref": "#/components/schemas/MCPToolFilter" + } + ] + }, + "require_approval": { + "description": "Specify which of the MCP server's tools require approval.", + "nullable": true, + "anyOf": [ + { + "type": "object", + "title": "MCP tool approval filter", + "description": "Specify which of the MCP server's tools require approval. Can be\n`always`, `never`, or a filter object associated with tools\nthat require approval.\n", + "properties": { + "always": { + "$ref": "#/components/schemas/MCPToolFilter" + }, + "never": { + "$ref": "#/components/schemas/MCPToolFilter" + } + }, + "additionalProperties": false + }, + { + "type": "string", + "title": "MCP tool approval setting", + "description": "Specify a single approval policy for all tools. One of `always` or \n`never`. When set to `always`, all tools will require approval. When \nset to `never`, all tools will not require approval.\n", + "enum": [ + "always", + "never" + ] + } + ] + } + }, + "required": [ + "type", + "server_label" + ] + }, + "MCPToolCall": { + "type": "object", + "title": "MCP tool call", + "description": "An invocation of a tool on an MCP server.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp_call" + ], + "description": "The type of the item. Always `mcp_call`.\n", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the tool call.\n" + }, + "server_label": { + "type": "string", + "description": "The label of the MCP server running the tool.\n" + }, + "name": { + "type": "string", + "description": "The name of the tool that was run.\n" + }, + "arguments": { + "type": "string", + "description": "A JSON string of the arguments passed to the tool.\n" + }, + "output": { + "type": "string", + "description": "The output from the tool call.\n", + "nullable": true + }, + "error": { + "type": "string", + "description": "The error from the tool call, if any.\n", + "nullable": true + } + }, + "required": [ + "type", + "id", + "server_label", + "name", + "arguments" + ] + }, + "MCPToolFilter": { + "type": "object", + "title": "MCP tool filter", + "description": "A filter object to specify which tools are allowed.\n", + "properties": { + "tool_names": { + "type": "array", + "title": "MCP allowed tools", + "items": { + "type": "string" + }, + "description": "List of allowed tool names." + }, + "read_only": { + "type": "boolean", + "description": "Indicates whether or not a tool modifies data or is read-only. If an\nMCP server is [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint),\nit will match this filter.\n" + } + }, + "required": [], + "additionalProperties": false + }, + "MessageContentImageFileObject": { + "title": "Image file", + "type": "object", + "description": "References an image [File](https://platform.openai.com/docs/api-reference/files) in the content of a message.", + "properties": { + "type": { + "description": "Always `image_file`.", + "type": "string", + "enum": [ + "image_file" + ], + "x-stainless-const": true + }, + "image_file": { + "type": "object", + "properties": { + "file_id": { + "description": "The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose=\"vision\"` when uploading the File if you need to later display the file content.", + "type": "string" + }, + "detail": { + "type": "string", + "description": "Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`.", + "enum": [ + "auto", + "low", + "high" + ], + "default": "auto" + } + }, + "required": [ + "file_id" + ] + } + }, + "required": [ + "type", + "image_file" + ] + }, + "MessageContentImageUrlObject": { + "title": "Image URL", + "type": "object", + "description": "References an image URL in the content of a message.", + "properties": { + "type": { + "type": "string", + "enum": [ + "image_url" + ], + "description": "The type of the content part.", + "x-stainless-const": true + }, + "image_url": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.", + "format": "uri" + }, + "detail": { + "type": "string", + "description": "Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto`", + "enum": [ + "auto", + "low", + "high" + ], + "default": "auto" + } + }, + "required": [ + "url" + ] + } + }, + "required": [ + "type", + "image_url" + ] + }, + "MessageContentRefusalObject": { + "title": "Refusal", + "type": "object", + "description": "The refusal content generated by the assistant.", + "properties": { + "type": { + "description": "Always `refusal`.", + "type": "string", + "enum": [ + "refusal" + ], + "x-stainless-const": true + }, + "refusal": { + "type": "string", + "nullable": false + } + }, + "required": [ + "type", + "refusal" + ] + }, + "MessageContentTextAnnotationsFileCitationObject": { + "title": "File citation", + "type": "object", + "description": "A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the \"file_search\" tool to search files.", + "properties": { + "type": { + "description": "Always `file_citation`.", + "type": "string", + "enum": [ + "file_citation" + ], + "x-stainless-const": true + }, + "text": { + "description": "The text in the message content that needs to be replaced.", + "type": "string" + }, + "file_citation": { + "type": "object", + "properties": { + "file_id": { + "description": "The ID of the specific File the citation is from.", + "type": "string" + } + }, + "required": [ + "file_id" + ] + }, + "start_index": { + "type": "integer", + "minimum": 0 + }, + "end_index": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "type", + "text", + "file_citation", + "start_index", + "end_index" + ] + }, + "MessageContentTextAnnotationsFilePathObject": { + "title": "File path", + "type": "object", + "description": "A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file.", + "properties": { + "type": { + "description": "Always `file_path`.", + "type": "string", + "enum": [ + "file_path" + ], + "x-stainless-const": true + }, + "text": { + "description": "The text in the message content that needs to be replaced.", + "type": "string" + }, + "file_path": { + "type": "object", + "properties": { + "file_id": { + "description": "The ID of the file that was generated.", + "type": "string" + } + }, + "required": [ + "file_id" + ] + }, + "start_index": { + "type": "integer", + "minimum": 0 + }, + "end_index": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "type", + "text", + "file_path", + "start_index", + "end_index" + ] + }, + "MessageContentTextObject": { + "title": "Text", + "type": "object", + "description": "The text content that is part of a message.", + "properties": { + "type": { + "description": "Always `text`.", + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + }, + "text": { + "type": "object", + "properties": { + "value": { + "description": "The data that makes up the text.", + "type": "string" + }, + "annotations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TextAnnotation" + } + } + }, + "required": [ + "value", + "annotations" + ] + } + }, + "required": [ + "type", + "text" + ] + }, + "MessageDeltaContentImageFileObject": { + "title": "Image file", + "type": "object", + "description": "References an image [File](https://platform.openai.com/docs/api-reference/files) in the content of a message.", + "properties": { + "index": { + "type": "integer", + "description": "The index of the content part in the message." + }, + "type": { + "description": "Always `image_file`.", + "type": "string", + "enum": [ + "image_file" + ], + "x-stainless-const": true + }, + "image_file": { + "type": "object", + "properties": { + "file_id": { + "description": "The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose=\"vision\"` when uploading the File if you need to later display the file content.", + "type": "string" + }, + "detail": { + "type": "string", + "description": "Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`.", + "enum": [ + "auto", + "low", + "high" + ], + "default": "auto" + } + } + } + }, + "required": [ + "index", + "type" + ] + }, + "MessageDeltaContentImageUrlObject": { + "title": "Image URL", + "type": "object", + "description": "References an image URL in the content of a message.", + "properties": { + "index": { + "type": "integer", + "description": "The index of the content part in the message." + }, + "type": { + "description": "Always `image_url`.", + "type": "string", + "enum": [ + "image_url" + ], + "x-stainless-const": true + }, + "image_url": { + "type": "object", + "properties": { + "url": { + "description": "The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.", + "type": "string" + }, + "detail": { + "type": "string", + "description": "Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`.", + "enum": [ + "auto", + "low", + "high" + ], + "default": "auto" + } + } + } + }, + "required": [ + "index", + "type" + ] + }, + "MessageDeltaContentRefusalObject": { + "title": "Refusal", + "type": "object", + "description": "The refusal content that is part of a message.", + "properties": { + "index": { + "type": "integer", + "description": "The index of the refusal part in the message." + }, + "type": { + "description": "Always `refusal`.", + "type": "string", + "enum": [ + "refusal" + ], + "x-stainless-const": true + }, + "refusal": { + "type": "string" + } + }, + "required": [ + "index", + "type" + ] + }, + "MessageDeltaContentTextAnnotationsFileCitationObject": { + "title": "File citation", + "type": "object", + "description": "A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the \"file_search\" tool to search files.", + "properties": { + "index": { + "type": "integer", + "description": "The index of the annotation in the text content part." + }, + "type": { + "description": "Always `file_citation`.", + "type": "string", + "enum": [ + "file_citation" + ], + "x-stainless-const": true + }, + "text": { + "description": "The text in the message content that needs to be replaced.", + "type": "string" + }, + "file_citation": { + "type": "object", + "properties": { + "file_id": { + "description": "The ID of the specific File the citation is from.", + "type": "string" + }, + "quote": { + "description": "The specific quote in the file.", + "type": "string" + } + } + }, + "start_index": { + "type": "integer", + "minimum": 0 + }, + "end_index": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "index", + "type" + ] + }, + "MessageDeltaContentTextAnnotationsFilePathObject": { + "title": "File path", + "type": "object", + "description": "A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file.", + "properties": { + "index": { + "type": "integer", + "description": "The index of the annotation in the text content part." + }, + "type": { + "description": "Always `file_path`.", + "type": "string", + "enum": [ + "file_path" + ], + "x-stainless-const": true + }, + "text": { + "description": "The text in the message content that needs to be replaced.", + "type": "string" + }, + "file_path": { + "type": "object", + "properties": { + "file_id": { + "description": "The ID of the file that was generated.", + "type": "string" + } + } + }, + "start_index": { + "type": "integer", + "minimum": 0 + }, + "end_index": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "index", + "type" + ] + }, + "MessageDeltaContentTextObject": { + "title": "Text", + "type": "object", + "description": "The text content that is part of a message.", + "properties": { + "index": { + "type": "integer", + "description": "The index of the content part in the message." + }, + "type": { + "description": "Always `text`.", + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + }, + "text": { + "type": "object", + "properties": { + "value": { + "description": "The data that makes up the text.", + "type": "string" + }, + "annotations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TextAnnotationDelta" + } + } + } + } + }, + "required": [ + "index", + "type" + ] + }, + "MessageDeltaObject": { + "type": "object", + "title": "Message delta object", + "description": "Represents a message delta i.e. any changed fields on a message during streaming.\n", + "properties": { + "id": { + "description": "The identifier of the message, which can be referenced in API endpoints.", + "type": "string" + }, + "object": { + "description": "The object type, which is always `thread.message.delta`.", + "type": "string", + "enum": [ + "thread.message.delta" + ], + "x-stainless-const": true + }, + "delta": { + "description": "The delta containing the fields that have changed on the Message.", + "type": "object", + "properties": { + "role": { + "description": "The entity that produced the message. One of `user` or `assistant`.", + "type": "string", + "enum": [ + "user", + "assistant" + ] + }, + "content": { + "description": "The content of the message in array of text and/or images.", + "type": "array", + "items": { + "$ref": "#/components/schemas/MessageContentDelta" + } + } + } + } + }, + "required": [ + "id", + "object", + "delta" + ], + "x-oaiMeta": { + "name": "The message delta object", + "beta": true, + "example": "{\n \"id\": \"msg_123\",\n \"object\": \"thread.message.delta\",\n \"delta\": {\n \"content\": [\n {\n \"index\": 0,\n \"type\": \"text\",\n \"text\": { \"value\": \"Hello\", \"annotations\": [] }\n }\n ]\n }\n}\n" + } + }, + "MessageObject": { + "type": "object", + "title": "The message object", + "description": "Represents a message within a [thread](https://platform.openai.com/docs/api-reference/threads).", + "properties": { + "id": { + "description": "The identifier, which can be referenced in API endpoints.", + "type": "string" + }, + "object": { + "description": "The object type, which is always `thread.message`.", + "type": "string", + "enum": [ + "thread.message" + ], + "x-stainless-const": true + }, + "created_at": { + "description": "The Unix timestamp (in seconds) for when the message was created.", + "type": "integer" + }, + "thread_id": { + "description": "The [thread](https://platform.openai.com/docs/api-reference/threads) ID that this message belongs to.", + "type": "string" + }, + "status": { + "description": "The status of the message, which can be either `in_progress`, `incomplete`, or `completed`.", + "type": "string", + "enum": [ + "in_progress", + "incomplete", + "completed" + ] + }, + "incomplete_details": { + "description": "On an incomplete message, details about why the message is incomplete.", + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "The reason the message is incomplete.", + "enum": [ + "content_filter", + "max_tokens", + "run_cancelled", + "run_expired", + "run_failed" + ] + } + }, + "nullable": true, + "required": [ + "reason" + ] + }, + "completed_at": { + "description": "The Unix timestamp (in seconds) for when the message was completed.", + "type": "integer", + "nullable": true + }, + "incomplete_at": { + "description": "The Unix timestamp (in seconds) for when the message was marked as incomplete.", + "type": "integer", + "nullable": true + }, + "role": { + "description": "The entity that produced the message. One of `user` or `assistant`.", + "type": "string", + "enum": [ + "user", + "assistant" + ] + }, + "content": { + "description": "The content of the message in array of text and/or images.", + "type": "array", + "items": { + "$ref": "#/components/schemas/MessageContent" + } + }, + "assistant_id": { + "description": "If applicable, the ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) that authored this message.", + "type": "string", + "nullable": true + }, + "run_id": { + "description": "The ID of the [run](https://platform.openai.com/docs/api-reference/runs) associated with the creation of this message. Value is `null` when messages are created manually using the create message or create thread endpoints.", + "type": "string", + "nullable": true + }, + "attachments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "file_id": { + "type": "string", + "description": "The ID of the file to attach to the message." + }, + "tools": { + "description": "The tools to add this file to.", + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/AssistantToolsCode" + }, + { + "$ref": "#/components/schemas/AssistantToolsFileSearchTypeOnly" + } + ] + } + } + } + }, + "description": "A list of files attached to the message, and the tools they were added to.", + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + }, + "required": [ + "id", + "object", + "created_at", + "thread_id", + "status", + "incomplete_details", + "completed_at", + "incomplete_at", + "role", + "content", + "assistant_id", + "run_id", + "attachments", + "metadata" + ], + "x-oaiMeta": { + "name": "The message object", + "beta": true, + "example": "{\n \"id\": \"msg_abc123\",\n \"object\": \"thread.message\",\n \"created_at\": 1698983503,\n \"thread_id\": \"thread_abc123\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": {\n \"value\": \"Hi! How can I help you today?\",\n \"annotations\": []\n }\n }\n ],\n \"assistant_id\": \"asst_abc123\",\n \"run_id\": \"run_abc123\",\n \"attachments\": [],\n \"metadata\": {}\n}\n" + } + }, + "MessageRequestContentTextObject": { + "title": "Text", + "type": "object", + "description": "The text content that is part of a message.", + "properties": { + "type": { + "description": "Always `text`.", + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "Text content to be sent to the model" + } + }, + "required": [ + "type", + "text" + ] + }, + "MessageStreamEvent": { + "anyOf": [ + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.message.created" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/MessageObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) is created.", + "x-oaiMeta": { + "dataDescription": "`data` is a [message](/docs/api-reference/messages/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.message.in_progress" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/MessageObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) moves to an `in_progress` state.", + "x-oaiMeta": { + "dataDescription": "`data` is a [message](/docs/api-reference/messages/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.message.delta" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/MessageDeltaObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when parts of a [Message](https://platform.openai.com/docs/api-reference/messages/object) are being streamed.", + "x-oaiMeta": { + "dataDescription": "`data` is a [message delta](/docs/api-reference/assistants-streaming/message-delta-object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.message.completed" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/MessageObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) is completed.", + "x-oaiMeta": { + "dataDescription": "`data` is a [message](/docs/api-reference/messages/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.message.incomplete" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/MessageObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [message](https://platform.openai.com/docs/api-reference/messages/object) ends before it is completed.", + "x-oaiMeta": { + "dataDescription": "`data` is a [message](/docs/api-reference/messages/object)" + } + } + ], + "discriminator": { + "propertyName": "event" + } + }, + "Metadata": { + "type": "object", + "description": "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard. \n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n", + "additionalProperties": { + "type": "string" + }, + "x-oaiTypeLabel": "map", + "nullable": true + }, + "Model": { + "title": "Model", + "description": "Describes an OpenAI model offering that can be used with the API.", + "properties": { + "id": { + "type": "string", + "description": "The model identifier, which can be referenced in the API endpoints." + }, + "created": { + "type": "integer", + "description": "The Unix timestamp (in seconds) when the model was created." + }, + "object": { + "type": "string", + "description": "The object type, which is always \"model\".", + "enum": [ + "model" + ], + "x-stainless-const": true + }, + "owned_by": { + "type": "string", + "description": "The organization that owns the model." + } + }, + "required": [ + "id", + "object", + "created", + "owned_by" + ], + "x-oaiMeta": { + "name": "The model object", + "example": "{\n \"id\": \"VAR_chat_model_id\",\n \"object\": \"model\",\n \"created\": 1686935002,\n \"owned_by\": \"openai\"\n}\n" + } + }, + "ModelIds": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModelIdsShared" + }, + { + "$ref": "#/components/schemas/ModelIdsResponses" + } + ] + }, + "ModelIdsResponses": { + "example": "gpt-4o", + "anyOf": [ + { + "$ref": "#/components/schemas/ModelIdsShared" + }, + { + "type": "string", + "title": "ResponsesOnlyModel", + "enum": [ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11" + ] + } + ] + }, + "ModelIdsShared": { + "example": "gpt-4o", + "anyOf": [ + { + "type": "string" + }, + { + "$ref": "#/components/schemas/ChatModel" + } + ] + }, + "ModelResponseProperties": { + "type": "object", + "properties": { + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "top_logprobs": { + "description": "An integer between 0 and 20 specifying the number of most likely tokens to\nreturn at each token position, each with an associated log probability.\n", + "type": "integer", + "minimum": 0, + "maximum": 20, + "nullable": true + }, + "temperature": { + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 1, + "example": 1, + "nullable": true, + "description": "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }, + "top_p": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 1, + "example": 1, + "nullable": true, + "description": "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }, + "user": { + "type": "string", + "example": "user-1234", + "deprecated": true, + "description": "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n" + }, + "safety_identifier": { + "type": "string", + "example": "safety-identifier-1234", + "description": "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n" + }, + "prompt_cache_key": { + "type": "string", + "example": "prompt-cache-key-1234", + "description": "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching).\n" + }, + "service_tier": { + "$ref": "#/components/schemas/ServiceTier" + } + } + }, + "ModifyAssistantRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "model": { + "description": "ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n", + "anyOf": [ + { + "type": "string" + }, + { + "$ref": "#/components/schemas/AssistantSupportedModels" + } + ] + }, + "reasoning_effort": { + "$ref": "#/components/schemas/ReasoningEffort" + }, + "name": { + "description": "The name of the assistant. The maximum length is 256 characters.\n", + "type": "string", + "nullable": true, + "maxLength": 256 + }, + "description": { + "description": "The description of the assistant. The maximum length is 512 characters.\n", + "type": "string", + "nullable": true, + "maxLength": 512 + }, + "instructions": { + "description": "The system instructions that the assistant uses. The maximum length is 256,000 characters.\n", + "type": "string", + "nullable": true, + "maxLength": 256000 + }, + "tools": { + "description": "A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n", + "default": [], + "type": "array", + "maxItems": 128, + "items": { + "$ref": "#/components/schemas/AssistantTool" + } + }, + "tool_resources": { + "type": "object", + "description": "A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n", + "properties": { + "code_interpreter": { + "type": "object", + "properties": { + "file_ids": { + "type": "array", + "description": "Overrides the list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + "default": [], + "maxItems": 20, + "items": { + "type": "string" + } + } + } + }, + "file_search": { + "type": "object", + "properties": { + "vector_store_ids": { + "type": "array", + "description": "Overrides the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + "maxItems": 1, + "items": { + "type": "string" + } + } + } + } + }, + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "temperature": { + "description": "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n", + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 1, + "example": 1, + "nullable": true + }, + "top_p": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 1, + "example": 1, + "nullable": true, + "description": "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }, + "response_format": { + "$ref": "#/components/schemas/AssistantsApiResponseFormatOption", + "nullable": true + } + } + }, + "ModifyCertificateRequest": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The updated name for the certificate" + } + }, + "required": [ + "name" + ] + }, + "ModifyMessageRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + }, + "ModifyRunRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + }, + "ModifyThreadRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "tool_resources": { + "type": "object", + "description": "A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n", + "properties": { + "code_interpreter": { + "type": "object", + "properties": { + "file_ids": { + "type": "array", + "description": "A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + "default": [], + "maxItems": 20, + "items": { + "type": "string" + } + } + } + }, + "file_search": { + "type": "object", + "properties": { + "vector_store_ids": { + "type": "array", + "description": "The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + "maxItems": 1, + "items": { + "type": "string" + } + } + } + } + }, + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + }, + "Move": { + "type": "object", + "title": "Move", + "description": "A mouse move action.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "move" + ], + "default": "move", + "description": "Specifies the event type. For a move action, this property is \nalways set to `move`.\n", + "x-stainless-const": true + }, + "x": { + "type": "integer", + "description": "The x-coordinate to move to.\n" + }, + "y": { + "type": "integer", + "description": "The y-coordinate to move to.\n" + } + }, + "required": [ + "type", + "x", + "y" + ] + }, + "OpenAIFile": { + "title": "OpenAIFile", + "description": "The `File` object represents a document that has been uploaded to OpenAI.", + "properties": { + "id": { + "type": "string", + "description": "The file identifier, which can be referenced in the API endpoints." + }, + "bytes": { + "type": "integer", + "description": "The size of the file, in bytes." + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the file was created." + }, + "expires_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the file will expire." + }, + "filename": { + "type": "string", + "description": "The name of the file." + }, + "object": { + "type": "string", + "description": "The object type, which is always `file`.", + "enum": [ + "file" + ], + "x-stainless-const": true + }, + "purpose": { + "type": "string", + "description": "The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`.", + "enum": [ + "assistants", + "assistants_output", + "batch", + "batch_output", + "fine-tune", + "fine-tune-results", + "vision", + "user_data" + ] + }, + "status": { + "type": "string", + "deprecated": true, + "description": "Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`.", + "enum": [ + "uploaded", + "processed", + "error" + ] + }, + "status_details": { + "type": "string", + "deprecated": true, + "description": "Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`." + } + }, + "required": [ + "id", + "object", + "bytes", + "created_at", + "filename", + "purpose", + "status" + ], + "x-oaiMeta": { + "name": "The file object", + "example": "{\n \"id\": \"file-abc123\",\n \"object\": \"file\",\n \"bytes\": 120000,\n \"created_at\": 1677610602,\n \"expires_at\": 1680202602,\n \"filename\": \"salesOverview.pdf\",\n \"purpose\": \"assistants\",\n}\n" + } + }, + "OtherChunkingStrategyResponseParam": { + "type": "object", + "title": "Other Chunking Strategy", + "description": "This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the `chunking_strategy` concept was introduced in the API.", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "Always `other`.", + "enum": [ + "other" + ], + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + "OutputAudio": { + "type": "object", + "title": "Output audio", + "description": "An audio output from the model.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the output audio. Always `output_audio`.\n", + "enum": [ + "output_audio" + ], + "x-stainless-const": true + }, + "data": { + "type": "string", + "description": "Base64-encoded audio data from the model.\n" + }, + "transcript": { + "type": "string", + "description": "The transcript of the audio data from the model.\n" + } + }, + "required": [ + "type", + "data", + "transcript" + ] + }, + "OutputContent": { + "anyOf": [ + { + "$ref": "#/components/schemas/OutputTextContent" + }, + { + "$ref": "#/components/schemas/RefusalContent" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "OutputItem": { + "anyOf": [ + { + "$ref": "#/components/schemas/OutputMessage" + }, + { + "$ref": "#/components/schemas/FileSearchToolCall" + }, + { + "$ref": "#/components/schemas/FunctionToolCall" + }, + { + "$ref": "#/components/schemas/WebSearchToolCall" + }, + { + "$ref": "#/components/schemas/ComputerToolCall" + }, + { + "$ref": "#/components/schemas/ReasoningItem" + }, + { + "$ref": "#/components/schemas/ImageGenToolCall" + }, + { + "$ref": "#/components/schemas/CodeInterpreterToolCall" + }, + { + "$ref": "#/components/schemas/LocalShellToolCall" + }, + { + "$ref": "#/components/schemas/MCPToolCall" + }, + { + "$ref": "#/components/schemas/MCPListTools" + }, + { + "$ref": "#/components/schemas/MCPApprovalRequest" + }, + { + "$ref": "#/components/schemas/CustomToolCall" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "OutputMessage": { + "type": "object", + "title": "Output message", + "description": "An output message from the model.\n", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the output message.\n", + "x-stainless-go-json": "omitzero" + }, + "type": { + "type": "string", + "description": "The type of the output message. Always `message`.\n", + "enum": [ + "message" + ], + "x-stainless-const": true + }, + "role": { + "type": "string", + "description": "The role of the output message. Always `assistant`.\n", + "enum": [ + "assistant" + ], + "x-stainless-const": true + }, + "content": { + "type": "array", + "description": "The content of the output message.\n", + "items": { + "$ref": "#/components/schemas/OutputContent" + } + }, + "status": { + "type": "string", + "description": "The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n", + "enum": [ + "in_progress", + "completed", + "incomplete" + ] + } + }, + "required": [ + "id", + "type", + "role", + "content", + "status" + ] + }, + "ParallelToolCalls": { + "description": "Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use.", + "type": "boolean", + "default": true + }, + "PartialImages": { + "type": "integer", + "maximum": 3, + "minimum": 0, + "default": 0, + "example": 1, + "nullable": true, + "description": "The number of partial images to generate. This parameter is used for\nstreaming responses that return partial images. Value must be between 0 and 3.\nWhen set to 0, the response will be a single image sent in one streaming event.\n\nNote that the final image may be sent before the full number of partial images \nare generated if the full image is generated more quickly.\n" + }, + "PredictionContent": { + "type": "object", + "title": "Static Content", + "description": "Static predicted output content, such as the content of a text file that is\nbeing regenerated.\n", + "required": [ + "type", + "content" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "content" + ], + "description": "The type of the predicted content you want to provide. This type is\ncurrently always `content`.\n", + "x-stainless-const": true + }, + "content": { + "description": "The content that should be matched when generating a model response.\nIf generated tokens would match this content, the entire model response\ncan be returned much more quickly.\n", + "anyOf": [ + { + "type": "string", + "title": "Text content", + "description": "The content used for a Predicted Output. This is often the\ntext of a file you are regenerating with minor changes.\n" + }, + { + "type": "array", + "description": "An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text inputs.", + "title": "Array of content parts", + "items": { + "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartText" + }, + "minItems": 1 + } + ] + } + } + }, + "Project": { + "type": "object", + "description": "Represents an individual project.", + "properties": { + "id": { + "type": "string", + "description": "The identifier, which can be referenced in API endpoints" + }, + "object": { + "type": "string", + "enum": [ + "organization.project" + ], + "description": "The object type, which is always `organization.project`", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the project. This appears in reporting." + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the project was created." + }, + "archived_at": { + "type": "integer", + "nullable": true, + "description": "The Unix timestamp (in seconds) of when the project was archived or `null`." + }, + "status": { + "type": "string", + "enum": [ + "active", + "archived" + ], + "description": "`active` or `archived`" + } + }, + "required": [ + "id", + "object", + "name", + "created_at", + "status" + ], + "x-oaiMeta": { + "name": "The project object", + "example": "{\n \"id\": \"proj_abc\",\n \"object\": \"organization.project\",\n \"name\": \"Project example\",\n \"created_at\": 1711471533,\n \"archived_at\": null,\n \"status\": \"active\"\n}\n" + } + }, + "ProjectApiKey": { + "type": "object", + "description": "Represents an individual API key in a project.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.project.api_key" + ], + "description": "The object type, which is always `organization.project.api_key`", + "x-stainless-const": true + }, + "redacted_value": { + "type": "string", + "description": "The redacted value of the API key" + }, + "name": { + "type": "string", + "description": "The name of the API key" + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the API key was created" + }, + "last_used_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the API key was last used." + }, + "id": { + "type": "string", + "description": "The identifier, which can be referenced in API endpoints" + }, + "owner": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "user", + "service_account" + ], + "description": "`user` or `service_account`" + }, + "user": { + "$ref": "#/components/schemas/ProjectUser" + }, + "service_account": { + "$ref": "#/components/schemas/ProjectServiceAccount" + } + } + } + }, + "required": [ + "object", + "redacted_value", + "name", + "created_at", + "last_used_at", + "id", + "owner" + ], + "x-oaiMeta": { + "name": "The project API key object", + "example": "{\n \"object\": \"organization.project.api_key\",\n \"redacted_value\": \"sk-abc...def\",\n \"name\": \"My API Key\",\n \"created_at\": 1711471533,\n \"last_used_at\": 1711471534,\n \"id\": \"key_abc\",\n \"owner\": {\n \"type\": \"user\",\n \"user\": {\n \"object\": \"organization.project.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"created_at\": 1711471533\n }\n }\n}\n" + } + }, + "ProjectApiKeyDeleteResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.project.api_key.deleted" + ], + "x-stainless-const": true + }, + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + } + }, + "required": [ + "object", + "id", + "deleted" + ] + }, + "ProjectApiKeyListResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProjectApiKey" + } + }, + "first_id": { + "type": "string" + }, + "last_id": { + "type": "string" + }, + "has_more": { + "type": "boolean" + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ProjectCreateRequest": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The friendly name of the project, this name appears in reports." + } + }, + "required": [ + "name" + ] + }, + "ProjectListResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Project" + } + }, + "first_id": { + "type": "string" + }, + "last_id": { + "type": "string" + }, + "has_more": { + "type": "boolean" + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ProjectRateLimit": { + "type": "object", + "description": "Represents a project rate limit config.", + "properties": { + "object": { + "type": "string", + "enum": [ + "project.rate_limit" + ], + "description": "The object type, which is always `project.rate_limit`", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The identifier, which can be referenced in API endpoints." + }, + "model": { + "type": "string", + "description": "The model this rate limit applies to." + }, + "max_requests_per_1_minute": { + "type": "integer", + "description": "The maximum requests per minute." + }, + "max_tokens_per_1_minute": { + "type": "integer", + "description": "The maximum tokens per minute." + }, + "max_images_per_1_minute": { + "type": "integer", + "description": "The maximum images per minute. Only present for relevant models." + }, + "max_audio_megabytes_per_1_minute": { + "type": "integer", + "description": "The maximum audio megabytes per minute. Only present for relevant models." + }, + "max_requests_per_1_day": { + "type": "integer", + "description": "The maximum requests per day. Only present for relevant models." + }, + "batch_1_day_max_input_tokens": { + "type": "integer", + "description": "The maximum batch input tokens per day. Only present for relevant models." + } + }, + "required": [ + "object", + "id", + "model", + "max_requests_per_1_minute", + "max_tokens_per_1_minute" + ], + "x-oaiMeta": { + "name": "The project rate limit object", + "example": "{\n \"object\": \"project.rate_limit\",\n \"id\": \"rl_ada\",\n \"model\": \"ada\",\n \"max_requests_per_1_minute\": 600,\n \"max_tokens_per_1_minute\": 150000,\n \"max_images_per_1_minute\": 10\n}\n" + } + }, + "ProjectRateLimitListResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProjectRateLimit" + } + }, + "first_id": { + "type": "string" + }, + "last_id": { + "type": "string" + }, + "has_more": { + "type": "boolean" + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ProjectRateLimitUpdateRequest": { + "type": "object", + "properties": { + "max_requests_per_1_minute": { + "type": "integer", + "description": "The maximum requests per minute." + }, + "max_tokens_per_1_minute": { + "type": "integer", + "description": "The maximum tokens per minute." + }, + "max_images_per_1_minute": { + "type": "integer", + "description": "The maximum images per minute. Only relevant for certain models." + }, + "max_audio_megabytes_per_1_minute": { + "type": "integer", + "description": "The maximum audio megabytes per minute. Only relevant for certain models." + }, + "max_requests_per_1_day": { + "type": "integer", + "description": "The maximum requests per day. Only relevant for certain models." + }, + "batch_1_day_max_input_tokens": { + "type": "integer", + "description": "The maximum batch input tokens per day. Only relevant for certain models." + } + } + }, + "ProjectServiceAccount": { + "type": "object", + "description": "Represents an individual service account in a project.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.project.service_account" + ], + "description": "The object type, which is always `organization.project.service_account`", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The identifier, which can be referenced in API endpoints" + }, + "name": { + "type": "string", + "description": "The name of the service account" + }, + "role": { + "type": "string", + "enum": [ + "owner", + "member" + ], + "description": "`owner` or `member`" + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the service account was created" + } + }, + "required": [ + "object", + "id", + "name", + "role", + "created_at" + ], + "x-oaiMeta": { + "name": "The project service account object", + "example": "{\n \"object\": \"organization.project.service_account\",\n \"id\": \"svc_acct_abc\",\n \"name\": \"Service Account\",\n \"role\": \"owner\",\n \"created_at\": 1711471533\n}\n" + } + }, + "ProjectServiceAccountApiKey": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.project.service_account.api_key" + ], + "description": "The object type, which is always `organization.project.service_account.api_key`", + "x-stainless-const": true + }, + "value": { + "type": "string" + }, + "name": { + "type": "string" + }, + "created_at": { + "type": "integer" + }, + "id": { + "type": "string" + } + }, + "required": [ + "object", + "value", + "name", + "created_at", + "id" + ] + }, + "ProjectServiceAccountCreateRequest": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the service account being created." + } + }, + "required": [ + "name" + ] + }, + "ProjectServiceAccountCreateResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.project.service_account" + ], + "x-stainless-const": true + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "role": { + "type": "string", + "enum": [ + "member" + ], + "description": "Service accounts can only have one role of type `member`", + "x-stainless-const": true + }, + "created_at": { + "type": "integer" + }, + "api_key": { + "$ref": "#/components/schemas/ProjectServiceAccountApiKey" + } + }, + "required": [ + "object", + "id", + "name", + "role", + "created_at", + "api_key" + ] + }, + "ProjectServiceAccountDeleteResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.project.service_account.deleted" + ], + "x-stainless-const": true + }, + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + } + }, + "required": [ + "object", + "id", + "deleted" + ] + }, + "ProjectServiceAccountListResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProjectServiceAccount" + } + }, + "first_id": { + "type": "string" + }, + "last_id": { + "type": "string" + }, + "has_more": { + "type": "boolean" + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ProjectUpdateRequest": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The updated name of the project, this name appears in reports." + } + }, + "required": [ + "name" + ] + }, + "ProjectUser": { + "type": "object", + "description": "Represents an individual user in a project.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.project.user" + ], + "description": "The object type, which is always `organization.project.user`", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The identifier, which can be referenced in API endpoints" + }, + "name": { + "type": "string", + "description": "The name of the user" + }, + "email": { + "type": "string", + "description": "The email address of the user" + }, + "role": { + "type": "string", + "enum": [ + "owner", + "member" + ], + "description": "`owner` or `member`" + }, + "added_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the project was added." + } + }, + "required": [ + "object", + "id", + "name", + "email", + "role", + "added_at" + ], + "x-oaiMeta": { + "name": "The project user object", + "example": "{\n \"object\": \"organization.project.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n}\n" + } + }, + "ProjectUserCreateRequest": { + "type": "object", + "properties": { + "user_id": { + "type": "string", + "description": "The ID of the user." + }, + "role": { + "type": "string", + "enum": [ + "owner", + "member" + ], + "description": "`owner` or `member`" + } + }, + "required": [ + "user_id", + "role" + ] + }, + "ProjectUserDeleteResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.project.user.deleted" + ], + "x-stainless-const": true + }, + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + } + }, + "required": [ + "object", + "id", + "deleted" + ] + }, + "ProjectUserListResponse": { + "type": "object", + "properties": { + "object": { + "type": "string" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProjectUser" + } + }, + "first_id": { + "type": "string" + }, + "last_id": { + "type": "string" + }, + "has_more": { + "type": "boolean" + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "ProjectUserUpdateRequest": { + "type": "object", + "properties": { + "role": { + "type": "string", + "enum": [ + "owner", + "member" + ], + "description": "`owner` or `member`" + } + }, + "required": [ + "role" + ] + }, + "Prompt": { + "type": "object", + "nullable": true, + "description": "Reference to a prompt template and its variables. \n[Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts).\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique identifier of the prompt template to use." + }, + "version": { + "type": "string", + "description": "Optional version of the prompt template.", + "nullable": true + }, + "variables": { + "$ref": "#/components/schemas/ResponsePromptVariables" + } + } + }, + "RealtimeAudioFormats": { + "anyOf": [ + { + "type": "object", + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported.", + "properties": { + "type": { + "type": "string", + "description": "The audio format. Always `audio/pcm`.", + "enum": [ + "audio/pcm" + ] + }, + "rate": { + "type": "integer", + "description": "The sample rate of the audio. Always `24000`.", + "enum": [ + 24000 + ] + } + } + }, + { + "type": "object", + "title": "PCMU audio format", + "description": "The G.711 μ-law format.", + "properties": { + "type": { + "type": "string", + "description": "The audio format. Always `audio/pcmu`.", + "enum": [ + "audio/pcmu" + ] + } + } + }, + { + "type": "object", + "title": "PCMA audio format", + "description": "The G.711 A-law format.", + "properties": { + "type": { + "type": "string", + "description": "The audio format. Always `audio/pcma`.", + "enum": [ + "audio/pcma" + ] + } + } + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "RealtimeClientEvent": { + "discriminator": { + "propertyName": "type" + }, + "description": "A realtime client event.\n", + "anyOf": [ + { + "$ref": "#/components/schemas/RealtimeClientEventConversationItemCreate" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventConversationItemDelete" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventConversationItemRetrieve" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventConversationItemTruncate" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventInputAudioBufferAppend" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventInputAudioBufferClear" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventOutputAudioBufferClear" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventInputAudioBufferCommit" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventResponseCancel" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventResponseCreate" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventSessionUpdate" + }, + { + "$ref": "#/components/schemas/RealtimeClientEventTranscriptionSessionUpdate" + } + ] + }, + "RealtimeClientEventConversationItemCreate": { + "type": "object", + "description": "Add a new Item to the Conversation's context, including messages, function \ncalls, and function call responses. This event can be used both to populate a \n\"history\" of the conversation and to add new items mid-stream, but has the \ncurrent limitation that it cannot populate assistant audio messages.\n\nIf successful, the server will respond with a `conversation.item.created` \nevent, otherwise an `error` event will be sent.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `conversation.item.create`.", + "x-stainless-const": true, + "const": "conversation.item.create" + }, + "previous_item_id": { + "type": "string", + "description": "The ID of the preceding item after which the new item will be inserted. \nIf not set, the new item will be appended to the end of the conversation.\nIf set to `root`, the new item will be added to the beginning of the conversation.\nIf set to an existing ID, it allows an item to be inserted mid-conversation. If the\nID cannot be found, an error will be returned and the item will not be added.\n" + }, + "item": { + "$ref": "#/components/schemas/RealtimeConversationItem" + } + }, + "required": [ + "type", + "item" + ], + "x-oaiMeta": { + "name": "conversation.item.create", + "group": "realtime", + "example": "{\n \"type\": \"conversation.item.create\",\n \"item\": {\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"input_text\",\n \"text\": \"hi\"\n }\n ]\n },\n \"event_id\": \"b904fba0-0ec4-40af-8bbb-f908a9b26793\",\n \"timestamp\": \"2:30:35 PM\"\n}\n" + } + }, + "RealtimeClientEventConversationItemDelete": { + "type": "object", + "description": "Send this event when you want to remove any item from the conversation \nhistory. The server will respond with a `conversation.item.deleted` event, \nunless the item does not exist in the conversation history, in which case the \nserver will respond with an error.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `conversation.item.delete`.", + "x-stainless-const": true, + "const": "conversation.item.delete" + }, + "item_id": { + "type": "string", + "description": "The ID of the item to delete." + } + }, + "required": [ + "type", + "item_id" + ], + "x-oaiMeta": { + "name": "conversation.item.delete", + "group": "realtime", + "example": "{\n \"event_id\": \"event_901\",\n \"type\": \"conversation.item.delete\",\n \"item_id\": \"msg_003\"\n}\n" + } + }, + "RealtimeClientEventConversationItemRetrieve": { + "type": "object", + "description": "Send this event when you want to retrieve the server's representation of a specific item in the conversation history. This is useful, for example, to inspect user audio after noise cancellation and VAD.\nThe server will respond with a `conversation.item.retrieved` event,\nunless the item does not exist in the conversation history, in which case the\nserver will respond with an error.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `conversation.item.retrieve`.", + "x-stainless-const": true, + "const": "conversation.item.retrieve" + }, + "item_id": { + "type": "string", + "description": "The ID of the item to retrieve." + } + }, + "required": [ + "type", + "item_id" + ], + "x-oaiMeta": { + "name": "conversation.item.retrieve", + "group": "realtime", + "example": "{\n \"event_id\": \"event_901\",\n \"type\": \"conversation.item.retrieve\",\n \"item_id\": \"msg_003\"\n}\n" + } + }, + "RealtimeClientEventConversationItemTruncate": { + "type": "object", + "description": "Send this event to truncate a previous assistant message’s audio. The server \nwill produce audio faster than realtime, so this event is useful when the user \ninterrupts to truncate audio that has already been sent to the client but not \nyet played. This will synchronize the server's understanding of the audio with \nthe client's playback.\n\nTruncating audio will delete the server-side text transcript to ensure there \nis not text in the context that hasn't been heard by the user.\n\nIf successful, the server will respond with a `conversation.item.truncated` \nevent.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `conversation.item.truncate`.", + "x-stainless-const": true, + "const": "conversation.item.truncate" + }, + "item_id": { + "type": "string", + "description": "The ID of the assistant message item to truncate. Only assistant message \nitems can be truncated.\n" + }, + "content_index": { + "type": "integer", + "description": "The index of the content part to truncate. Set this to 0." + }, + "audio_end_ms": { + "type": "integer", + "description": "Inclusive duration up to which audio is truncated, in milliseconds. If \nthe audio_end_ms is greater than the actual audio duration, the server \nwill respond with an error.\n" + } + }, + "required": [ + "type", + "item_id", + "content_index", + "audio_end_ms" + ], + "x-oaiMeta": { + "name": "conversation.item.truncate", + "group": "realtime", + "example": "{\n \"event_id\": \"event_678\",\n \"type\": \"conversation.item.truncate\",\n \"item_id\": \"msg_002\",\n \"content_index\": 0,\n \"audio_end_ms\": 1500\n}\n" + } + }, + "RealtimeClientEventInputAudioBufferAppend": { + "type": "object", + "description": "Send this event to append audio bytes to the input audio buffer. The audio \nbuffer is temporary storage you can write to and later commit. In Server VAD \nmode, the audio buffer is used to detect speech and the server will decide \nwhen to commit. When Server VAD is disabled, you must commit the audio buffer\nmanually.\n\nThe client may choose how much audio to place in each event up to a maximum \nof 15 MiB, for example streaming smaller chunks from the client may allow the \nVAD to be more responsive. Unlike made other client events, the server will \nnot send a confirmation response to this event.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `input_audio_buffer.append`.", + "x-stainless-const": true, + "const": "input_audio_buffer.append" + }, + "audio": { + "type": "string", + "description": "Base64-encoded audio bytes. This must be in the format specified by the \n`input_audio_format` field in the session configuration.\n" + } + }, + "required": [ + "type", + "audio" + ], + "x-oaiMeta": { + "name": "input_audio_buffer.append", + "group": "realtime", + "example": "{\n \"event_id\": \"event_456\",\n \"type\": \"input_audio_buffer.append\",\n \"audio\": \"Base64EncodedAudioData\"\n}\n" + } + }, + "RealtimeClientEventInputAudioBufferClear": { + "type": "object", + "description": "Send this event to clear the audio bytes in the buffer. The server will \nrespond with an `input_audio_buffer.cleared` event.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `input_audio_buffer.clear`.", + "x-stainless-const": true, + "const": "input_audio_buffer.clear" + } + }, + "required": [ + "type" + ], + "x-oaiMeta": { + "name": "input_audio_buffer.clear", + "group": "realtime", + "example": "{\n \"event_id\": \"event_012\",\n \"type\": \"input_audio_buffer.clear\"\n}\n" + } + }, + "RealtimeClientEventInputAudioBufferCommit": { + "type": "object", + "description": "Send this event to commit the user input audio buffer, which will create a \nnew user message item in the conversation. This event will produce an error \nif the input audio buffer is empty. When in Server VAD mode, the client does \nnot need to send this event, the server will commit the audio buffer \nautomatically.\n\nCommitting the input audio buffer will trigger input audio transcription \n(if enabled in session configuration), but it will not create a response \nfrom the model. The server will respond with an `input_audio_buffer.committed` \nevent.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `input_audio_buffer.commit`.", + "x-stainless-const": true, + "const": "input_audio_buffer.commit" + } + }, + "required": [ + "type" + ], + "x-oaiMeta": { + "name": "input_audio_buffer.commit", + "group": "realtime", + "example": "{\n \"event_id\": \"event_789\",\n \"type\": \"input_audio_buffer.commit\"\n}\n" + } + }, + "RealtimeClientEventOutputAudioBufferClear": { + "type": "object", + "description": "**WebRTC Only:** Emit to cut off the current audio response. This will trigger the server to\nstop generating audio and emit a `output_audio_buffer.cleared` event. This\nevent should be preceded by a `response.cancel` client event to stop the\ngeneration of the current response.\n[Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the client event used for error handling." + }, + "type": { + "description": "The event type, must be `output_audio_buffer.clear`.", + "x-stainless-const": true, + "const": "output_audio_buffer.clear" + } + }, + "required": [ + "type" + ], + "x-oaiMeta": { + "name": "output_audio_buffer.clear", + "group": "realtime", + "example": "{\n \"event_id\": \"optional_client_event_id\",\n \"type\": \"output_audio_buffer.clear\"\n}\n" + } + }, + "RealtimeClientEventResponseCancel": { + "type": "object", + "description": "Send this event to cancel an in-progress response. The server will respond \nwith a `response.done` event with a status of `response.status=cancelled`. If \nthere is no response to cancel, the server will respond with an error.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `response.cancel`.", + "x-stainless-const": true, + "const": "response.cancel" + }, + "response_id": { + "type": "string", + "description": "A specific response ID to cancel - if not provided, will cancel an \nin-progress response in the default conversation.\n" + } + }, + "required": [ + "type" + ], + "x-oaiMeta": { + "name": "response.cancel", + "group": "realtime", + "example": "{\n \"event_id\": \"event_567\",\n \"type\": \"response.cancel\"\n}\n" + } + }, + "RealtimeClientEventResponseCreate": { + "type": "object", + "description": "This event instructs the server to create a Response, which means triggering \nmodel inference. When in Server VAD mode, the server will create Responses \nautomatically.\n\nA Response will include at least one Item, and may have two, in which case \nthe second will be a function call. These Items will be appended to the \nconversation history.\n\nThe server will respond with a `response.created` event, events for Items \nand content created, and finally a `response.done` event to indicate the \nResponse is complete.\n\nThe `response.create` event includes inference configuration like \n`instructions`, and `temperature`. These fields will override the Session's \nconfiguration for this Response only.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `response.create`.", + "x-stainless-const": true, + "const": "response.create" + }, + "response": { + "$ref": "#/components/schemas/RealtimeResponseCreateParams" + } + }, + "required": [ + "type" + ], + "x-oaiMeta": { + "name": "response.create", + "group": "realtime", + "example": "{\n \"type\": \"response.create\",\n \"event_id\": \"xxx\",\n \"timestamp\": \"2:30:35 PM\"\n}\n" + } + }, + "RealtimeClientEventSessionUpdate": { + "type": "object", + "description": "Send this event to update the session’s default configuration.\nThe client may send this event at any time to update any field,\nexcept for `voice`. However, note that once a session has been\ninitialized with a particular `model`, it can’t be changed to\nanother model using `session.update`.\n\nWhen the server receives a `session.update`, it will respond\nwith a `session.updated` event showing the full, effective configuration.\nOnly the fields that are present are updated. To clear a field like\n`instructions`, pass an empty string.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `session.update`.", + "x-stainless-const": true, + "const": "session.update" + }, + "session": { + "$ref": "#/components/schemas/RealtimeSessionCreateRequest" + } + }, + "required": [ + "type", + "session" + ], + "x-oaiMeta": { + "name": "session.update", + "group": "realtime", + "example": "{\n \"type\": \"session.update\",\n \"session\": {\n \"type\": \"realtime\",\n \"tools\": [\n {\n \"type\": \"function\",\n \"name\": \"display_color_palette\",\n \"description\": \"\\nCall this function when a user asks for a color palette.\\n\",\n \"parameters\": {\n \"type\": \"object\",\n \"strict\": true,\n \"properties\": {\n \"theme\": {\n \"type\": \"string\",\n \"description\": \"Description of the theme for the color scheme.\"\n },\n \"colors\": {\n \"type\": \"array\",\n \"description\": \"Array of five hex color codes based on the theme.\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Hex color code\"\n }\n }\n },\n \"required\": [\n \"theme\",\n \"colors\"\n ]\n }\n }\n ],\n \"tool_choice\": \"auto\"\n },\n \"event_id\": \"5fc543c4-f59c-420f-8fb9-68c45d1546a7\",\n \"timestamp\": \"2:30:32 PM\"\n}\n" + } + }, + "RealtimeClientEventTranscriptionSessionUpdate": { + "type": "object", + "description": "Send this event to update a transcription session.\n", + "properties": { + "event_id": { + "type": "string", + "description": "Optional client-generated ID used to identify this event." + }, + "type": { + "description": "The event type, must be `transcription_session.update`.", + "x-stainless-const": true, + "const": "transcription_session.update" + }, + "session": { + "$ref": "#/components/schemas/RealtimeTranscriptionSessionCreateRequest" + } + }, + "required": [ + "type", + "session" + ], + "x-oaiMeta": { + "name": "transcription_session.update", + "group": "realtime", + "example": "{\n \"type\": \"transcription_session.update\",\n \"session\": {\n \"input_audio_format\": \"pcm16\",\n \"input_audio_transcription\": {\n \"model\": \"gpt-4o-transcribe\",\n \"prompt\": \"\",\n \"language\": \"\"\n },\n \"turn_detection\": {\n \"type\": \"server_vad\",\n \"threshold\": 0.5,\n \"prefix_padding_ms\": 300,\n \"silence_duration_ms\": 500,\n \"create_response\": true,\n },\n \"input_audio_noise_reduction\": {\n \"type\": \"near_field\"\n },\n \"include\": [\n \"item.input_audio_transcription.logprobs\",\n ]\n }\n}\n" + } + }, + "RealtimeConversationItem": { + "description": "A single item within a Realtime conversation.", + "anyOf": [ + { + "$ref": "#/components/schemas/RealtimeConversationItemMessageSystem" + }, + { + "$ref": "#/components/schemas/RealtimeConversationItemMessageUser" + }, + { + "$ref": "#/components/schemas/RealtimeConversationItemMessageAssistant" + }, + { + "$ref": "#/components/schemas/RealtimeConversationItemFunctionCall" + }, + { + "$ref": "#/components/schemas/RealtimeConversationItemFunctionCallOutput" + }, + { + "$ref": "#/components/schemas/RealtimeMCPApprovalResponse" + }, + { + "$ref": "#/components/schemas/RealtimeMCPListTools" + }, + { + "$ref": "#/components/schemas/RealtimeMCPToolCall" + }, + { + "$ref": "#/components/schemas/RealtimeMCPApprovalRequest" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "RealtimeConversationItemFunctionCall": { + "type": "object", + "title": "Realtime function call item", + "description": "A function call item in a Realtime conversation.", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the item." + }, + "object": { + "type": "string", + "enum": [ + "realtime.item" + ], + "description": "Identifier for the API object being returned - always `realtime.item`.", + "x-stainless-const": true + }, + "type": { + "type": "string", + "enum": [ + "function_call" + ], + "description": "The type of the item. Always `function_call`.", + "x-stainless-const": true + }, + "status": { + "type": "string", + "enum": [ + "completed", + "incomplete", + "in_progress" + ], + "description": "The status of the item. Has no effect on the conversation." + }, + "call_id": { + "type": "string", + "description": "The ID of the function call." + }, + "name": { + "type": "string", + "description": "The name of the function being called." + }, + "arguments": { + "type": "string", + "description": "The arguments of the function call." + } + }, + "required": [ + "type", + "name", + "arguments" + ] + }, + "RealtimeConversationItemFunctionCallOutput": { + "type": "object", + "title": "Realtime function call output item", + "description": "A function call output item in a Realtime conversation.", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the item." + }, + "object": { + "type": "string", + "enum": [ + "realtime.item" + ], + "description": "Identifier for the API object being returned - always `realtime.item`.", + "x-stainless-const": true + }, + "type": { + "type": "string", + "enum": [ + "function_call_output" + ], + "description": "The type of the item. Always `function_call_output`.", + "x-stainless-const": true + }, + "status": { + "type": "string", + "enum": [ + "completed", + "incomplete", + "in_progress" + ], + "description": "The status of the item. Has no effect on the conversation." + }, + "call_id": { + "type": "string", + "description": "The ID of the function call this output is for." + }, + "output": { + "type": "string", + "description": "The output of the function call." + } + }, + "required": [ + "type", + "call_id", + "output" + ] + }, + "RealtimeConversationItemMessageAssistant": { + "type": "object", + "title": "Realtime assistant message item", + "description": "An assistant message item in a Realtime conversation.", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the item." + }, + "object": { + "type": "string", + "enum": [ + "realtime.item" + ], + "description": "Identifier for the API object being returned - always `realtime.item`.", + "x-stainless-const": true + }, + "type": { + "type": "string", + "enum": [ + "message" + ], + "description": "The type of the item. Always `message`.", + "x-stainless-const": true + }, + "status": { + "type": "string", + "enum": [ + "completed", + "incomplete", + "in_progress" + ], + "description": "The status of the item. Has no effect on the conversation." + }, + "role": { + "type": "string", + "enum": [ + "assistant" + ], + "description": "The role of the message sender. Always `assistant`.", + "x-stainless-const": true + }, + "content": { + "type": "array", + "description": "The content of the message.", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ], + "description": "The content type. Always `text` for assistant messages.", + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text content." + } + } + } + } + }, + "required": [ + "type", + "role", + "content" + ] + }, + "RealtimeConversationItemMessageSystem": { + "type": "object", + "title": "Realtime system message item", + "description": "A system message item in a Realtime conversation.", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the item." + }, + "object": { + "type": "string", + "enum": [ + "realtime.item" + ], + "description": "Identifier for the API object being returned - always `realtime.item`.", + "x-stainless-const": true + }, + "type": { + "type": "string", + "enum": [ + "message" + ], + "description": "The type of the item. Always `message`.", + "x-stainless-const": true + }, + "status": { + "type": "string", + "enum": [ + "completed", + "incomplete", + "in_progress" + ], + "description": "The status of the item. Has no effect on the conversation." + }, + "role": { + "type": "string", + "enum": [ + "system" + ], + "description": "The role of the message sender. Always `system`.", + "x-stainless-const": true + }, + "content": { + "type": "array", + "description": "The content of the message.", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "input_text" + ], + "description": "The content type. Always `input_text` for system messages.", + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text content." + } + } + } + } + }, + "required": [ + "type", + "role", + "content" + ] + }, + "RealtimeConversationItemMessageUser": { + "type": "object", + "title": "Realtime user message item", + "description": "A user message item in a Realtime conversation.", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the item." + }, + "object": { + "type": "string", + "enum": [ + "realtime.item" + ], + "description": "Identifier for the API object being returned - always `realtime.item`.", + "x-stainless-const": true + }, + "type": { + "type": "string", + "enum": [ + "message" + ], + "description": "The type of the item. Always `message`.", + "x-stainless-const": true + }, + "status": { + "type": "string", + "enum": [ + "completed", + "incomplete", + "in_progress" + ], + "description": "The status of the item. Has no effect on the conversation." + }, + "role": { + "type": "string", + "enum": [ + "user" + ], + "description": "The role of the message sender. Always `user`.", + "x-stainless-const": true + }, + "content": { + "type": "array", + "description": "The content of the message.", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "input_text", + "input_audio" + ], + "description": "The content type (`input_text` or `input_audio`)." + }, + "text": { + "type": "string", + "description": "The text content (for `input_text`)." + }, + "audio": { + "type": "string", + "description": "Base64-encoded audio bytes (for `input_audio`)." + }, + "transcript": { + "type": "string", + "description": "Transcript of the audio (for `input_audio`)." + } + } + } + } + }, + "required": [ + "type", + "role", + "content" + ] + }, + "RealtimeConversationItemWithReference": { + "type": "object", + "description": "The item to add to the conversation.", + "properties": { + "id": { + "type": "string", + "description": "For an item of type (`message` | `function_call` | `function_call_output`)\nthis field allows the client to assign the unique ID of the item. It is\nnot required because the server will generate one if not provided.\n\nFor an item of type `item_reference`, this field is required and is a\nreference to any item that has previously existed in the conversation.\n" + }, + "type": { + "type": "string", + "enum": [ + "message", + "function_call", + "function_call_output", + "item_reference" + ], + "description": "The type of the item (`message`, `function_call`, `function_call_output`, `item_reference`).\n" + }, + "object": { + "type": "string", + "enum": [ + "realtime.item" + ], + "description": "Identifier for the API object being returned - always `realtime.item`.\n", + "x-stainless-const": true + }, + "status": { + "type": "string", + "enum": [ + "completed", + "incomplete", + "in_progress" + ], + "description": "The status of the item (`completed`, `incomplete`, `in_progress`). These have no effect \non the conversation, but are accepted for consistency with the \n`conversation.item.created` event.\n" + }, + "role": { + "type": "string", + "enum": [ + "user", + "assistant", + "system" + ], + "description": "The role of the message sender (`user`, `assistant`, `system`), only \napplicable for `message` items.\n" + }, + "content": { + "type": "array", + "description": "The content of the message, applicable for `message` items. \n- Message items of role `system` support only `input_text` content\n- Message items of role `user` support `input_text` and `input_audio` \n content\n- Message items of role `assistant` support `text` content.\n", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "input_text", + "input_audio", + "item_reference", + "text" + ], + "description": "The content type (`input_text`, `input_audio`, `item_reference`, `text`).\n" + }, + "text": { + "type": "string", + "description": "The text content, used for `input_text` and `text` content types.\n" + }, + "id": { + "type": "string", + "description": "ID of a previous conversation item to reference (for `item_reference`\ncontent types in `response.create` events). These can reference both\nclient and server created items.\n" + }, + "audio": { + "type": "string", + "description": "Base64-encoded audio bytes, used for `input_audio` content type.\n" + }, + "transcript": { + "type": "string", + "description": "The transcript of the audio, used for `input_audio` content type.\n" + } + } + } + }, + "call_id": { + "type": "string", + "description": "The ID of the function call (for `function_call` and \n`function_call_output` items). If passed on a `function_call_output` \nitem, the server will check that a `function_call` item with the same \nID exists in the conversation history.\n" + }, + "name": { + "type": "string", + "description": "The name of the function being called (for `function_call` items).\n" + }, + "arguments": { + "type": "string", + "description": "The arguments of the function call (for `function_call` items).\n" + }, + "output": { + "type": "string", + "description": "The output of the function call (for `function_call_output` items).\n" + } + } + }, + "RealtimeCreateClientSecretRequest": { + "type": "object", + "title": "Realtime session configuration", + "description": "Create a session and client secret for the Realtime API. The request can specify\neither a realtime or a transcription session configuration.\n[Learn more about the Realtime API](https://platform.openai.com/docs/guides/realtime).\n", + "properties": { + "expires_after": { + "type": "object", + "title": "Client secret expiration", + "description": "Configuration for the ephemeral token expiration.\n", + "properties": { + "anchor": { + "type": "string", + "enum": [ + "created_at" + ], + "description": "The anchor point for the ephemeral token expiration. Only `created_at` is currently supported.\n", + "default": "created_at", + "x-stainless-const": true + }, + "seconds": { + "type": "integer", + "description": "The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200`.\n", + "minimum": 10, + "maximum": 7200, + "default": 600 + } + } + }, + "session": { + "title": "Session configuration", + "description": "Session configuration to use for the client secret. Choose either a realtime\nsession or a transcription session.\n", + "anyOf": [ + { + "$ref": "#/components/schemas/RealtimeSessionCreateRequest" + }, + { + "$ref": "#/components/schemas/RealtimeTranscriptionSessionCreateRequest" + } + ], + "discriminator": { + "propertyName": "type" + } + } + } + }, + "RealtimeCreateClientSecretResponse": { + "type": "object", + "title": "Realtime session and client secret", + "description": "Response from creating a session and client secret for the Realtime API.\n", + "properties": { + "value": { + "type": "string", + "description": "The generated client secret value." + }, + "expires_at": { + "type": "integer", + "description": "Expiration timestamp for the client secret, in seconds since epoch." + }, + "session": { + "title": "Session configuration", + "description": "The session configuration for either a realtime or transcription session.\n", + "anyOf": [ + { + "$ref": "#/components/schemas/RealtimeSessionCreateResponse" + }, + { + "$ref": "#/components/schemas/RealtimeTranscriptionSessionCreateResponse" + } + ] + } + }, + "required": [ + "value", + "expires_at", + "session" + ], + "x-oaiMeta": { + "name": "Session response object", + "group": "realtime", + "example": "{\n \"value\": \"ek_68af296e8e408191a1120ab6383263c2\",\n \"expires_at\": 1756310470,\n \"session\": {\n \"type\": \"realtime\",\n \"object\": \"realtime.session\",\n \"id\": \"sess_C9CiUVUzUzYIssh3ELY1d\",\n \"model\": \"gpt-4o-realtime-preview\",\n \"output_modalities\": [\n \"audio\"\n ],\n \"instructions\": \"You are a friendly assistant.\",\n \"tools\": [],\n \"tool_choice\": \"auto\",\n \"max_output_tokens\": \"inf\",\n \"tracing\": null,\n \"truncation\": \"auto\",\n \"prompt\": null,\n \"expires_at\": 0,\n \"audio\": {\n \"input\": {\n \"format\": {\n \"type\": \"audio/pcm\",\n \"rate\": 24000\n },\n \"transcription\": null,\n \"noise_reduction\": null,\n \"turn_detection\": {\n \"type\": \"server_vad\",\n \"threshold\": 0.5,\n \"prefix_padding_ms\": 300,\n \"silence_duration_ms\": 200,\n \"idle_timeout_ms\": null,\n \"create_response\": true,\n \"interrupt_response\": true\n }\n },\n \"output\": {\n \"format\": {\n \"type\": \"audio/pcm\",\n \"rate\": 24000\n },\n \"voice\": \"alloy\",\n \"speed\": 1.0\n }\n },\n \"include\": null\n }\n}\n" + } + }, + "RealtimeMCPApprovalRequest": { + "type": "object", + "title": "Realtime MCP approval request", + "description": "A Realtime item requesting human approval of a tool invocation.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp_approval_request" + ], + "description": "The type of the item. Always `mcp_approval_request`.", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the approval request." + }, + "server_label": { + "type": "string", + "description": "The label of the MCP server making the request." + }, + "name": { + "type": "string", + "description": "The name of the tool to run." + }, + "arguments": { + "type": "string", + "description": "A JSON string of arguments for the tool." + } + }, + "required": [ + "type", + "id", + "server_label", + "name", + "arguments" + ] + }, + "RealtimeMCPApprovalResponse": { + "type": "object", + "title": "Realtime MCP approval response", + "description": "A Realtime item responding to an MCP approval request.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp_approval_response" + ], + "description": "The type of the item. Always `mcp_approval_response`.", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the approval response." + }, + "approval_request_id": { + "type": "string", + "description": "The ID of the approval request being answered." + }, + "approve": { + "type": "boolean", + "description": "Whether the request was approved." + }, + "reason": { + "type": "string", + "description": "Optional reason for the decision.", + "nullable": true + } + }, + "required": [ + "type", + "id", + "approval_request_id", + "approve" + ] + }, + "RealtimeMCPHTTPError": { + "type": "object", + "title": "Realtime MCP HTTP error", + "properties": { + "type": { + "type": "string", + "enum": [ + "http_error" + ], + "x-stainless-const": true + }, + "code": { + "type": "integer" + }, + "message": { + "type": "string" + } + }, + "required": [ + "type", + "code", + "message" + ] + }, + "RealtimeMCPListTools": { + "type": "object", + "title": "Realtime MCP list tools", + "description": "A Realtime item listing tools available on an MCP server.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp_list_tools" + ], + "description": "The type of the item. Always `mcp_list_tools`.", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the list." + }, + "server_label": { + "type": "string", + "description": "The label of the MCP server." + }, + "tools": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MCPListToolsTool" + }, + "description": "The tools available on the server." + } + }, + "required": [ + "type", + "server_label", + "tools" + ] + }, + "RealtimeMCPProtocolError": { + "type": "object", + "title": "Realtime MCP protocol error", + "properties": { + "type": { + "type": "string", + "enum": [ + "protocol_error" + ], + "x-stainless-const": true + }, + "code": { + "type": "integer" + }, + "message": { + "type": "string" + } + }, + "required": [ + "type", + "code", + "message" + ] + }, + "RealtimeMCPToolCall": { + "type": "object", + "title": "Realtime MCP tool call", + "description": "A Realtime item representing an invocation of a tool on an MCP server.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp_tool_call" + ], + "description": "The type of the item. Always `mcp_tool_call`.", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the tool call." + }, + "server_label": { + "type": "string", + "description": "The label of the MCP server running the tool." + }, + "name": { + "type": "string", + "description": "The name of the tool that was run." + }, + "arguments": { + "type": "string", + "description": "A JSON string of the arguments passed to the tool." + }, + "approval_request_id": { + "type": "string", + "description": "The ID of an associated approval request, if any.", + "nullable": true + }, + "output": { + "type": "string", + "description": "The output from the tool call.", + "nullable": true + }, + "error": { + "description": "The error from the tool call, if any.", + "nullable": true, + "anyOf": [ + { + "$ref": "#/components/schemas/RealtimeMCPProtocolError" + }, + { + "$ref": "#/components/schemas/RealtimeMCPToolExecutionError" + }, + { + "$ref": "#/components/schemas/RealtimeMCPHTTPError" + } + ], + "discriminator": { + "propertyName": "type" + } + } + }, + "required": [ + "type", + "id", + "server_label", + "name", + "arguments" + ] + }, + "RealtimeMCPToolExecutionError": { + "type": "object", + "title": "Realtime MCP tool execution error", + "properties": { + "type": { + "type": "string", + "enum": [ + "tool_execution_error" + ], + "x-stainless-const": true + }, + "message": { + "type": "string" + } + }, + "required": [ + "type", + "message" + ] + }, + "RealtimeResponse": { + "type": "object", + "description": "The response resource.", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the response." + }, + "object": { + "description": "The object type, must be `realtime.response`.", + "x-stainless-const": true, + "const": "realtime.response" + }, + "status": { + "type": "string", + "enum": [ + "completed", + "cancelled", + "failed", + "incomplete", + "in_progress" + ], + "description": "The final status of the response (`completed`, `cancelled`, `failed`, or \n`incomplete`, `in_progress`).\n" + }, + "status_details": { + "type": "object", + "description": "Additional details about the status.", + "properties": { + "type": { + "type": "string", + "enum": [ + "completed", + "cancelled", + "incomplete", + "failed" + ], + "description": "The type of error that caused the response to fail, corresponding \nwith the `status` field (`completed`, `cancelled`, `incomplete`, \n`failed`).\n" + }, + "reason": { + "type": "string", + "enum": [ + "turn_detected", + "client_cancelled", + "max_output_tokens", + "content_filter" + ], + "description": "The reason the Response did not complete. For a `cancelled` Response, \none of `turn_detected` (the server VAD detected a new start of speech) \nor `client_cancelled` (the client sent a cancel event). For an \n`incomplete` Response, one of `max_output_tokens` or `content_filter` \n(the server-side safety filter activated and cut off the response).\n" + }, + "error": { + "type": "object", + "description": "A description of the error that caused the response to fail, \npopulated when the `status` is `failed`.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of error." + }, + "code": { + "type": "string", + "description": "Error code, if any." + } + } + } + } + }, + "output": { + "type": "array", + "description": "The list of output items generated by the response.", + "items": { + "$ref": "#/components/schemas/RealtimeConversationItem" + } + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "usage": { + "type": "object", + "description": "Usage statistics for the Response, this will correspond to billing. A \nRealtime API session will maintain a conversation context and append new \nItems to the Conversation, thus output from previous turns (text and \naudio tokens) will become the input for later turns.\n", + "properties": { + "total_tokens": { + "type": "integer", + "description": "The total number of tokens in the Response including input and output \ntext and audio tokens.\n" + }, + "input_tokens": { + "type": "integer", + "description": "The number of input tokens used in the Response, including text and \naudio tokens.\n" + }, + "output_tokens": { + "type": "integer", + "description": "The number of output tokens sent in the Response, including text and \naudio tokens.\n" + }, + "input_token_details": { + "type": "object", + "description": "Details about the input tokens used in the Response.", + "properties": { + "cached_tokens": { + "type": "integer", + "description": "The number of cached tokens used in the Response." + }, + "text_tokens": { + "type": "integer", + "description": "The number of text tokens used in the Response." + }, + "audio_tokens": { + "type": "integer", + "description": "The number of audio tokens used in the Response." + } + } + }, + "output_token_details": { + "type": "object", + "description": "Details about the output tokens used in the Response.", + "properties": { + "text_tokens": { + "type": "integer", + "description": "The number of text tokens used in the Response." + }, + "audio_tokens": { + "type": "integer", + "description": "The number of audio tokens used in the Response." + } + } + } + } + }, + "conversation_id": { + "description": "Which conversation the response is added to, determined by the `conversation`\nfield in the `response.create` event. If `auto`, the response will be added to\nthe default conversation and the value of `conversation_id` will be an id like\n`conv_1234`. If `none`, the response will not be added to any conversation and\nthe value of `conversation_id` will be `null`. If responses are being triggered\nby server VAD, the response will be added to the default conversation, thus\nthe `conversation_id` will be an id like `conv_1234`.\n", + "type": "string" + }, + "voice": { + "$ref": "#/components/schemas/VoiceIdsShared", + "description": "The voice the model used to respond.\nCurrent voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n" + }, + "modalities": { + "type": "array", + "description": "The set of modalities the model used to respond. If there are multiple modalities,\nthe model will pick one, for example if `modalities` is `[\"text\", \"audio\"]`, the model\ncould be responding in either text or audio.\n", + "items": { + "type": "string", + "enum": [ + "text", + "audio" + ] + } + }, + "output_audio_format": { + "type": "string", + "enum": [ + "pcm16", + "g711_ulaw", + "g711_alaw" + ], + "description": "The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n" + }, + "temperature": { + "type": "number", + "description": "Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n" + }, + "max_output_tokens": { + "description": "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls, that was used in this response.\n", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string", + "enum": [ + "inf" + ], + "x-stainless-const": true + } + ] + } + } + }, + "RealtimeResponseCreateParams": { + "type": "object", + "description": "Create a new Realtime response with these parameters", + "properties": { + "modalities": { + "type": "array", + "description": "The set of modalities the model can respond with. To disable audio,\nset this to [\"text\"].\n", + "items": { + "type": "string", + "enum": [ + "text", + "audio" + ] + } + }, + "instructions": { + "type": "string", + "description": "The default system instructions (i.e. system message) prepended to model \ncalls. This field allows the client to guide the model on desired \nresponses. The model can be instructed on response content and format, \n(e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good \nresponses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion \ninto your voice\", \"laugh frequently\"). The instructions are not guaranteed \nto be followed by the model, but they provide guidance to the model on the \ndesired behavior.\n\nNote that the server sets default instructions which will be used if this \nfield is not set and are visible in the `session.created` event at the \nstart of the session.\n" + }, + "voice": { + "$ref": "#/components/schemas/VoiceIdsShared", + "description": "The voice the model uses to respond. Voice cannot be changed during the \nsession once the model has responded with audio at least once. Current \nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n" + }, + "output_audio_format": { + "type": "string", + "enum": [ + "pcm16", + "g711_ulaw", + "g711_alaw" + ], + "description": "The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n" + }, + "tools": { + "type": "array", + "description": "Tools (functions) available to the model.", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "function" + ], + "description": "The type of the tool, i.e. `function`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the function." + }, + "description": { + "type": "string", + "description": "The description of the function, including guidance on when and how \nto call it, and guidance about what to tell the user when calling \n(if anything).\n" + }, + "parameters": { + "type": "object", + "description": "Parameters of the function in JSON Schema." + } + } + } + }, + "tool_choice": { + "description": "How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n", + "default": "auto", + "anyOf": [ + { + "$ref": "#/components/schemas/ToolChoiceOptions" + }, + { + "$ref": "#/components/schemas/ToolChoiceFunction" + }, + { + "$ref": "#/components/schemas/ToolChoiceMCP" + } + ] + }, + "temperature": { + "type": "number", + "description": "Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n" + }, + "max_output_tokens": { + "description": "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string", + "enum": [ + "inf" + ], + "x-stainless-const": true + } + ] + }, + "conversation": { + "description": "Controls which conversation the response is added to. Currently supports\n`auto` and `none`, with `auto` as the default value. The `auto` value\nmeans that the contents of the response will be added to the default\nconversation. Set this to `none` to create an out-of-band response which \nwill not add items to default conversation.\n", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "default": "auto", + "enum": [ + "auto", + "none" + ] + } + ] + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "prompt": { + "$ref": "#/components/schemas/Prompt" + }, + "input": { + "type": "array", + "description": "Input items to include in the prompt for the model. Using this field\ncreates a new context for this Response instead of using the default\nconversation. An empty array `[]` will clear the context for this Response.\nNote that this can include references to items from the default conversation.\n", + "items": { + "$ref": "#/components/schemas/RealtimeConversationItem" + } + } + } + }, + "RealtimeServerEvent": { + "discriminator": { + "propertyName": "type" + }, + "description": "A realtime server event.\n", + "anyOf": [ + { + "$ref": "#/components/schemas/RealtimeServerEventConversationCreated" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventConversationItemCreated" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventConversationItemDeleted" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionCompleted" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionDelta" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionFailed" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventConversationItemRetrieved" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventConversationItemTruncated" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventError" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventInputAudioBufferCleared" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventInputAudioBufferCommitted" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventInputAudioBufferSpeechStarted" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventInputAudioBufferSpeechStopped" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventRateLimitsUpdated" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseAudioDelta" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseAudioDone" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseAudioTranscriptDelta" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseAudioTranscriptDone" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseContentPartAdded" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseContentPartDone" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseCreated" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseDone" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDelta" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDone" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseOutputItemAdded" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseOutputItemDone" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseTextDelta" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseTextDone" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventSessionCreated" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventSessionUpdated" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventTranscriptionSessionUpdated" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventTranscriptionSessionCreated" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventOutputAudioBufferStarted" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventOutputAudioBufferStopped" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventOutputAudioBufferCleared" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventConversationItemAdded" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventConversationItemDone" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventInputAudioBufferTimeoutTriggered" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionSegment" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventMCPListToolsInProgress" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventMCPListToolsCompleted" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventMCPListToolsFailed" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseMCPCallArgumentsDelta" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseMCPCallArgumentsDone" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseMCPCallInProgress" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseMCPCallCompleted" + }, + { + "$ref": "#/components/schemas/RealtimeServerEventResponseMCPCallFailed" + } + ] + }, + "RealtimeServerEventConversationCreated": { + "type": "object", + "description": "Returned when a conversation is created. Emitted right after session creation.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `conversation.created`.", + "x-stainless-const": true, + "const": "conversation.created" + }, + "conversation": { + "type": "object", + "description": "The conversation resource.", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the conversation." + }, + "object": { + "description": "The object type, must be `realtime.conversation`.", + "const": "realtime.conversation" + } + } + } + }, + "required": [ + "event_id", + "type", + "conversation" + ], + "x-oaiMeta": { + "name": "conversation.created", + "group": "realtime", + "example": "{\n \"event_id\": \"event_9101\",\n \"type\": \"conversation.created\",\n \"conversation\": {\n \"id\": \"conv_001\",\n \"object\": \"realtime.conversation\"\n }\n}\n" + } + }, + "RealtimeServerEventConversationItemAdded": { + "type": "object", + "description": "Returned when a conversation item is added.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `conversation.item.added`.", + "x-stainless-const": true, + "const": "conversation.item.added" + }, + "previous_item_id": { + "type": "string", + "nullable": true, + "description": "The ID of the item that precedes this one, if any. This is used to\nmaintain ordering when items are inserted.\n" + }, + "item": { + "$ref": "#/components/schemas/RealtimeConversationItem" + } + }, + "required": [ + "event_id", + "type", + "item" + ], + "x-oaiMeta": { + "name": "conversation.item.added", + "group": "realtime", + "example": "{\n \"type\": \"conversation.item.added\",\n \"event_id\": \"event_C9G8pjSJCfRNEhMEnYAVy\",\n \"previous_item_id\": null,\n \"item\": {\n \"id\": \"item_C9G8pGVKYnaZu8PH5YQ9O\",\n \"type\": \"message\",\n \"status\": \"completed\",\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"input_text\",\n \"text\": \"hi\"\n }\n ]\n },\n \"timestamp\": \"2:30:35 PM\"\n}\n" + } + }, + "RealtimeServerEventConversationItemCreated": { + "type": "object", + "description": "Returned when a conversation item is created. There are several scenarios that produce this event:\n - The server is generating a Response, which if successful will produce \n either one or two Items, which will be of type `message` \n (role `assistant`) or type `function_call`.\n - The input audio buffer has been committed, either by the client or the \n server (in `server_vad` mode). The server will take the content of the \n input audio buffer and add it to a new user message Item.\n - The client has sent a `conversation.item.create` event to add a new Item \n to the Conversation.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `conversation.item.created`.", + "x-stainless-const": true, + "const": "conversation.item.created" + }, + "previous_item_id": { + "type": "string", + "nullable": true, + "description": "The ID of the preceding item in the Conversation context, allows the \nclient to understand the order of the conversation. Can be `null` if the \nitem has no predecessor.\n" + }, + "item": { + "$ref": "#/components/schemas/RealtimeConversationItem" + } + }, + "required": [ + "event_id", + "type", + "item" + ], + "x-oaiMeta": { + "name": "conversation.item.created", + "group": "realtime", + "example": "{\n \"event_id\": \"event_1920\",\n \"type\": \"conversation.item.created\",\n \"previous_item_id\": \"msg_002\",\n \"item\": {\n \"id\": \"msg_003\",\n \"object\": \"realtime.item\",\n \"type\": \"message\",\n \"status\": \"completed\",\n \"role\": \"user\",\n \"content\": []\n }\n}\n" + } + }, + "RealtimeServerEventConversationItemDeleted": { + "type": "object", + "description": "Returned when an item in the conversation is deleted by the client with a \n`conversation.item.delete` event. This event is used to synchronize the \nserver's understanding of the conversation history with the client's view.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `conversation.item.deleted`.", + "x-stainless-const": true, + "const": "conversation.item.deleted" + }, + "item_id": { + "type": "string", + "description": "The ID of the item that was deleted." + } + }, + "required": [ + "event_id", + "type", + "item_id" + ], + "x-oaiMeta": { + "name": "conversation.item.deleted", + "group": "realtime", + "example": "{\n \"event_id\": \"event_2728\",\n \"type\": \"conversation.item.deleted\",\n \"item_id\": \"msg_005\"\n}\n" + } + }, + "RealtimeServerEventConversationItemDone": { + "type": "object", + "description": "Returned when a conversation item is finalized.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `conversation.item.done`.", + "x-stainless-const": true, + "const": "conversation.item.done" + }, + "previous_item_id": { + "type": "string", + "nullable": true, + "description": "The ID of the item that precedes this one, if any. This is used to\nmaintain ordering when items are inserted.\n" + }, + "item": { + "$ref": "#/components/schemas/RealtimeConversationItem" + } + }, + "required": [ + "event_id", + "type", + "item" + ], + "x-oaiMeta": { + "name": "conversation.item.done", + "group": "realtime", + "example": "{\n \"type\": \"conversation.item.done\",\n \"event_id\": \"event_C9G8ps2i70P5Wd6OA0ftc\",\n \"previous_item_id\": null,\n \"item\": {\n \"id\": \"item_C9G8pGVKYnaZu8PH5YQ9O\",\n \"type\": \"message\",\n \"status\": \"completed\",\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"input_text\",\n \"text\": \"hi\"\n }\n ]\n },\n \"timestamp\": \"2:30:35 PM\"\n}\n" + } + }, + "RealtimeServerEventConversationItemInputAudioTranscriptionCompleted": { + "type": "object", + "description": "This event is the output of audio transcription for user audio written to the\nuser audio buffer. Transcription begins when the input audio buffer is\ncommitted by the client or server (in `server_vad` mode). Transcription runs\nasynchronously with Response creation, so this event may come before or after\nthe Response events.\n\nRealtime API models accept audio natively, and thus input transcription is a\nseparate process run on a separate ASR (Automatic Speech Recognition) model.\nThe transcript may diverge somewhat from the model's interpretation, and\nshould be treated as a rough guide.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "type": "string", + "enum": [ + "conversation.item.input_audio_transcription.completed" + ], + "description": "The event type, must be\n`conversation.item.input_audio_transcription.completed`.\n", + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the user message item containing the audio." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part containing the audio." + }, + "transcript": { + "type": "string", + "description": "The transcribed text." + }, + "logprobs": { + "type": "array", + "description": "The log probabilities of the transcription.", + "nullable": true, + "items": { + "$ref": "#/components/schemas/LogProbProperties" + } + }, + "usage": { + "type": "object", + "description": "Usage statistics for the transcription.", + "anyOf": [ + { + "$ref": "#/components/schemas/TranscriptTextUsageTokens", + "title": "Token Usage" + }, + { + "$ref": "#/components/schemas/TranscriptTextUsageDuration", + "title": "Duration Usage" + } + ] + } + }, + "required": [ + "event_id", + "type", + "item_id", + "content_index", + "transcript", + "usage" + ], + "x-oaiMeta": { + "name": "conversation.item.input_audio_transcription.completed", + "group": "realtime", + "example": "{\n \"event_id\": \"event_2122\",\n \"type\": \"conversation.item.input_audio_transcription.completed\",\n \"item_id\": \"msg_003\",\n \"content_index\": 0,\n \"transcript\": \"Hello, how are you?\",\n \"usage\": {\n \"type\": \"tokens\",\n \"total_tokens\": 48,\n \"input_tokens\": 38,\n \"input_token_details\": {\n \"text_tokens\": 10,\n \"audio_tokens\": 28,\n },\n \"output_tokens\": 10,\n }\n}\n" + } + }, + "RealtimeServerEventConversationItemInputAudioTranscriptionDelta": { + "type": "object", + "description": "Returned when the text value of an input audio transcription content part is updated.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `conversation.item.input_audio_transcription.delta`.", + "x-stainless-const": true, + "const": "conversation.item.input_audio_transcription.delta" + }, + "item_id": { + "type": "string", + "description": "The ID of the item." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part in the item's content array." + }, + "delta": { + "type": "string", + "description": "The text delta." + }, + "logprobs": { + "type": "array", + "description": "The log probabilities of the transcription.", + "nullable": true, + "items": { + "$ref": "#/components/schemas/LogProbProperties" + } + } + }, + "required": [ + "event_id", + "type", + "item_id" + ], + "x-oaiMeta": { + "name": "conversation.item.input_audio_transcription.delta", + "group": "realtime", + "example": "{\n \"type\": \"conversation.item.input_audio_transcription.delta\",\n \"event_id\": \"event_001\",\n \"item_id\": \"item_001\",\n \"content_index\": 0,\n \"delta\": \"Hello\"\n}\n" + } + }, + "RealtimeServerEventConversationItemInputAudioTranscriptionFailed": { + "type": "object", + "description": "Returned when input audio transcription is configured, and a transcription \nrequest for a user message failed. These events are separate from other \n`error` events so that the client can identify the related Item.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "type": "string", + "enum": [ + "conversation.item.input_audio_transcription.failed" + ], + "description": "The event type, must be\n`conversation.item.input_audio_transcription.failed`.\n", + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the user message item." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part containing the audio." + }, + "error": { + "type": "object", + "description": "Details of the transcription error.", + "properties": { + "type": { + "type": "string", + "description": "The type of error." + }, + "code": { + "type": "string", + "description": "Error code, if any." + }, + "message": { + "type": "string", + "description": "A human-readable error message." + }, + "param": { + "type": "string", + "description": "Parameter related to the error, if any." + } + } + } + }, + "required": [ + "event_id", + "type", + "item_id", + "content_index", + "error" + ], + "x-oaiMeta": { + "name": "conversation.item.input_audio_transcription.failed", + "group": "realtime", + "example": "{\n \"event_id\": \"event_2324\",\n \"type\": \"conversation.item.input_audio_transcription.failed\",\n \"item_id\": \"msg_003\",\n \"content_index\": 0,\n \"error\": {\n \"type\": \"transcription_error\",\n \"code\": \"audio_unintelligible\",\n \"message\": \"The audio could not be transcribed.\",\n \"param\": null\n }\n}\n" + } + }, + "RealtimeServerEventConversationItemInputAudioTranscriptionSegment": { + "type": "object", + "description": "Returned when an input audio transcription segment is identified for an item.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `conversation.item.input_audio_transcription.segment`.", + "x-stainless-const": true, + "const": "conversation.item.input_audio_transcription.segment" + }, + "item_id": { + "type": "string", + "description": "The ID of the item containing the input audio content." + }, + "content_index": { + "type": "integer", + "description": "The index of the input audio content part within the item." + }, + "text": { + "type": "string", + "description": "The text for this segment." + }, + "id": { + "type": "string", + "description": "The segment identifier." + }, + "speaker": { + "type": "string", + "description": "The detected speaker label for this segment." + }, + "start": { + "type": "number", + "format": "float", + "description": "Start time of the segment in seconds." + }, + "end": { + "type": "number", + "format": "float", + "description": "End time of the segment in seconds." + } + }, + "required": [ + "event_id", + "type", + "item_id", + "content_index", + "text", + "id", + "speaker", + "start", + "end" + ], + "x-oaiMeta": { + "name": "conversation.item.input_audio_transcription.segment", + "group": "realtime", + "example": "{\n \"event_id\": \"event_6501\",\n \"type\": \"conversation.item.input_audio_transcription.segment\",\n \"item_id\": \"msg_011\",\n \"content_index\": 0,\n \"text\": \"hello\",\n \"id\": \"seg_0001\",\n \"speaker\": \"spk_1\",\n \"start\": 0.0,\n \"end\": 0.4\n}\n" + } + }, + "RealtimeServerEventConversationItemRetrieved": { + "type": "object", + "description": "Returned when a conversation item is retrieved with `conversation.item.retrieve`.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `conversation.item.retrieved`.", + "x-stainless-const": true, + "const": "conversation.item.retrieved" + }, + "item": { + "$ref": "#/components/schemas/RealtimeConversationItem" + } + }, + "required": [ + "event_id", + "type", + "item" + ], + "x-oaiMeta": { + "name": "conversation.item.retrieved", + "group": "realtime", + "example": "{\n \"event_id\": \"event_1920\",\n \"type\": \"conversation.item.created\",\n \"previous_item_id\": \"msg_002\",\n \"item\": {\n \"id\": \"msg_003\",\n \"object\": \"realtime.item\",\n \"type\": \"message\",\n \"status\": \"completed\",\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"input_audio\",\n \"transcript\": \"hello how are you\",\n \"audio\": \"base64encodedaudio==\"\n }\n ]\n }\n}\n" + } + }, + "RealtimeServerEventConversationItemTruncated": { + "type": "object", + "description": "Returned when an earlier assistant audio message item is truncated by the \nclient with a `conversation.item.truncate` event. This event is used to \nsynchronize the server's understanding of the audio with the client's playback.\n\nThis action will truncate the audio and remove the server-side text transcript \nto ensure there is no text in the context that hasn't been heard by the user.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `conversation.item.truncated`.", + "x-stainless-const": true, + "const": "conversation.item.truncated" + }, + "item_id": { + "type": "string", + "description": "The ID of the assistant message item that was truncated." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part that was truncated." + }, + "audio_end_ms": { + "type": "integer", + "description": "The duration up to which the audio was truncated, in milliseconds.\n" + } + }, + "required": [ + "event_id", + "type", + "item_id", + "content_index", + "audio_end_ms" + ], + "x-oaiMeta": { + "name": "conversation.item.truncated", + "group": "realtime", + "example": "{\n \"event_id\": \"event_2526\",\n \"type\": \"conversation.item.truncated\",\n \"item_id\": \"msg_004\",\n \"content_index\": 0,\n \"audio_end_ms\": 1500\n}\n" + } + }, + "RealtimeServerEventError": { + "type": "object", + "description": "Returned when an error occurs, which could be a client problem or a server \nproblem. Most errors are recoverable and the session will stay open, we \nrecommend to implementors to monitor and log error messages by default.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `error`.", + "x-stainless-const": true, + "const": "error" + }, + "error": { + "type": "object", + "description": "Details of the error.", + "required": [ + "type", + "message" + ], + "properties": { + "type": { + "type": "string", + "description": "The type of error (e.g., \"invalid_request_error\", \"server_error\").\n" + }, + "code": { + "type": "string", + "description": "Error code, if any.", + "nullable": true + }, + "message": { + "type": "string", + "description": "A human-readable error message." + }, + "param": { + "type": "string", + "description": "Parameter related to the error, if any.", + "nullable": true + }, + "event_id": { + "type": "string", + "description": "The event_id of the client event that caused the error, if applicable.\n", + "nullable": true + } + } + } + }, + "required": [ + "event_id", + "type", + "error" + ], + "x-oaiMeta": { + "name": "error", + "group": "realtime", + "example": "{\n \"event_id\": \"event_890\",\n \"type\": \"error\",\n \"error\": {\n \"type\": \"invalid_request_error\",\n \"code\": \"invalid_event\",\n \"message\": \"The 'type' field is missing.\",\n \"param\": null,\n \"event_id\": \"event_567\"\n }\n}\n" + } + }, + "RealtimeServerEventInputAudioBufferCleared": { + "type": "object", + "description": "Returned when the input audio buffer is cleared by the client with a \n`input_audio_buffer.clear` event.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `input_audio_buffer.cleared`.", + "x-stainless-const": true, + "const": "input_audio_buffer.cleared" + } + }, + "required": [ + "event_id", + "type" + ], + "x-oaiMeta": { + "name": "input_audio_buffer.cleared", + "group": "realtime", + "example": "{\n \"event_id\": \"event_1314\",\n \"type\": \"input_audio_buffer.cleared\"\n}\n" + } + }, + "RealtimeServerEventInputAudioBufferCommitted": { + "type": "object", + "description": "Returned when an input audio buffer is committed, either by the client or \nautomatically in server VAD mode. The `item_id` property is the ID of the user\nmessage item that will be created, thus a `conversation.item.created` event \nwill also be sent to the client.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `input_audio_buffer.committed`.", + "x-stainless-const": true, + "const": "input_audio_buffer.committed" + }, + "previous_item_id": { + "type": "string", + "nullable": true, + "description": "The ID of the preceding item after which the new item will be inserted.\nCan be `null` if the item has no predecessor.\n" + }, + "item_id": { + "type": "string", + "description": "The ID of the user message item that will be created." + } + }, + "required": [ + "event_id", + "type", + "item_id" + ], + "x-oaiMeta": { + "name": "input_audio_buffer.committed", + "group": "realtime", + "example": "{\n \"event_id\": \"event_1121\",\n \"type\": \"input_audio_buffer.committed\",\n \"previous_item_id\": \"msg_001\",\n \"item_id\": \"msg_002\"\n}\n" + } + }, + "RealtimeServerEventInputAudioBufferSpeechStarted": { + "type": "object", + "description": "Sent by the server when in `server_vad` mode to indicate that speech has been \ndetected in the audio buffer. This can happen any time audio is added to the \nbuffer (unless speech is already detected). The client may want to use this \nevent to interrupt audio playback or provide visual feedback to the user. \n\nThe client should expect to receive a `input_audio_buffer.speech_stopped` event \nwhen speech stops. The `item_id` property is the ID of the user message item \nthat will be created when speech stops and will also be included in the \n`input_audio_buffer.speech_stopped` event (unless the client manually commits \nthe audio buffer during VAD activation).\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `input_audio_buffer.speech_started`.", + "x-stainless-const": true, + "const": "input_audio_buffer.speech_started" + }, + "audio_start_ms": { + "type": "integer", + "description": "Milliseconds from the start of all audio written to the buffer during the \nsession when speech was first detected. This will correspond to the \nbeginning of audio sent to the model, and thus includes the \n`prefix_padding_ms` configured in the Session.\n" + }, + "item_id": { + "type": "string", + "description": "The ID of the user message item that will be created when speech stops.\n" + } + }, + "required": [ + "event_id", + "type", + "audio_start_ms", + "item_id" + ], + "x-oaiMeta": { + "name": "input_audio_buffer.speech_started", + "group": "realtime", + "example": "{\n \"event_id\": \"event_1516\",\n \"type\": \"input_audio_buffer.speech_started\",\n \"audio_start_ms\": 1000,\n \"item_id\": \"msg_003\"\n}\n" + } + }, + "RealtimeServerEventInputAudioBufferSpeechStopped": { + "type": "object", + "description": "Returned in `server_vad` mode when the server detects the end of speech in \nthe audio buffer. The server will also send an `conversation.item.created` \nevent with the user message item that is created from the audio buffer.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `input_audio_buffer.speech_stopped`.", + "x-stainless-const": true, + "const": "input_audio_buffer.speech_stopped" + }, + "audio_end_ms": { + "type": "integer", + "description": "Milliseconds since the session started when speech stopped. This will \ncorrespond to the end of audio sent to the model, and thus includes the \n`min_silence_duration_ms` configured in the Session.\n" + }, + "item_id": { + "type": "string", + "description": "The ID of the user message item that will be created." + } + }, + "required": [ + "event_id", + "type", + "audio_end_ms", + "item_id" + ], + "x-oaiMeta": { + "name": "input_audio_buffer.speech_stopped", + "group": "realtime", + "example": "{\n \"event_id\": \"event_1718\",\n \"type\": \"input_audio_buffer.speech_stopped\",\n \"audio_end_ms\": 2000,\n \"item_id\": \"msg_003\"\n}\n" + } + }, + "RealtimeServerEventInputAudioBufferTimeoutTriggered": { + "type": "object", + "description": "Returned when the server VAD timeout is triggered for the input audio buffer.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `input_audio_buffer.timeout_triggered`.", + "x-stainless-const": true, + "const": "input_audio_buffer.timeout_triggered" + }, + "audio_start_ms": { + "type": "integer", + "description": "Millisecond offset where speech started within the buffered audio." + }, + "audio_end_ms": { + "type": "integer", + "description": "Millisecond offset where speech ended within the buffered audio." + }, + "item_id": { + "type": "string", + "description": "The ID of the item associated with this segment." + } + }, + "required": [ + "event_id", + "type", + "audio_start_ms", + "audio_end_ms", + "item_id" + ], + "x-oaiMeta": { + "name": "input_audio_buffer.timeout_triggered", + "group": "realtime", + "example": "{\n \"event_id\": \"event_6401\",\n \"type\": \"input_audio_buffer.timeout_triggered\",\n \"audio_start_ms\": 1200,\n \"audio_end_ms\": 2150,\n \"item_id\": \"msg_010\"\n}\n" + } + }, + "RealtimeServerEventMCPListToolsCompleted": { + "type": "object", + "description": "Returned when listing MCP tools has completed for an item.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `mcp_list_tools.completed`.", + "x-stainless-const": true, + "const": "mcp_list_tools.completed" + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP list tools item." + } + }, + "required": [ + "event_id", + "type", + "item_id" + ], + "x-oaiMeta": { + "name": "mcp_list_tools.completed", + "group": "realtime", + "example": "{\n \"event_id\": \"event_6102\",\n \"type\": \"mcp_list_tools.completed\",\n \"item_id\": \"mcp_list_tools_001\"\n}\n" + } + }, + "RealtimeServerEventMCPListToolsFailed": { + "type": "object", + "description": "Returned when listing MCP tools has failed for an item.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `mcp_list_tools.failed`.", + "x-stainless-const": true, + "const": "mcp_list_tools.failed" + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP list tools item." + } + }, + "required": [ + "event_id", + "type", + "item_id" + ], + "x-oaiMeta": { + "name": "mcp_list_tools.failed", + "group": "realtime", + "example": "{\n \"event_id\": \"event_6103\",\n \"type\": \"mcp_list_tools.failed\",\n \"item_id\": \"mcp_list_tools_001\"\n}\n" + } + }, + "RealtimeServerEventMCPListToolsInProgress": { + "type": "object", + "description": "Returned when listing MCP tools is in progress for an item.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `mcp_list_tools.in_progress`.", + "x-stainless-const": true, + "const": "mcp_list_tools.in_progress" + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP list tools item." + } + }, + "required": [ + "event_id", + "type", + "item_id" + ], + "x-oaiMeta": { + "name": "mcp_list_tools.in_progress", + "group": "realtime", + "example": "{\n \"event_id\": \"event_6101\",\n \"type\": \"mcp_list_tools.in_progress\",\n \"item_id\": \"mcp_list_tools_001\"\n}\n" + } + }, + "RealtimeServerEventOutputAudioBufferCleared": { + "type": "object", + "description": "**WebRTC Only:** Emitted when the output audio buffer is cleared. This happens either in VAD\nmode when the user has interrupted (`input_audio_buffer.speech_started`),\nor when the client has emitted the `output_audio_buffer.clear` event to manually\ncut off the current audio response.\n[Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `output_audio_buffer.cleared`.", + "x-stainless-const": true, + "const": "output_audio_buffer.cleared" + }, + "response_id": { + "type": "string", + "description": "The unique ID of the response that produced the audio." + } + }, + "required": [ + "event_id", + "type", + "response_id" + ], + "x-oaiMeta": { + "name": "output_audio_buffer.cleared", + "group": "realtime", + "example": "{\n \"event_id\": \"event_abc123\",\n \"type\": \"output_audio_buffer.cleared\",\n \"response_id\": \"resp_abc123\"\n}\n" + } + }, + "RealtimeServerEventOutputAudioBufferStarted": { + "type": "object", + "description": "**WebRTC Only:** Emitted when the server begins streaming audio to the client. This event is\nemitted after an audio content part has been added (`response.content_part.added`)\nto the response.\n[Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `output_audio_buffer.started`.", + "x-stainless-const": true, + "const": "output_audio_buffer.started" + }, + "response_id": { + "type": "string", + "description": "The unique ID of the response that produced the audio." + } + }, + "required": [ + "event_id", + "type", + "response_id" + ], + "x-oaiMeta": { + "name": "output_audio_buffer.started", + "group": "realtime", + "example": "{\n \"event_id\": \"event_abc123\",\n \"type\": \"output_audio_buffer.started\",\n \"response_id\": \"resp_abc123\"\n}\n" + } + }, + "RealtimeServerEventOutputAudioBufferStopped": { + "type": "object", + "description": "**WebRTC Only:** Emitted when the output audio buffer has been completely drained on the server,\nand no more audio is forthcoming. This event is emitted after the full response\ndata has been sent to the client (`response.done`).\n[Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `output_audio_buffer.stopped`.", + "x-stainless-const": true, + "const": "output_audio_buffer.stopped" + }, + "response_id": { + "type": "string", + "description": "The unique ID of the response that produced the audio." + } + }, + "required": [ + "event_id", + "type", + "response_id" + ], + "x-oaiMeta": { + "name": "output_audio_buffer.stopped", + "group": "realtime", + "example": "{\n \"event_id\": \"event_abc123\",\n \"type\": \"output_audio_buffer.stopped\",\n \"response_id\": \"resp_abc123\"\n}\n" + } + }, + "RealtimeServerEventRateLimitsUpdated": { + "type": "object", + "description": "Emitted at the beginning of a Response to indicate the updated rate limits. \nWhen a Response is created some tokens will be \"reserved\" for the output \ntokens, the rate limits shown here reflect that reservation, which is then \nadjusted accordingly once the Response is completed.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `rate_limits.updated`.", + "x-stainless-const": true, + "const": "rate_limits.updated" + }, + "rate_limits": { + "type": "array", + "description": "List of rate limit information.", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "requests", + "tokens" + ], + "description": "The name of the rate limit (`requests`, `tokens`).\n" + }, + "limit": { + "type": "integer", + "description": "The maximum allowed value for the rate limit." + }, + "remaining": { + "type": "integer", + "description": "The remaining value before the limit is reached." + }, + "reset_seconds": { + "type": "number", + "description": "Seconds until the rate limit resets." + } + } + } + } + }, + "required": [ + "event_id", + "type", + "rate_limits" + ], + "x-oaiMeta": { + "name": "rate_limits.updated", + "group": "realtime", + "example": "{\n \"event_id\": \"event_5758\",\n \"type\": \"rate_limits.updated\",\n \"rate_limits\": [\n {\n \"name\": \"requests\",\n \"limit\": 1000,\n \"remaining\": 999,\n \"reset_seconds\": 60\n },\n {\n \"name\": \"tokens\",\n \"limit\": 50000,\n \"remaining\": 49950,\n \"reset_seconds\": 60\n }\n ]\n}\n" + } + }, + "RealtimeServerEventResponseAudioDelta": { + "type": "object", + "description": "Returned when the model-generated audio is updated.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.output_audio.delta`.", + "x-stainless-const": true, + "const": "response.output_audio.delta" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part in the item's content array." + }, + "delta": { + "type": "string", + "description": "Base64-encoded audio data delta." + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "content_index", + "delta" + ], + "x-oaiMeta": { + "name": "response.output_audio.delta", + "group": "realtime", + "example": "{\n \"event_id\": \"event_4950\",\n \"type\": \"response.output_audio.delta\",\n \"response_id\": \"resp_001\",\n \"item_id\": \"msg_008\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"delta\": \"Base64EncodedAudioDelta\"\n}\n" + } + }, + "RealtimeServerEventResponseAudioDone": { + "type": "object", + "description": "Returned when the model-generated audio is done. Also emitted when a Response\nis interrupted, incomplete, or cancelled.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.output_audio.done`.", + "x-stainless-const": true, + "const": "response.output_audio.done" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part in the item's content array." + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "content_index" + ], + "x-oaiMeta": { + "name": "response.output_audio.done", + "group": "realtime", + "example": "{\n \"event_id\": \"event_5152\",\n \"type\": \"response.output_audio.done\",\n \"response_id\": \"resp_001\",\n \"item_id\": \"msg_008\",\n \"output_index\": 0,\n \"content_index\": 0\n}\n" + } + }, + "RealtimeServerEventResponseAudioTranscriptDelta": { + "type": "object", + "description": "Returned when the model-generated transcription of audio output is updated.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.output_audio_transcript.delta`.", + "x-stainless-const": true, + "const": "response.output_audio_transcript.delta" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part in the item's content array." + }, + "delta": { + "type": "string", + "description": "The transcript delta." + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "content_index", + "delta" + ], + "x-oaiMeta": { + "name": "response.output_audio_transcript.delta", + "group": "realtime", + "example": "{\n \"event_id\": \"event_4546\",\n \"type\": \"response.output_audio_transcript.delta\",\n \"response_id\": \"resp_001\",\n \"item_id\": \"msg_008\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"delta\": \"Hello, how can I a\"\n}\n" + } + }, + "RealtimeServerEventResponseAudioTranscriptDone": { + "type": "object", + "description": "Returned when the model-generated transcription of audio output is done\nstreaming. Also emitted when a Response is interrupted, incomplete, or\ncancelled.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.output_audio_transcript.done`.", + "x-stainless-const": true, + "const": "response.output_audio_transcript.done" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part in the item's content array." + }, + "transcript": { + "type": "string", + "description": "The final transcript of the audio." + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "content_index", + "transcript" + ], + "x-oaiMeta": { + "name": "response.output_audio_transcript.done", + "group": "realtime", + "example": "{\n \"event_id\": \"event_4748\",\n \"type\": \"response.output_audio_transcript.done\",\n \"response_id\": \"resp_001\",\n \"item_id\": \"msg_008\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"transcript\": \"Hello, how can I assist you today?\"\n}\n" + } + }, + "RealtimeServerEventResponseContentPartAdded": { + "type": "object", + "description": "Returned when a new content part is added to an assistant message item during\nresponse generation.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.content_part.added`.", + "x-stainless-const": true, + "const": "response.content_part.added" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the item to which the content part was added." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part in the item's content array." + }, + "part": { + "type": "object", + "description": "The content part that was added.", + "properties": { + "type": { + "type": "string", + "enum": [ + "text", + "audio" + ], + "description": "The content type (\"text\", \"audio\")." + }, + "text": { + "type": "string", + "description": "The text content (if type is \"text\")." + }, + "audio": { + "type": "string", + "description": "Base64-encoded audio data (if type is \"audio\")." + }, + "transcript": { + "type": "string", + "description": "The transcript of the audio (if type is \"audio\")." + } + } + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "content_index", + "part" + ], + "x-oaiMeta": { + "name": "response.content_part.added", + "group": "realtime", + "example": "{\n \"event_id\": \"event_3738\",\n \"type\": \"response.content_part.added\",\n \"response_id\": \"resp_001\",\n \"item_id\": \"msg_007\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"part\": {\n \"type\": \"text\",\n \"text\": \"\"\n }\n}\n" + } + }, + "RealtimeServerEventResponseContentPartDone": { + "type": "object", + "description": "Returned when a content part is done streaming in an assistant message item.\nAlso emitted when a Response is interrupted, incomplete, or cancelled.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.content_part.done`.", + "x-stainless-const": true, + "const": "response.content_part.done" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part in the item's content array." + }, + "part": { + "type": "object", + "description": "The content part that is done.", + "properties": { + "type": { + "type": "string", + "enum": [ + "text", + "audio" + ], + "description": "The content type (\"text\", \"audio\")." + }, + "text": { + "type": "string", + "description": "The text content (if type is \"text\")." + }, + "audio": { + "type": "string", + "description": "Base64-encoded audio data (if type is \"audio\")." + }, + "transcript": { + "type": "string", + "description": "The transcript of the audio (if type is \"audio\")." + } + } + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "content_index", + "part" + ], + "x-oaiMeta": { + "name": "response.content_part.done", + "group": "realtime", + "example": "{\n \"event_id\": \"event_3940\",\n \"type\": \"response.content_part.done\",\n \"response_id\": \"resp_001\",\n \"item_id\": \"msg_007\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"part\": {\n \"type\": \"text\",\n \"text\": \"Sure, I can help with that.\"\n }\n}\n" + } + }, + "RealtimeServerEventResponseCreated": { + "type": "object", + "description": "Returned when a new Response is created. The first event of response creation,\nwhere the response is in an initial state of `in_progress`.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.created`.", + "x-stainless-const": true, + "const": "response.created" + }, + "response": { + "$ref": "#/components/schemas/RealtimeResponse" + } + }, + "required": [ + "event_id", + "type", + "response" + ], + "x-oaiMeta": { + "name": "response.created", + "group": "realtime", + "example": "{\n \"type\": \"response.created\",\n \"event_id\": \"event_C9G8pqbTEddBSIxbBN6Os\",\n \"response\": {\n \"object\": \"realtime.response\",\n \"id\": \"resp_C9G8p7IH2WxLbkgPNouYL\",\n \"status\": \"in_progress\",\n \"status_details\": null,\n \"output\": [],\n \"conversation_id\": \"conv_C9G8mmBkLhQJwCon3hoJN\",\n \"output_modalities\": [\n \"audio\"\n ],\n \"max_output_tokens\": \"inf\",\n \"audio\": {\n \"output\": {\n \"format\": {\n \"type\": \"audio/pcm\",\n \"rate\": 24000\n },\n \"voice\": \"marin\"\n }\n },\n \"usage\": null,\n \"metadata\": null\n },\n \"timestamp\": \"2:30:35 PM\"\n}\n" + } + }, + "RealtimeServerEventResponseDone": { + "type": "object", + "description": "Returned when a Response is done streaming. Always emitted, no matter the \nfinal state. The Response object included in the `response.done` event will \ninclude all output Items in the Response but will omit the raw audio data.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.done`.", + "x-stainless-const": true, + "const": "response.done" + }, + "response": { + "$ref": "#/components/schemas/RealtimeResponse" + } + }, + "required": [ + "event_id", + "type", + "response" + ], + "x-oaiMeta": { + "name": "response.done", + "group": "realtime", + "example": "{\n \"event_id\": \"event_3132\",\n \"type\": \"response.done\",\n \"response\": {\n \"id\": \"resp_001\",\n \"object\": \"realtime.response\",\n \"status\": \"completed\",\n \"status_details\": null,\n \"output\": [\n {\n \"id\": \"msg_006\",\n \"object\": \"realtime.item\",\n \"type\": \"message\",\n \"status\": \"completed\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": \"Sure, how can I assist you today?\"\n }\n ]\n }\n ],\n \"usage\": {\n \"total_tokens\":275,\n \"input_tokens\":127,\n \"output_tokens\":148,\n \"input_token_details\": {\n \"cached_tokens\":384,\n \"text_tokens\":119,\n \"audio_tokens\":8,\n \"cached_tokens_details\": {\n \"text_tokens\": 128,\n \"audio_tokens\": 256\n }\n },\n \"output_token_details\": {\n \"text_tokens\":36,\n \"audio_tokens\":112\n }\n }\n }\n}\n" + } + }, + "RealtimeServerEventResponseFunctionCallArgumentsDelta": { + "type": "object", + "description": "Returned when the model-generated function call arguments are updated.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.function_call_arguments.delta`.\n", + "x-stainless-const": true, + "const": "response.function_call_arguments.delta" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the function call item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "call_id": { + "type": "string", + "description": "The ID of the function call." + }, + "delta": { + "type": "string", + "description": "The arguments delta as a JSON string." + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "call_id", + "delta" + ], + "x-oaiMeta": { + "name": "response.function_call_arguments.delta", + "group": "realtime", + "example": "{\n \"event_id\": \"event_5354\",\n \"type\": \"response.function_call_arguments.delta\",\n \"response_id\": \"resp_002\",\n \"item_id\": \"fc_001\",\n \"output_index\": 0,\n \"call_id\": \"call_001\",\n \"delta\": \"{\\\"location\\\": \\\"San\\\"\"\n}\n" + } + }, + "RealtimeServerEventResponseFunctionCallArgumentsDone": { + "type": "object", + "description": "Returned when the model-generated function call arguments are done streaming.\nAlso emitted when a Response is interrupted, incomplete, or cancelled.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.function_call_arguments.done`.\n", + "x-stainless-const": true, + "const": "response.function_call_arguments.done" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the function call item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "call_id": { + "type": "string", + "description": "The ID of the function call." + }, + "arguments": { + "type": "string", + "description": "The final arguments as a JSON string." + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "call_id", + "arguments" + ], + "x-oaiMeta": { + "name": "response.function_call_arguments.done", + "group": "realtime", + "example": "{\n \"event_id\": \"event_5556\",\n \"type\": \"response.function_call_arguments.done\",\n \"response_id\": \"resp_002\",\n \"item_id\": \"fc_001\",\n \"output_index\": 0,\n \"call_id\": \"call_001\",\n \"arguments\": \"{\\\"location\\\": \\\"San Francisco\\\"}\"\n}\n" + } + }, + "RealtimeServerEventResponseMCPCallArgumentsDelta": { + "type": "object", + "description": "Returned when MCP tool call arguments are updated during response generation.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.mcp_call_arguments.delta`.", + "x-stainless-const": true, + "const": "response.mcp_call_arguments.delta" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP tool call item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "delta": { + "type": "string", + "description": "The JSON-encoded arguments delta." + }, + "obfuscation": { + "type": "string", + "nullable": true, + "description": "If present, indicates the delta text was obfuscated." + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "delta" + ], + "x-oaiMeta": { + "name": "response.mcp_call_arguments.delta", + "group": "realtime", + "example": "{\n \"event_id\": \"event_6201\",\n \"type\": \"response.mcp_call_arguments.delta\",\n \"response_id\": \"resp_001\",\n \"item_id\": \"mcp_call_001\",\n \"output_index\": 0,\n \"delta\": \"{\\\"partial\\\":true}\"\n}\n" + } + }, + "RealtimeServerEventResponseMCPCallArgumentsDone": { + "type": "object", + "description": "Returned when MCP tool call arguments are finalized during response generation.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.mcp_call_arguments.done`.", + "x-stainless-const": true, + "const": "response.mcp_call_arguments.done" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP tool call item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "arguments": { + "type": "string", + "description": "The final JSON-encoded arguments string." + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "arguments" + ], + "x-oaiMeta": { + "name": "response.mcp_call_arguments.done", + "group": "realtime", + "example": "{\n \"event_id\": \"event_6202\",\n \"type\": \"response.mcp_call_arguments.done\",\n \"response_id\": \"resp_001\",\n \"item_id\": \"mcp_call_001\",\n \"output_index\": 0,\n \"arguments\": \"{\\\"q\\\":\\\"docs\\\"}\"\n}\n" + } + }, + "RealtimeServerEventResponseMCPCallCompleted": { + "type": "object", + "description": "Returned when an MCP tool call has completed successfully.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.mcp_call.completed`.", + "x-stainless-const": true, + "const": "response.mcp_call.completed" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP tool call item." + } + }, + "required": [ + "event_id", + "type", + "output_index", + "item_id" + ], + "x-oaiMeta": { + "name": "response.mcp_call.completed", + "group": "realtime", + "example": "{\n \"event_id\": \"event_6302\",\n \"type\": \"response.mcp_call.completed\",\n \"output_index\": 0,\n \"item_id\": \"mcp_call_001\"\n}\n" + } + }, + "RealtimeServerEventResponseMCPCallFailed": { + "type": "object", + "description": "Returned when an MCP tool call has failed.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.mcp_call.failed`.", + "x-stainless-const": true, + "const": "response.mcp_call.failed" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP tool call item." + } + }, + "required": [ + "event_id", + "type", + "output_index", + "item_id" + ], + "x-oaiMeta": { + "name": "response.mcp_call.failed", + "group": "realtime", + "example": "{\n \"event_id\": \"event_6303\",\n \"type\": \"response.mcp_call.failed\",\n \"output_index\": 0,\n \"item_id\": \"mcp_call_001\"\n}\n" + } + }, + "RealtimeServerEventResponseMCPCallInProgress": { + "type": "object", + "description": "Returned when an MCP tool call has started and is in progress.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.mcp_call.in_progress`.", + "x-stainless-const": true, + "const": "response.mcp_call.in_progress" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP tool call item." + } + }, + "required": [ + "event_id", + "type", + "output_index", + "item_id" + ], + "x-oaiMeta": { + "name": "response.mcp_call.in_progress", + "group": "realtime", + "example": "{\n \"event_id\": \"event_6301\",\n \"type\": \"response.mcp_call.in_progress\",\n \"output_index\": 0,\n \"item_id\": \"mcp_call_001\"\n}\n" + } + }, + "RealtimeServerEventResponseOutputItemAdded": { + "type": "object", + "description": "Returned when a new Item is created during Response generation.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.output_item.added`.", + "x-stainless-const": true, + "const": "response.output_item.added" + }, + "response_id": { + "type": "string", + "description": "The ID of the Response to which the item belongs." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the Response." + }, + "item": { + "$ref": "#/components/schemas/RealtimeConversationItem" + } + }, + "required": [ + "event_id", + "type", + "response_id", + "output_index", + "item" + ], + "x-oaiMeta": { + "name": "response.output_item.added", + "group": "realtime", + "example": "{\n \"event_id\": \"event_3334\",\n \"type\": \"response.output_item.added\",\n \"response_id\": \"resp_001\",\n \"output_index\": 0,\n \"item\": {\n \"id\": \"msg_007\",\n \"object\": \"realtime.item\",\n \"type\": \"message\",\n \"status\": \"in_progress\",\n \"role\": \"assistant\",\n \"content\": []\n }\n}\n" + } + }, + "RealtimeServerEventResponseOutputItemDone": { + "type": "object", + "description": "Returned when an Item is done streaming. Also emitted when a Response is \ninterrupted, incomplete, or cancelled.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.output_item.done`.", + "x-stainless-const": true, + "const": "response.output_item.done" + }, + "response_id": { + "type": "string", + "description": "The ID of the Response to which the item belongs." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the Response." + }, + "item": { + "$ref": "#/components/schemas/RealtimeConversationItem" + } + }, + "required": [ + "event_id", + "type", + "response_id", + "output_index", + "item" + ], + "x-oaiMeta": { + "name": "response.output_item.done", + "group": "realtime", + "example": "{\n \"event_id\": \"event_3536\",\n \"type\": \"response.output_item.done\",\n \"response_id\": \"resp_001\",\n \"output_index\": 0,\n \"item\": {\n \"id\": \"msg_007\",\n \"object\": \"realtime.item\",\n \"type\": \"message\",\n \"status\": \"completed\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"text\",\n \"text\": \"Sure, I can help with that.\"\n }\n ]\n }\n}\n" + } + }, + "RealtimeServerEventResponseTextDelta": { + "type": "object", + "description": "Returned when the text value of an \"output_text\" content part is updated.", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.output_text.delta`.", + "x-stainless-const": true, + "const": "response.output_text.delta" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part in the item's content array." + }, + "delta": { + "type": "string", + "description": "The text delta." + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "content_index", + "delta" + ], + "x-oaiMeta": { + "name": "response.output_text.delta", + "group": "realtime", + "example": "{\n \"event_id\": \"event_4142\",\n \"type\": \"response.output_text.delta\",\n \"response_id\": \"resp_001\",\n \"item_id\": \"msg_007\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"delta\": \"Sure, I can h\"\n}\n" + } + }, + "RealtimeServerEventResponseTextDone": { + "type": "object", + "description": "Returned when the text value of an \"output_text\" content part is done streaming. Also\nemitted when a Response is interrupted, incomplete, or cancelled.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `response.output_text.done`.", + "x-stainless-const": true, + "const": "response.output_text.done" + }, + "response_id": { + "type": "string", + "description": "The ID of the response." + }, + "item_id": { + "type": "string", + "description": "The ID of the item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part in the item's content array." + }, + "text": { + "type": "string", + "description": "The final text content." + } + }, + "required": [ + "event_id", + "type", + "response_id", + "item_id", + "output_index", + "content_index", + "text" + ], + "x-oaiMeta": { + "name": "response.output_text.done", + "group": "realtime", + "example": "{\n \"event_id\": \"event_4344\",\n \"type\": \"response.output_text.done\",\n \"response_id\": \"resp_001\",\n \"item_id\": \"msg_007\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"text\": \"Sure, I can help with that.\"\n}\n" + } + }, + "RealtimeServerEventSessionCreated": { + "type": "object", + "description": "Returned when a Session is created. Emitted automatically when a new \nconnection is established as the first server event. This event will contain \nthe default Session configuration.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `session.created`.", + "x-stainless-const": true, + "const": "session.created" + }, + "session": { + "$ref": "#/components/schemas/RealtimeSession" + } + }, + "required": [ + "event_id", + "type", + "session" + ], + "x-oaiMeta": { + "name": "session.created", + "group": "realtime", + "example": "{\n \"type\": \"session.created\",\n \"event_id\": \"event_C9G5RJeJ2gF77mV7f2B1j\",\n \"session\": {\n \"type\": \"realtime\",\n \"object\": \"realtime.session\",\n \"id\": \"sess_C9G5QPteg4UIbotdKLoYQ\",\n \"model\": \"gpt-4o-realtime-preview-2025-08-25\",\n \"output_modalities\": [\n \"audio\"\n ],\n \"instructions\": \"Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you’re asked about them.\",\n \"tools\": [],\n \"tool_choice\": \"auto\",\n \"max_output_tokens\": \"inf\",\n \"tracing\": null,\n \"prompt\": null,\n \"expires_at\": 1756324625,\n \"audio\": {\n \"input\": {\n \"format\": {\n \"type\": \"audio/pcm\",\n \"rate\": 24000\n },\n \"transcription\": null,\n \"noise_reduction\": null,\n \"turn_detection\": {\n \"type\": \"server_vad\",\n \"threshold\": 0.5,\n \"prefix_padding_ms\": 300,\n \"silence_duration_ms\": 200,\n \"idle_timeout_ms\": null,\n \"create_response\": true,\n \"interrupt_response\": true\n }\n },\n \"output\": {\n \"format\": {\n \"type\": \"audio/pcm\",\n \"rate\": 24000\n },\n \"voice\": \"marin\",\n \"speed\": 1\n }\n },\n \"include\": null\n },\n \"timestamp\": \"2:27:05 PM\"\n}\n" + } + }, + "RealtimeServerEventSessionUpdated": { + "type": "object", + "description": "Returned when a session is updated with a `session.update` event, unless \nthere is an error.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `session.updated`.", + "x-stainless-const": true, + "const": "session.updated" + }, + "session": { + "$ref": "#/components/schemas/RealtimeSession" + } + }, + "required": [ + "event_id", + "type", + "session" + ], + "x-oaiMeta": { + "name": "session.updated", + "group": "realtime", + "example": "{\n \"type\": \"session.updated\",\n \"event_id\": \"event_C9G8mqI3IucaojlVKE8Cs\",\n \"session\": {\n \"type\": \"realtime\",\n \"object\": \"realtime.session\",\n \"id\": \"sess_C9G8l3zp50uFv4qgxfJ8o\",\n \"model\": \"gpt-4o-realtime-preview-2025-08-25\",\n \"output_modalities\": [\n \"audio\"\n ],\n \"instructions\": \"Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you’re asked about them.\",\n \"tools\": [\n {\n \"type\": \"function\",\n \"name\": \"display_color_palette\",\n \"description\": \"\\nCall this function when a user asks for a color palette.\\n\",\n \"parameters\": {\n \"type\": \"object\",\n \"strict\": true,\n \"properties\": {\n \"theme\": {\n \"type\": \"string\",\n \"description\": \"Description of the theme for the color scheme.\"\n },\n \"colors\": {\n \"type\": \"array\",\n \"description\": \"Array of five hex color codes based on the theme.\",\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Hex color code\"\n }\n }\n },\n \"required\": [\n \"theme\",\n \"colors\"\n ]\n }\n }\n ],\n \"tool_choice\": \"auto\",\n \"max_output_tokens\": \"inf\",\n \"tracing\": null,\n \"prompt\": null,\n \"expires_at\": 1756324832,\n \"audio\": {\n \"input\": {\n \"format\": {\n \"type\": \"audio/pcm\",\n \"rate\": 24000\n },\n \"transcription\": null,\n \"noise_reduction\": null,\n \"turn_detection\": {\n \"type\": \"server_vad\",\n \"threshold\": 0.5,\n \"prefix_padding_ms\": 300,\n \"silence_duration_ms\": 200,\n \"idle_timeout_ms\": null,\n \"create_response\": true,\n \"interrupt_response\": true\n }\n },\n \"output\": {\n \"format\": {\n \"type\": \"audio/pcm\",\n \"rate\": 24000\n },\n \"voice\": \"marin\",\n \"speed\": 1\n }\n },\n \"include\": null\n },\n \"timestamp\": \"2:30:32 PM\"\n}\n" + } + }, + "RealtimeServerEventTranscriptionSessionCreated": { + "type": "object", + "description": "Returned when a transcription session is created.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `transcription_session.created`.", + "x-stainless-const": true, + "const": "transcription_session.created" + }, + "session": { + "$ref": "#/components/schemas/RealtimeTranscriptionSessionCreateResponse" + } + }, + "required": [ + "event_id", + "type", + "session" + ], + "x-oaiMeta": { + "name": "transcription_session.created", + "group": "realtime", + "example": "{\n \"event_id\": \"event_5566\",\n \"type\": \"transcription_session.created\",\n \"session\": {\n \"id\": \"sess_001\",\n \"object\": \"realtime.transcription_session\",\n \"input_audio_format\": \"pcm16\",\n \"input_audio_transcription\": {\n \"model\": \"gpt-4o-transcribe\",\n \"prompt\": \"\",\n \"language\": \"\"\n },\n \"turn_detection\": {\n \"type\": \"server_vad\",\n \"threshold\": 0.5,\n \"prefix_padding_ms\": 300,\n \"silence_duration_ms\": 500\n },\n \"input_audio_noise_reduction\": {\n \"type\": \"near_field\"\n },\n \"include\": []\n }\n}\n" + } + }, + "RealtimeServerEventTranscriptionSessionUpdated": { + "type": "object", + "description": "Returned when a transcription session is updated with a `transcription_session.update` event, unless \nthere is an error.\n", + "properties": { + "event_id": { + "type": "string", + "description": "The unique ID of the server event." + }, + "type": { + "description": "The event type, must be `transcription_session.updated`.", + "x-stainless-const": true, + "const": "transcription_session.updated" + }, + "session": { + "$ref": "#/components/schemas/RealtimeTranscriptionSessionCreateResponse" + } + }, + "required": [ + "event_id", + "type", + "session" + ], + "x-oaiMeta": { + "name": "transcription_session.updated", + "group": "realtime", + "example": "{\n \"event_id\": \"event_5678\",\n \"type\": \"transcription_session.updated\",\n \"session\": {\n \"id\": \"sess_001\",\n \"object\": \"realtime.transcription_session\",\n \"input_audio_format\": \"pcm16\",\n \"input_audio_transcription\": {\n \"model\": \"gpt-4o-transcribe\",\n \"prompt\": \"\",\n \"language\": \"\"\n },\n \"turn_detection\": {\n \"type\": \"server_vad\",\n \"threshold\": 0.5,\n \"prefix_padding_ms\": 300,\n \"silence_duration_ms\": 500,\n \"create_response\": true,\n // \"interrupt_response\": false -- this will NOT be returned\n },\n \"input_audio_noise_reduction\": {\n \"type\": \"near_field\"\n },\n \"include\": [\n \"item.input_audio_transcription.avg_logprob\",\n ],\n }\n}\n" + } + }, + "RealtimeSession": { + "type": "object", + "description": "Realtime session object.", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the session that looks like `sess_1234567890abcdef`.\n" + }, + "object": { + "type": "string", + "enum": [ + "realtime.session" + ], + "description": "The object type. Always `realtime.session`." + }, + "modalities": { + "description": "The set of modalities the model can respond with. To disable audio,\nset this to [\"text\"].\n", + "items": { + "type": "string", + "enum": [ + "text", + "audio" + ] + } + }, + "model": { + "type": "string", + "description": "The Realtime model used for this session.\n", + "enum": [ + "gpt-realtime", + "gpt-realtime-2025-08-28", + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-realtime-preview-2025-06-03", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17" + ] + }, + "instructions": { + "type": "string", + "description": "The default system instructions (i.e. system message) prepended to model\ncalls. This field allows the client to guide the model on desired\nresponses. The model can be instructed on response content and format,\n(e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good\nresponses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion\ninto your voice\", \"laugh frequently\"). The instructions are not\nguaranteed to be followed by the model, but they provide guidance to the\nmodel on the desired behavior.\n\n\nNote that the server sets default instructions which will be used if this\nfield is not set and are visible in the `session.created` event at the\nstart of the session.\n" + }, + "voice": { + "$ref": "#/components/schemas/VoiceIdsShared", + "description": "The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n" + }, + "input_audio_format": { + "type": "string", + "default": "pcm16", + "enum": [ + "pcm16", + "g711_ulaw", + "g711_alaw" + ], + "description": "The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\nsingle channel (mono), and little-endian byte order.\n" + }, + "output_audio_format": { + "type": "string", + "default": "pcm16", + "enum": [ + "pcm16", + "g711_ulaw", + "g711_alaw" + ], + "description": "The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, output audio is sampled at a rate of 24kHz.\n" + }, + "input_audio_transcription": { + "type": "object", + "nullable": true, + "description": "Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n", + "properties": { + "model": { + "type": "string", + "description": "The model to use for transcription, current options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1`.\n" + }, + "language": { + "type": "string", + "description": "The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n" + }, + "prompt": { + "type": "string", + "description": "An optional text to guide the model's style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models, the prompt is a free text string, for example \"expect words related to technology\".\n" + } + } + }, + "turn_detection": { + "type": "object", + "nullable": true, + "description": "Configuration for turn detection, ether Server VAD or Semantic VAD. This can be set to `null` to turn off, in which case the client must manually trigger model response.\nServer VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech.\nSemantic VAD is more advanced and uses a turn detection model (in conjunction with VAD) to semantically estimate whether the user has finished speaking, then dynamically sets a timeout based on this probability. For example, if user audio trails off with \"uhhm\", the model will score a low probability of turn end and wait longer for the user to continue speaking. This can be useful for more natural conversations, but may have a higher latency.\n", + "properties": { + "type": { + "type": "string", + "default": "server_vad", + "enum": [ + "server_vad", + "semantic_vad" + ], + "description": "Type of turn detection.\n" + }, + "eagerness": { + "type": "string", + "default": "auto", + "enum": [ + "low", + "medium", + "high", + "auto" + ], + "description": "Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`.\n" + }, + "threshold": { + "type": "number", + "description": "Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n" + }, + "prefix_padding_ms": { + "type": "integer", + "description": "Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n" + }, + "silence_duration_ms": { + "type": "integer", + "description": "Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n" + }, + "create_response": { + "type": "boolean", + "default": true, + "description": "Whether or not to automatically generate a response when a VAD stop event occurs.\n" + }, + "interrupt_response": { + "type": "boolean", + "default": true, + "description": "Whether or not to automatically interrupt any ongoing response with output to the default\nconversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n" + }, + "idle_timeout_ms": { + "type": "integer", + "nullable": true, + "description": "Optional idle timeout after which turn detection will auto-timeout when\nno additional audio is received.\n" + } + } + }, + "input_audio_noise_reduction": { + "type": "object", + "description": "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "near_field", + "far_field" + ], + "description": "Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones.\n" + } + } + }, + "speed": { + "type": "number", + "default": 1, + "maximum": 1.5, + "minimum": 0.25, + "description": "The speed of the model's spoken response. 1.0 is the default speed. 0.25 is\nthe minimum speed. 1.5 is the maximum speed. This value can only be changed\nin between model turns, not while a response is in progress.\n" + }, + "tracing": { + "title": "Tracing Configuration", + "nullable": true, + "description": "Configuration options for tracing. Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n", + "anyOf": [ + { + "type": "string", + "default": "auto", + "description": "Default tracing mode for the session.\n", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "object", + "title": "Tracing Configuration", + "description": "Granular configuration for tracing.\n", + "properties": { + "workflow_name": { + "type": "string", + "description": "The name of the workflow to attach to this trace. This is used to\nname the trace in the traces dashboard.\n" + }, + "group_id": { + "type": "string", + "description": "The group id to attach to this trace to enable filtering and\ngrouping in the traces dashboard.\n" + }, + "metadata": { + "type": "object", + "description": "The arbitrary metadata to attach to this trace to enable\nfiltering in the traces dashboard.\n" + } + } + } + ] + }, + "tools": { + "type": "array", + "description": "Tools (functions) available to the model.", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "function" + ], + "description": "The type of the tool, i.e. `function`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the function." + }, + "description": { + "type": "string", + "description": "The description of the function, including guidance on when and how\nto call it, and guidance about what to tell the user when calling\n(if anything).\n" + }, + "parameters": { + "type": "object", + "description": "Parameters of the function in JSON Schema." + } + } + } + }, + "tool_choice": { + "type": "string", + "default": "auto", + "description": "How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n" + }, + "temperature": { + "type": "number", + "default": 0.8, + "description": "Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a temperature of 0.8 is highly recommended for best performance.\n" + }, + "max_response_output_tokens": { + "description": "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string", + "enum": [ + "inf" + ], + "x-stainless-const": true + } + ] + }, + "expires_at": { + "type": "integer", + "description": "Expiration timestamp for the session, in seconds since epoch." + }, + "prompt": { + "$ref": "#/components/schemas/Prompt", + "nullable": true + }, + "include": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "item.input_audio_transcription.logprobs" + ] + }, + "nullable": true, + "description": "Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + } + } + }, + "RealtimeSessionCreateRequest": { + "type": "object", + "title": "Realtime session configuration", + "description": "Realtime session object configuration.", + "properties": { + "type": { + "type": "string", + "description": "The type of session to create. Always `realtime` for the Realtime API.\n", + "enum": [ + "realtime" + ], + "x-stainless-const": true + }, + "output_modalities": { + "description": "The set of modalities the model can respond with. To disable audio,\nset this to [\"text\"].\n", + "items": { + "type": "string", + "enum": [ + "text", + "audio" + ] + } + }, + "model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "gpt-realtime", + "gpt-realtime-2025-08-28", + "gpt-4o-realtime", + "gpt-4o-mini-realtime", + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-realtime-preview-2025-06-03", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17" + ], + "x-stainless-nominal": false + } + ], + "description": "The Realtime model used for this session.\n" + }, + "instructions": { + "type": "string", + "description": "The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior.\n\nNote that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session.\n" + }, + "audio": { + "type": "object", + "description": "Configuration for input and output audio.\n", + "properties": { + "input": { + "type": "object", + "properties": { + "format": { + "type": "string", + "default": "pcm16", + "enum": [ + "pcm16", + "g711_ulaw", + "g711_alaw" + ], + "description": "The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\nsingle channel (mono), and little-endian byte order.\n" + }, + "transcription": { + "type": "object", + "description": "Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n", + "properties": { + "model": { + "type": "string", + "description": "The model to use for transcription. Current options are\n`whisper-1`, `gpt-4o-transcribe-latest`, `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`,\nand `gpt-4o-transcribe-diarize`.\n", + "enum": [ + "whisper-1", + "gpt-4o-transcribe-latest", + "gpt-4o-mini-transcribe", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize" + ] + }, + "language": { + "type": "string", + "description": "The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n" + }, + "prompt": { + "type": "string", + "description": "An optional text to guide the model's style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models, the prompt is a free text string, for example \"expect words related to technology\".\n" + } + } + }, + "noise_reduction": { + "type": "object", + "description": "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "near_field", + "far_field" + ], + "description": "Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones.\n" + } + } + }, + "turn_detection": { + "type": "object", + "description": "Configuration for turn detection, ether Server VAD or Semantic VAD. This can be set to `null` to turn off, in which case the client must manually trigger model response.\nServer VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech.\nSemantic VAD is more advanced and uses a turn detection model (in conjunction with VAD) to semantically estimate whether the user has finished speaking, then dynamically sets a timeout based on this probability. For example, if user audio trails off with \"uhhm\", the model will score a low probability of turn end and wait longer for the user to continue speaking. This can be useful for more natural conversations, but may have a higher latency.\n", + "properties": { + "type": { + "type": "string", + "default": "server_vad", + "enum": [ + "server_vad", + "semantic_vad" + ], + "description": "Type of turn detection.\n" + }, + "eagerness": { + "type": "string", + "default": "auto", + "enum": [ + "low", + "medium", + "high", + "auto" + ], + "description": "Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`.\n" + }, + "threshold": { + "type": "number", + "description": "Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n" + }, + "prefix_padding_ms": { + "type": "integer", + "description": "Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n" + }, + "silence_duration_ms": { + "type": "integer", + "description": "Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n" + }, + "create_response": { + "type": "boolean", + "default": true, + "description": "Whether or not to automatically generate a response when a VAD stop event occurs.\n" + }, + "interrupt_response": { + "type": "boolean", + "default": true, + "description": "Whether or not to automatically interrupt any ongoing response with output to the default\nconversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n" + }, + "idle_timeout_ms": { + "type": "integer", + "nullable": true, + "description": "Optional idle timeout after which turn detection will auto-timeout when\nno additional audio is received.\n" + } + } + } + } + }, + "output": { + "type": "object", + "properties": { + "format": { + "type": "string", + "default": "pcm16", + "enum": [ + "pcm16", + "g711_ulaw", + "g711_alaw" + ], + "description": "The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, output audio is sampled at a rate of 24kHz.\n" + }, + "voice": { + "$ref": "#/components/schemas/VoiceIdsShared", + "default": "alloy", + "description": "The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, `verse`, `marin`, and `cedar`.\n" + }, + "speed": { + "type": "number", + "default": 1, + "maximum": 1.5, + "minimum": 0.25, + "description": "The speed of the model's spoken response. 1.0 is the default speed. 0.25 is\nthe minimum speed. 1.5 is the maximum speed. This value can only be changed\nin between model turns, not while a response is in progress.\n" + } + } + } + } + }, + "include": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "item.input_audio_transcription.logprobs" + ] + }, + "description": "Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }, + "tracing": { + "title": "Tracing Configuration", + "description": "Configuration options for tracing. Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n", + "nullable": true, + "anyOf": [ + { + "type": "string", + "default": "auto", + "description": "Default tracing mode for the session.\n", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "object", + "title": "Tracing Configuration", + "description": "Granular configuration for tracing.\n", + "properties": { + "workflow_name": { + "type": "string", + "description": "The name of the workflow to attach to this trace. This is used to\nname the trace in the traces dashboard.\n" + }, + "group_id": { + "type": "string", + "description": "The group id to attach to this trace to enable filtering and\ngrouping in the traces dashboard.\n" + }, + "metadata": { + "type": "object", + "description": "The arbitrary metadata to attach to this trace to enable\nfiltering in the traces dashboard.\n" + } + } + } + ] + }, + "tools": { + "type": "array", + "description": "Tools available to the model.", + "items": { + "anyOf": [ + { + "type": "object", + "title": "Function tool", + "properties": { + "type": { + "type": "string", + "enum": [ + "function" + ], + "description": "The type of the tool, i.e. `function`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the function." + }, + "description": { + "type": "string", + "description": "The description of the function, including guidance on when and how\nto call it, and guidance about what to tell the user when calling\n(if anything).\n" + }, + "parameters": { + "type": "object", + "description": "Parameters of the function in JSON Schema." + } + } + }, + { + "$ref": "#/components/schemas/MCPTool" + } + ], + "discriminator": { + "propertyName": "type" + } + } + }, + "tool_choice": { + "description": "How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n", + "default": "auto", + "anyOf": [ + { + "$ref": "#/components/schemas/ToolChoiceOptions" + }, + { + "$ref": "#/components/schemas/ToolChoiceFunction" + }, + { + "$ref": "#/components/schemas/ToolChoiceMCP" + } + ] + }, + "temperature": { + "type": "number", + "default": 0.8, + "description": "Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a temperature of 0.8 is highly recommended for best performance.\n" + }, + "max_output_tokens": { + "description": "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string", + "enum": [ + "inf" + ], + "x-stainless-const": true + } + ] + }, + "truncation": { + "$ref": "#/components/schemas/RealtimeTruncation" + }, + "prompt": { + "$ref": "#/components/schemas/Prompt" + }, + "client_secret": { + "type": "object", + "description": "Configuration options for the generated client secret.\n", + "properties": { + "expires_after": { + "type": "object", + "description": "Configuration for the ephemeral token expiration.\n", + "properties": { + "anchor": { + "type": "string", + "enum": [ + "created_at" + ], + "description": "The anchor point for the ephemeral token expiration. Only `created_at` is currently supported.\n" + }, + "seconds": { + "default": 600, + "type": "integer", + "description": "The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200`.\n" + } + }, + "required": [ + "anchor" + ] + } + } + } + }, + "required": [ + "type", + "model" + ] + }, + "RealtimeSessionCreateResponse": { + "type": "object", + "title": "Realtime session configuration object", + "description": "A Realtime session configuration object.\n", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the session that looks like `sess_1234567890abcdef`.\n" + }, + "object": { + "type": "string", + "description": "The object type. Always `realtime.session`." + }, + "expires_at": { + "type": "integer", + "description": "Expiration timestamp for the session, in seconds since epoch." + }, + "include": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "item.input_audio_transcription.logprobs" + ] + }, + "description": "Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }, + "model": { + "type": "string", + "description": "The Realtime model used for this session." + }, + "output_modalities": { + "description": "The set of modalities the model can respond with. To disable audio,\nset this to [\"text\"].\n", + "items": { + "type": "string", + "enum": [ + "text", + "audio" + ] + } + }, + "instructions": { + "type": "string", + "description": "The default system instructions (i.e. system message) prepended to model\ncalls. This field allows the client to guide the model on desired\nresponses. The model can be instructed on response content and format,\n(e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good\nresponses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion\ninto your voice\", \"laugh frequently\"). The instructions are not guaranteed\nto be followed by the model, but they provide guidance to the model on the\ndesired behavior.\n\nNote that the server sets default instructions which will be used if this\nfield is not set and are visible in the `session.created` event at the\nstart of the session.\n" + }, + "audio": { + "type": "object", + "description": "Configuration for input and output audio for the session.\n", + "properties": { + "input": { + "type": "object", + "properties": { + "format": { + "type": "string", + "description": "The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n" + }, + "transcription": { + "type": "object", + "description": "Configuration for input audio transcription.\n", + "properties": { + "model": { + "type": "string", + "description": "The model to use for transcription.\n" + }, + "language": { + "type": "string", + "description": "The language of the input audio.\n" + }, + "prompt": { + "type": "string", + "description": "Optional text to guide the model's style or continue a previous audio segment.\n" + } + } + }, + "noise_reduction": { + "type": "object", + "description": "Configuration for input audio noise reduction.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "near_field", + "far_field" + ] + } + } + }, + "turn_detection": { + "type": "object", + "description": "Configuration for turn detection.\n", + "properties": { + "type": { + "type": "string", + "description": "Type of turn detection, only `server_vad` is currently supported.\n" + }, + "threshold": { + "type": "number" + }, + "prefix_padding_ms": { + "type": "integer" + }, + "silence_duration_ms": { + "type": "integer" + } + } + } + } + }, + "output": { + "type": "object", + "properties": { + "format": { + "type": "string", + "description": "The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n" + }, + "voice": { + "$ref": "#/components/schemas/VoiceIdsShared" + }, + "speed": { + "type": "number" + } + } + } + } + }, + "tracing": { + "title": "Tracing Configuration", + "description": "Configuration options for tracing. Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n", + "anyOf": [ + { + "type": "string", + "default": "auto", + "description": "Default tracing mode for the session.\n", + "enum": [ + "auto" + ], + "x-stainless-const": true + }, + { + "type": "object", + "title": "Tracing Configuration", + "description": "Granular configuration for tracing.\n", + "properties": { + "workflow_name": { + "type": "string", + "description": "The name of the workflow to attach to this trace. This is used to\nname the trace in the traces dashboard.\n" + }, + "group_id": { + "type": "string", + "description": "The group id to attach to this trace to enable filtering and\ngrouping in the traces dashboard.\n" + }, + "metadata": { + "type": "object", + "description": "The arbitrary metadata to attach to this trace to enable\nfiltering in the traces dashboard.\n" + } + } + } + ] + }, + "turn_detection": { + "type": "object", + "description": "Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n", + "properties": { + "type": { + "type": "string", + "description": "Type of turn detection, only `server_vad` is currently supported.\n" + }, + "threshold": { + "type": "number", + "description": "Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n" + }, + "prefix_padding_ms": { + "type": "integer", + "description": "Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n" + }, + "silence_duration_ms": { + "type": "integer", + "description": "Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n" + } + } + }, + "tools": { + "type": "array", + "description": "Tools (functions) available to the model.", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "function" + ], + "description": "The type of the tool, i.e. `function`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the function." + }, + "description": { + "type": "string", + "description": "The description of the function, including guidance on when and how\nto call it, and guidance about what to tell the user when calling\n(if anything).\n" + }, + "parameters": { + "type": "object", + "description": "Parameters of the function in JSON Schema." + } + } + } + }, + "tool_choice": { + "type": "string", + "description": "How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n" + }, + "max_output_tokens": { + "description": "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n", + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string", + "enum": [ + "inf" + ], + "x-stainless-const": true + } + ] + } + }, + "required": [ + "client_secret" + ], + "x-oaiMeta": { + "name": "The session object", + "group": "realtime", + "example": "{\n \"id\": \"sess_001\",\n \"object\": \"realtime.session\",\n \"expires_at\": 1742188264,\n \"model\": \"gpt-4o-realtime\",\n \"output_modalities\": [\"audio\", \"text\"],\n \"instructions\": \"You are a friendly assistant.\",\n \"tools\": [],\n \"tool_choice\": \"none\",\n \"max_output_tokens\": \"inf\",\n \"tracing\": \"auto\",\n \"truncation\": \"auto\",\n \"prompt\": null,\n \"audio\": {\n \"input\": {\n \"format\": \"pcm16\",\n \"transcription\": { \"model\": \"whisper-1\" },\n \"noise_reduction\": null,\n \"turn_detection\": null\n },\n \"output\": {\n \"format\": \"pcm16\",\n \"voice\": \"alloy\",\n \"speed\": 1.0\n }\n },\n \"client_secret\": {\n \"value\": \"ek_abc123\",\n \"expires_at\": 1234567890\n }\n}\n" + } + }, + "RealtimeTranscriptionSessionCreateRequest": { + "type": "object", + "title": "Realtime transcription session configuration", + "description": "Realtime transcription session object configuration.", + "properties": { + "type": { + "type": "string", + "description": "The type of session to create. Always `transcription` for transcription sessions.\n", + "enum": [ + "transcription" + ], + "x-stainless-const": true + }, + "model": { + "description": "ID of the model to use. The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source Whisper V2 model).\n", + "example": "gpt-4o-transcribe", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "whisper-1", + "gpt-4o-transcribe", + "gpt-4o-mini-transcribe" + ], + "x-stainless-nominal": false + } + ] + }, + "turn_detection": { + "type": "object", + "description": "Configuration for turn detection. Can be set to `null` to turn off. Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech.\n", + "properties": { + "type": { + "type": "string", + "description": "Type of turn detection. Only `server_vad` is currently supported for transcription sessions.\n", + "enum": [ + "server_vad" + ] + }, + "threshold": { + "type": "number", + "description": "Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n" + }, + "prefix_padding_ms": { + "type": "integer", + "description": "Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n" + }, + "silence_duration_ms": { + "type": "integer", + "description": "Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n" + } + } + }, + "input_audio_noise_reduction": { + "type": "object", + "description": "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "near_field", + "far_field" + ], + "description": "Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones.\n" + } + } + }, + "input_audio_format": { + "type": "string", + "default": "pcm16", + "enum": [ + "pcm16", + "g711_ulaw", + "g711_alaw" + ], + "description": "The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\nsingle channel (mono), and little-endian byte order.\n" + }, + "input_audio_transcription": { + "type": "object", + "description": "Configuration for input audio transcription. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n", + "properties": { + "model": { + "type": "string", + "description": "The model to use for transcription, current options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1`.\n", + "enum": [ + "gpt-4o-transcribe", + "gpt-4o-mini-transcribe", + "whisper-1" + ] + }, + "language": { + "type": "string", + "description": "The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n" + }, + "prompt": { + "type": "string", + "description": "An optional text to guide the model's style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models, the prompt is a free text string, for example \"expect words related to technology\".\n" + } + } + }, + "include": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "item.input_audio_transcription.logprobs" + ] + }, + "description": "The set of items to include in the transcription. Current available items are:\n- `item.input_audio_transcription.logprobs`\n" + } + }, + "required": [ + "type", + "model" + ] + }, + "RealtimeTranscriptionSessionCreateResponse": { + "type": "object", + "title": "Realtime transcription session configuration object", + "description": "A Realtime transcription session configuration object.\n", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the session that looks like `sess_1234567890abcdef`.\n" + }, + "object": { + "type": "string", + "description": "The object type. Always `realtime.transcription_session`." + }, + "expires_at": { + "type": "integer", + "description": "Expiration timestamp for the session, in seconds since epoch." + }, + "include": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "item.input_audio_transcription.logprobs" + ] + }, + "description": "Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }, + "audio": { + "type": "object", + "description": "Configuration for input audio for the session.\n", + "properties": { + "input": { + "type": "object", + "properties": { + "format": { + "type": "string", + "description": "The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n" + }, + "transcription": { + "type": "object", + "description": "Configuration of the transcription model.\n", + "properties": { + "model": { + "type": "string", + "description": "The model to use for transcription. Can be `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, or `whisper-1`.\n", + "enum": [ + "gpt-4o-transcribe", + "gpt-4o-mini-transcribe", + "whisper-1" + ] + }, + "language": { + "type": "string", + "description": "The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n" + }, + "prompt": { + "type": "string", + "description": "An optional text to guide the model's style or continue a previous audio segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should match the audio language.\n" + } + } + }, + "noise_reduction": { + "type": "object", + "description": "Configuration for input audio noise reduction.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "near_field", + "far_field" + ] + } + } + }, + "turn_detection": { + "type": "object", + "description": "Configuration for turn detection.\n", + "properties": { + "type": { + "type": "string", + "description": "Type of turn detection, only `server_vad` is currently supported.\n" + }, + "threshold": { + "type": "number" + }, + "prefix_padding_ms": { + "type": "integer" + }, + "silence_duration_ms": { + "type": "integer" + } + } + } + } + } + } + } + }, + "x-oaiMeta": { + "name": "The transcription session object", + "group": "realtime", + "example": "{\n \"id\": \"sess_BBwZc7cFV3XizEyKGDCGL\",\n \"object\": \"realtime.transcription_session\",\n \"expires_at\": 1742188264,\n \"include\": [\"item.input_audio_transcription.logprobs\"],\n \"audio\": {\n \"input\": {\n \"format\": \"pcm16\",\n \"transcription\": {\n \"model\": \"gpt-4o-transcribe\",\n \"language\": null,\n \"prompt\": \"\"\n },\n \"noise_reduction\": null,\n \"turn_detection\": {\n \"type\": \"server_vad\",\n \"threshold\": 0.5,\n \"prefix_padding_ms\": 300,\n \"silence_duration_ms\": 200\n }\n }\n }\n}\n" + } + }, + "RealtimeTruncation": { + "title": "Realtime Truncation Controls", + "description": "Controls how the realtime conversation is truncated prior to model inference.\nThe default is `auto`. When set to `retention_ratio`, the server retains a\nfraction of the conversation tokens prior to the instructions.\n", + "anyOf": [ + { + "type": "string", + "description": "The truncation strategy to use for the session.", + "enum": [ + "auto", + "disabled" + ], + "title": "RealtimeTruncationStrategy" + }, + { + "type": "object", + "title": "Retention ratio truncation", + "description": "Retain a fraction of the conversation tokens.", + "properties": { + "type": { + "type": "string", + "enum": [ + "retention_ratio" + ], + "description": "Use retention ratio truncation.", + "x-stainless-const": true + }, + "retention_ratio": { + "type": "number", + "description": "Fraction of pre-instruction conversation tokens to retain (0.0 - 1.0).\n", + "minimum": 0, + "maximum": 1 + }, + "post_instructions_token_limit": { + "type": "integer", + "nullable": true, + "description": "Optional cap on tokens allowed after the instructions.\n" + } + }, + "required": [ + "type", + "retention_ratio" + ] + } + ] + }, + "Reasoning": { + "type": "object", + "description": "**gpt-5 and o-series models only**\n\nConfiguration options for\n[reasoning models](https://platform.openai.com/docs/guides/reasoning).\n", + "title": "Reasoning", + "properties": { + "effort": { + "$ref": "#/components/schemas/ReasoningEffort" + }, + "summary": { + "type": "string", + "description": "A summary of the reasoning performed by the model. This can be\nuseful for debugging and understanding the model's reasoning process.\nOne of `auto`, `concise`, or `detailed`.\n", + "enum": [ + "auto", + "concise", + "detailed" + ], + "nullable": true + }, + "generate_summary": { + "type": "string", + "deprecated": true, + "description": "**Deprecated:** use `summary` instead.\n\nA summary of the reasoning performed by the model. This can be\nuseful for debugging and understanding the model's reasoning process.\nOne of `auto`, `concise`, or `detailed`.\n", + "enum": [ + "auto", + "concise", + "detailed" + ], + "nullable": true + } + } + }, + "ReasoningEffort": { + "type": "string", + "enum": [ + "minimal", + "low", + "medium", + "high" + ], + "default": "medium", + "nullable": true, + "description": "Constrains effort on reasoning for \n[reasoning models](https://platform.openai.com/docs/guides/reasoning).\nCurrently supported values are `minimal`, `low`, `medium`, and `high`. Reducing\nreasoning effort can result in faster responses and fewer tokens used\non reasoning in a response.\n" + }, + "ReasoningItem": { + "type": "object", + "description": "A description of the chain of thought used by a reasoning model while generating\na response. Be sure to include these items in your `input` to the Responses API\nfor subsequent turns of a conversation if you are manually \n[managing context](https://platform.openai.com/docs/guides/conversation-state).\n", + "title": "Reasoning", + "properties": { + "type": { + "type": "string", + "description": "The type of the object. Always `reasoning`.\n", + "enum": [ + "reasoning" + ], + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique identifier of the reasoning content.\n" + }, + "encrypted_content": { + "type": "string", + "description": "The encrypted content of the reasoning item - populated when a response is\ngenerated with `reasoning.encrypted_content` in the `include` parameter.\n", + "nullable": true + }, + "summary": { + "type": "array", + "description": "Reasoning summary content.\n", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "The type of the object. Always `summary_text`.\n", + "enum": [ + "summary_text" + ], + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "A summary of the reasoning output from the model so far.\n" + } + }, + "required": [ + "type", + "text" + ] + } + }, + "content": { + "type": "array", + "description": "Reasoning text content.\n", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "The type of the object. Always `reasoning_text`.\n", + "enum": [ + "reasoning_text" + ], + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "Reasoning text output from the model.\n" + } + }, + "required": [ + "type", + "text" + ] + } + }, + "status": { + "type": "string", + "description": "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n", + "enum": [ + "in_progress", + "completed", + "incomplete" + ] + } + }, + "required": [ + "id", + "summary", + "type" + ] + }, + "Response": { + "title": "The response object", + "allOf": [ + { + "$ref": "#/components/schemas/ModelResponseProperties" + }, + { + "$ref": "#/components/schemas/ResponseProperties" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for this Response.\n" + }, + "object": { + "type": "string", + "description": "The object type of this resource - always set to `response`.\n", + "enum": [ + "response" + ], + "x-stainless-const": true + }, + "status": { + "type": "string", + "description": "The status of the response generation. One of `completed`, `failed`,\n`in_progress`, `cancelled`, `queued`, or `incomplete`.\n", + "enum": [ + "completed", + "failed", + "in_progress", + "cancelled", + "queued", + "incomplete" + ] + }, + "created_at": { + "type": "number", + "description": "Unix timestamp (in seconds) of when this Response was created.\n" + }, + "error": { + "$ref": "#/components/schemas/ResponseError" + }, + "incomplete_details": { + "type": "object", + "nullable": true, + "description": "Details about why the response is incomplete.\n", + "properties": { + "reason": { + "type": "string", + "description": "The reason why the response is incomplete.", + "enum": [ + "max_output_tokens", + "content_filter" + ] + } + } + }, + "output": { + "type": "array", + "description": "An array of content items generated by the model.\n\n- The length and order of items in the `output` array is dependent\n on the model's response.\n- Rather than accessing the first item in the `output` array and\n assuming it's an `assistant` message with the content generated by\n the model, you might consider using the `output_text` property where\n supported in SDKs.\n", + "items": { + "$ref": "#/components/schemas/OutputItem" + } + }, + "instructions": { + "nullable": true, + "description": "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n", + "anyOf": [ + { + "type": "string", + "description": "A text input to the model, equivalent to a text input with the\n`developer` role.\n" + }, + { + "type": "array", + "title": "Input item list", + "description": "A list of one or many input items to the model, containing\ndifferent content types.\n", + "items": { + "$ref": "#/components/schemas/InputItem" + } + } + ] + }, + "output_text": { + "type": "string", + "nullable": true, + "description": "SDK-only convenience property that contains the aggregated text output\nfrom all `output_text` items in the `output` array, if any are present.\nSupported in the Python and JavaScript SDKs.\n", + "x-oaiSupportedSDKs": [ + "python", + "javascript" + ], + "x-stainless-skip": true + }, + "usage": { + "$ref": "#/components/schemas/ResponseUsage" + }, + "parallel_tool_calls": { + "type": "boolean", + "description": "Whether to allow the model to run tool calls in parallel.\n", + "default": true + }, + "conversation": { + "nullable": true, + "$ref": "#/components/schemas/Conversation-2" + } + }, + "required": [ + "id", + "object", + "created_at", + "error", + "incomplete_details", + "instructions", + "model", + "tools", + "output", + "parallel_tool_calls", + "metadata", + "tool_choice", + "temperature", + "top_p" + ] + } + ] + }, + "ResponseAudioDeltaEvent": { + "type": "object", + "description": "Emitted when there is a partial audio response.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.audio.delta`.\n", + "enum": [ + "response.audio.delta" + ], + "x-stainless-const": true + }, + "sequence_number": { + "type": "integer", + "description": "A sequence number for this chunk of the stream response.\n" + }, + "delta": { + "type": "string", + "description": "A chunk of Base64 encoded response audio bytes.\n" + } + }, + "required": [ + "type", + "delta", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.audio.delta", + "group": "responses", + "example": "{\n \"type\": \"response.audio.delta\",\n \"response_id\": \"resp_123\",\n \"delta\": \"base64encoded...\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseAudioDoneEvent": { + "type": "object", + "description": "Emitted when the audio response is complete.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.audio.done`.\n", + "enum": [ + "response.audio.done" + ], + "x-stainless-const": true + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of the delta.\n" + } + }, + "required": [ + "type", + "sequence_number", + "response_id" + ], + "x-oaiMeta": { + "name": "response.audio.done", + "group": "responses", + "example": "{\n \"type\": \"response.audio.done\",\n \"response_id\": \"resp-123\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseAudioTranscriptDeltaEvent": { + "type": "object", + "description": "Emitted when there is a partial transcript of audio.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.audio.transcript.delta`.\n", + "enum": [ + "response.audio.transcript.delta" + ], + "x-stainless-const": true + }, + "delta": { + "type": "string", + "description": "The partial transcript of the audio response.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "response_id", + "delta", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.audio.transcript.delta", + "group": "responses", + "example": "{\n \"type\": \"response.audio.transcript.delta\",\n \"response_id\": \"resp_123\",\n \"delta\": \" ... partial transcript ... \",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseAudioTranscriptDoneEvent": { + "type": "object", + "description": "Emitted when the full audio transcript is completed.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.audio.transcript.done`.\n", + "enum": [ + "response.audio.transcript.done" + ], + "x-stainless-const": true + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "response_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.audio.transcript.done", + "group": "responses", + "example": "{\n \"type\": \"response.audio.transcript.done\",\n \"response_id\": \"resp_123\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseCodeInterpreterCallCodeDeltaEvent": { + "type": "object", + "description": "Emitted when a partial code snippet is streamed by the code interpreter.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.code_interpreter_call_code.delta`.", + "enum": [ + "response.code_interpreter_call_code.delta" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response for which the code is being streamed." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the code interpreter tool call item." + }, + "delta": { + "type": "string", + "description": "The partial code snippet being streamed by the code interpreter." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event, used to order streaming events." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "delta", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.code_interpreter_call_code.delta", + "group": "responses", + "example": "{\n \"type\": \"response.code_interpreter_call_code.delta\",\n \"output_index\": 0,\n \"item_id\": \"ci_12345\",\n \"delta\": \"print('Hello, world')\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseCodeInterpreterCallCodeDoneEvent": { + "type": "object", + "description": "Emitted when the code snippet is finalized by the code interpreter.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.code_interpreter_call_code.done`.", + "enum": [ + "response.code_interpreter_call_code.done" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response for which the code is finalized." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the code interpreter tool call item." + }, + "code": { + "type": "string", + "description": "The final code snippet output by the code interpreter." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event, used to order streaming events." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "code", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.code_interpreter_call_code.done", + "group": "responses", + "example": "{\n \"type\": \"response.code_interpreter_call_code.done\",\n \"output_index\": 3,\n \"item_id\": \"ci_12345\",\n \"code\": \"print('done')\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseCodeInterpreterCallCompletedEvent": { + "type": "object", + "description": "Emitted when the code interpreter call is completed.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.code_interpreter_call.completed`.", + "enum": [ + "response.code_interpreter_call.completed" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response for which the code interpreter call is completed." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the code interpreter tool call item." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event, used to order streaming events." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.code_interpreter_call.completed", + "group": "responses", + "example": "{\n \"type\": \"response.code_interpreter_call.completed\",\n \"output_index\": 5,\n \"item_id\": \"ci_12345\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseCodeInterpreterCallInProgressEvent": { + "type": "object", + "description": "Emitted when a code interpreter call is in progress.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.code_interpreter_call.in_progress`.", + "enum": [ + "response.code_interpreter_call.in_progress" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response for which the code interpreter call is in progress." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the code interpreter tool call item." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event, used to order streaming events." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.code_interpreter_call.in_progress", + "group": "responses", + "example": "{\n \"type\": \"response.code_interpreter_call.in_progress\",\n \"output_index\": 0,\n \"item_id\": \"ci_12345\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseCodeInterpreterCallInterpretingEvent": { + "type": "object", + "description": "Emitted when the code interpreter is actively interpreting the code snippet.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.code_interpreter_call.interpreting`.", + "enum": [ + "response.code_interpreter_call.interpreting" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response for which the code interpreter is interpreting code." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the code interpreter tool call item." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event, used to order streaming events." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.code_interpreter_call.interpreting", + "group": "responses", + "example": "{\n \"type\": \"response.code_interpreter_call.interpreting\",\n \"output_index\": 4,\n \"item_id\": \"ci_12345\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseCompletedEvent": { + "type": "object", + "description": "Emitted when the model response is complete.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.completed`.\n", + "enum": [ + "response.completed" + ], + "x-stainless-const": true + }, + "response": { + "$ref": "#/components/schemas/Response", + "description": "Properties of the completed response.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number for this event." + } + }, + "required": [ + "type", + "response", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.completed", + "group": "responses", + "example": "{\n \"type\": \"response.completed\",\n \"response\": {\n \"id\": \"resp_123\",\n \"object\": \"response\",\n \"created_at\": 1740855869,\n \"status\": \"completed\",\n \"error\": null,\n \"incomplete_details\": null,\n \"input\": [],\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"output\": [\n {\n \"id\": \"msg_123\",\n \"type\": \"message\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"output_text\",\n \"text\": \"In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.\",\n \"annotations\": []\n }\n ]\n }\n ],\n \"previous_response_id\": null,\n \"reasoning_effort\": null,\n \"store\": false,\n \"temperature\": 1,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_p\": 1,\n \"truncation\": \"disabled\",\n \"usage\": {\n \"input_tokens\": 0,\n \"output_tokens\": 0,\n \"output_tokens_details\": {\n \"reasoning_tokens\": 0\n },\n \"total_tokens\": 0\n },\n \"user\": null,\n \"metadata\": {}\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseContentPartAddedEvent": { + "type": "object", + "description": "Emitted when a new content part is added.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.content_part.added`.\n", + "enum": [ + "response.content_part.added" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the output item that the content part was added to.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the content part was added to.\n" + }, + "content_index": { + "type": "integer", + "description": "The index of the content part that was added.\n" + }, + "part": { + "$ref": "#/components/schemas/OutputContent", + "description": "The content part that was added.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "item_id", + "output_index", + "content_index", + "part", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.content_part.added", + "group": "responses", + "example": "{\n \"type\": \"response.content_part.added\",\n \"item_id\": \"msg_123\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"part\": {\n \"type\": \"output_text\",\n \"text\": \"\",\n \"annotations\": []\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseContentPartDoneEvent": { + "type": "object", + "description": "Emitted when a content part is done.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.content_part.done`.\n", + "enum": [ + "response.content_part.done" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the output item that the content part was added to.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the content part was added to.\n" + }, + "content_index": { + "type": "integer", + "description": "The index of the content part that is done.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + }, + "part": { + "$ref": "#/components/schemas/OutputContent", + "description": "The content part that is done.\n" + } + }, + "required": [ + "type", + "item_id", + "output_index", + "content_index", + "part", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.content_part.done", + "group": "responses", + "example": "{\n \"type\": \"response.content_part.done\",\n \"item_id\": \"msg_123\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"sequence_number\": 1,\n \"part\": {\n \"type\": \"output_text\",\n \"text\": \"In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.\",\n \"annotations\": []\n }\n}\n" + } + }, + "ResponseCreatedEvent": { + "type": "object", + "description": "An event that is emitted when a response is created.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.created`.\n", + "enum": [ + "response.created" + ], + "x-stainless-const": true + }, + "response": { + "$ref": "#/components/schemas/Response", + "description": "The response that was created.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number for this event." + } + }, + "required": [ + "type", + "response", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.created", + "group": "responses", + "example": "{\n \"type\": \"response.created\",\n \"response\": {\n \"id\": \"resp_67ccfcdd16748190a91872c75d38539e09e4d4aac714747c\",\n \"object\": \"response\",\n \"created_at\": 1741487325,\n \"status\": \"in_progress\",\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4o-2024-08-06\",\n \"output\": [],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": null,\n \"summary\": null\n },\n \"store\": true,\n \"temperature\": 1,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_p\": 1,\n \"truncation\": \"disabled\",\n \"usage\": null,\n \"user\": null,\n \"metadata\": {}\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseCustomToolCallInputDeltaEvent": { + "title": "ResponseCustomToolCallInputDelta", + "type": "object", + "description": "Event representing a delta (partial update) to the input of a custom tool call.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.custom_tool_call_input.delta" + ], + "description": "The event type identifier.", + "x-stainless-const": true + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + }, + "output_index": { + "type": "integer", + "description": "The index of the output this delta applies to." + }, + "item_id": { + "type": "string", + "description": "Unique identifier for the API item associated with this event." + }, + "delta": { + "type": "string", + "description": "The incremental input data (delta) for the custom tool call." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "delta", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.custom_tool_call_input.delta", + "group": "responses", + "example": "{\n \"type\": \"response.custom_tool_call_input.delta\",\n \"output_index\": 0,\n \"item_id\": \"ctc_1234567890abcdef\",\n \"delta\": \"partial input text\"\n}\n" + } + }, + "ResponseCustomToolCallInputDoneEvent": { + "title": "ResponseCustomToolCallInputDone", + "type": "object", + "description": "Event indicating that input for a custom tool call is complete.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.custom_tool_call_input.done" + ], + "description": "The event type identifier.", + "x-stainless-const": true + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + }, + "output_index": { + "type": "integer", + "description": "The index of the output this event applies to." + }, + "item_id": { + "type": "string", + "description": "Unique identifier for the API item associated with this event." + }, + "input": { + "type": "string", + "description": "The complete input data for the custom tool call." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "input", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.custom_tool_call_input.done", + "group": "responses", + "example": "{\n \"type\": \"response.custom_tool_call_input.done\",\n \"output_index\": 0,\n \"item_id\": \"ctc_1234567890abcdef\",\n \"input\": \"final complete input text\"\n}\n" + } + }, + "ResponseError": { + "type": "object", + "description": "An error object returned when the model fails to generate a Response.\n", + "nullable": true, + "properties": { + "code": { + "$ref": "#/components/schemas/ResponseErrorCode" + }, + "message": { + "type": "string", + "description": "A human-readable description of the error.\n" + } + }, + "required": [ + "code", + "message" + ] + }, + "ResponseErrorCode": { + "type": "string", + "description": "The error code for the response.\n", + "enum": [ + "server_error", + "rate_limit_exceeded", + "invalid_prompt", + "vector_store_timeout", + "invalid_image", + "invalid_image_format", + "invalid_base64_image", + "invalid_image_url", + "image_too_large", + "image_too_small", + "image_parse_error", + "image_content_policy_violation", + "invalid_image_mode", + "image_file_too_large", + "unsupported_image_media_type", + "empty_image_file", + "failed_to_download_image", + "image_file_not_found" + ] + }, + "ResponseErrorEvent": { + "type": "object", + "description": "Emitted when an error occurs.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `error`.\n", + "enum": [ + "error" + ], + "x-stainless-const": true + }, + "code": { + "type": "string", + "description": "The error code.\n", + "nullable": true + }, + "message": { + "type": "string", + "description": "The error message.\n" + }, + "param": { + "type": "string", + "description": "The error parameter.\n", + "nullable": true + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "code", + "message", + "param", + "sequence_number" + ], + "x-oaiMeta": { + "name": "error", + "group": "responses", + "example": "{\n \"type\": \"error\",\n \"code\": \"ERR_SOMETHING\",\n \"message\": \"Something went wrong\",\n \"param\": null,\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseFailedEvent": { + "type": "object", + "description": "An event that is emitted when a response fails.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.failed`.\n", + "enum": [ + "response.failed" + ], + "x-stainless-const": true + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + }, + "response": { + "$ref": "#/components/schemas/Response", + "description": "The response that failed.\n" + } + }, + "required": [ + "type", + "response", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.failed", + "group": "responses", + "example": "{\n \"type\": \"response.failed\",\n \"response\": {\n \"id\": \"resp_123\",\n \"object\": \"response\",\n \"created_at\": 1740855869,\n \"status\": \"failed\",\n \"error\": {\n \"code\": \"server_error\",\n \"message\": \"The model failed to generate a response.\"\n },\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"output\": [],\n \"previous_response_id\": null,\n \"reasoning_effort\": null,\n \"store\": false,\n \"temperature\": 1,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_p\": 1,\n \"truncation\": \"disabled\",\n \"usage\": null,\n \"user\": null,\n \"metadata\": {}\n }\n}\n" + } + }, + "ResponseFileSearchCallCompletedEvent": { + "type": "object", + "description": "Emitted when a file search call is completed (results found).", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.file_search_call.completed`.\n", + "enum": [ + "response.file_search_call.completed" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the file search call is initiated.\n" + }, + "item_id": { + "type": "string", + "description": "The ID of the output item that the file search call is initiated.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.file_search_call.completed", + "group": "responses", + "example": "{\n \"type\": \"response.file_search_call.completed\",\n \"output_index\": 0,\n \"item_id\": \"fs_123\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseFileSearchCallInProgressEvent": { + "type": "object", + "description": "Emitted when a file search call is initiated.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.file_search_call.in_progress`.\n", + "enum": [ + "response.file_search_call.in_progress" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the file search call is initiated.\n" + }, + "item_id": { + "type": "string", + "description": "The ID of the output item that the file search call is initiated.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.file_search_call.in_progress", + "group": "responses", + "example": "{\n \"type\": \"response.file_search_call.in_progress\",\n \"output_index\": 0,\n \"item_id\": \"fs_123\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseFileSearchCallSearchingEvent": { + "type": "object", + "description": "Emitted when a file search is currently searching.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.file_search_call.searching`.\n", + "enum": [ + "response.file_search_call.searching" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the file search call is searching.\n" + }, + "item_id": { + "type": "string", + "description": "The ID of the output item that the file search call is initiated.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.file_search_call.searching", + "group": "responses", + "example": "{\n \"type\": \"response.file_search_call.searching\",\n \"output_index\": 0,\n \"item_id\": \"fs_123\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseFormatJsonObject": { + "type": "object", + "title": "JSON object", + "description": "JSON object response format. An older method of generating JSON responses.\nUsing `json_schema` is recommended for models that support it. Note that the\nmodel will not generate JSON without a system or user message instructing it\nto do so.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of response format being defined. Always `json_object`.", + "enum": [ + "json_object" + ], + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + "ResponseFormatJsonSchema": { + "type": "object", + "title": "JSON schema", + "description": "JSON Schema response format. Used to generate structured JSON responses.\nLearn more about [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs).\n", + "properties": { + "type": { + "type": "string", + "description": "The type of response format being defined. Always `json_schema`.", + "enum": [ + "json_schema" + ], + "x-stainless-const": true + }, + "json_schema": { + "type": "object", + "title": "JSON schema", + "description": "Structured Outputs configuration options, including a JSON Schema.\n", + "properties": { + "description": { + "type": "string", + "description": "A description of what the response format is for, used by the model to\ndetermine how to respond in the format.\n" + }, + "name": { + "type": "string", + "description": "The name of the response format. Must be a-z, A-Z, 0-9, or contain\nunderscores and dashes, with a maximum length of 64.\n" + }, + "schema": { + "$ref": "#/components/schemas/ResponseFormatJsonSchemaSchema" + }, + "strict": { + "type": "boolean", + "nullable": true, + "default": false, + "description": "Whether to enable strict schema adherence when generating the output.\nIf set to true, the model will always follow the exact schema defined\nin the `schema` field. Only a subset of JSON Schema is supported when\n`strict` is `true`. To learn more, read the [Structured Outputs\nguide](https://platform.openai.com/docs/guides/structured-outputs).\n" + } + }, + "required": [ + "name" + ] + } + }, + "required": [ + "type", + "json_schema" + ] + }, + "ResponseFormatJsonSchemaSchema": { + "type": "object", + "title": "JSON schema", + "description": "The schema for the response format, described as a JSON Schema object.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n", + "additionalProperties": true + }, + "ResponseFormatText": { + "type": "object", + "title": "Text", + "description": "Default response format. Used to generate text responses.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of response format being defined. Always `text`.", + "enum": [ + "text" + ], + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + "ResponseFormatTextGrammar": { + "type": "object", + "title": "Text grammar", + "description": "A custom grammar for the model to follow when generating text.\nLearn more in the [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars).\n", + "properties": { + "type": { + "type": "string", + "description": "The type of response format being defined. Always `grammar`.", + "enum": [ + "grammar" + ], + "x-stainless-const": true + }, + "grammar": { + "type": "string", + "description": "The custom grammar for the model to follow." + } + }, + "required": [ + "type", + "grammar" + ] + }, + "ResponseFormatTextPython": { + "type": "object", + "title": "Python grammar", + "description": "Configure the model to generate valid Python code. See the\n[custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars) for more details.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of response format being defined. Always `python`.", + "enum": [ + "python" + ], + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + "ResponseFunctionCallArgumentsDeltaEvent": { + "type": "object", + "description": "Emitted when there is a partial function-call arguments delta.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.function_call_arguments.delta`.\n", + "enum": [ + "response.function_call_arguments.delta" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the output item that the function-call arguments delta is added to.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the function-call arguments delta is added to.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + }, + "delta": { + "type": "string", + "description": "The function-call arguments delta that is added.\n" + } + }, + "required": [ + "type", + "item_id", + "output_index", + "delta", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.function_call_arguments.delta", + "group": "responses", + "example": "{\n \"type\": \"response.function_call_arguments.delta\",\n \"item_id\": \"item-abc\",\n \"output_index\": 0,\n \"delta\": \"{ \\\"arg\\\":\"\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseFunctionCallArgumentsDoneEvent": { + "type": "object", + "description": "Emitted when function-call arguments are finalized.", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.function_call_arguments.done" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the item." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + }, + "arguments": { + "type": "string", + "description": "The function-call arguments." + } + }, + "required": [ + "type", + "item_id", + "output_index", + "arguments", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.function_call_arguments.done", + "group": "responses", + "example": "{\n \"type\": \"response.function_call_arguments.done\",\n \"item_id\": \"item-abc\",\n \"output_index\": 1,\n \"arguments\": \"{ \\\"arg\\\": 123 }\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseImageGenCallCompletedEvent": { + "type": "object", + "title": "ResponseImageGenCallCompletedEvent", + "description": "Emitted when an image generation tool call has completed and the final image is available.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.image_generation_call.completed" + ], + "description": "The type of the event. Always 'response.image_generation_call.completed'.", + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response's output array." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the image generation item being processed." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.image_generation_call.completed", + "group": "responses", + "example": "{\n \"type\": \"response.image_generation_call.completed\",\n \"output_index\": 0,\n \"item_id\": \"item-123\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseImageGenCallGeneratingEvent": { + "type": "object", + "title": "ResponseImageGenCallGeneratingEvent", + "description": "Emitted when an image generation tool call is actively generating an image (intermediate state).\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.image_generation_call.generating" + ], + "description": "The type of the event. Always 'response.image_generation_call.generating'.", + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response's output array." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the image generation item being processed." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of the image generation item being processed." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.image_generation_call.generating", + "group": "responses", + "example": "{\n \"type\": \"response.image_generation_call.generating\",\n \"output_index\": 0,\n \"item_id\": \"item-123\",\n \"sequence_number\": 0\n}\n" + } + }, + "ResponseImageGenCallInProgressEvent": { + "type": "object", + "title": "ResponseImageGenCallInProgressEvent", + "description": "Emitted when an image generation tool call is in progress.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.image_generation_call.in_progress" + ], + "description": "The type of the event. Always 'response.image_generation_call.in_progress'.", + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response's output array." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the image generation item being processed." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of the image generation item being processed." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.image_generation_call.in_progress", + "group": "responses", + "example": "{\n \"type\": \"response.image_generation_call.in_progress\",\n \"output_index\": 0,\n \"item_id\": \"item-123\",\n \"sequence_number\": 0\n}\n" + } + }, + "ResponseImageGenCallPartialImageEvent": { + "type": "object", + "title": "ResponseImageGenCallPartialImageEvent", + "description": "Emitted when a partial image is available during image generation streaming.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.image_generation_call.partial_image" + ], + "description": "The type of the event. Always 'response.image_generation_call.partial_image'.", + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response's output array." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the image generation item being processed." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of the image generation item being processed." + }, + "partial_image_index": { + "type": "integer", + "description": "0-based index for the partial image (backend is 1-based, but this is 0-based for the user)." + }, + "partial_image_b64": { + "type": "string", + "description": "Base64-encoded partial image data, suitable for rendering as an image." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number", + "partial_image_index", + "partial_image_b64" + ], + "x-oaiMeta": { + "name": "response.image_generation_call.partial_image", + "group": "responses", + "example": "{\n \"type\": \"response.image_generation_call.partial_image\",\n \"output_index\": 0,\n \"item_id\": \"item-123\",\n \"sequence_number\": 0,\n \"partial_image_index\": 0,\n \"partial_image_b64\": \"...\"\n}\n" + } + }, + "ResponseInProgressEvent": { + "type": "object", + "description": "Emitted when the response is in progress.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.in_progress`.\n", + "enum": [ + "response.in_progress" + ], + "x-stainless-const": true + }, + "response": { + "$ref": "#/components/schemas/Response", + "description": "The response that is in progress.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "response", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.in_progress", + "group": "responses", + "example": "{\n \"type\": \"response.in_progress\",\n \"response\": {\n \"id\": \"resp_67ccfcdd16748190a91872c75d38539e09e4d4aac714747c\",\n \"object\": \"response\",\n \"created_at\": 1741487325,\n \"status\": \"in_progress\",\n \"error\": null,\n \"incomplete_details\": null,\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4o-2024-08-06\",\n \"output\": [],\n \"parallel_tool_calls\": true,\n \"previous_response_id\": null,\n \"reasoning\": {\n \"effort\": null,\n \"summary\": null\n },\n \"store\": true,\n \"temperature\": 1,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_p\": 1,\n \"truncation\": \"disabled\",\n \"usage\": null,\n \"user\": null,\n \"metadata\": {}\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseIncompleteEvent": { + "type": "object", + "description": "An event that is emitted when a response finishes as incomplete.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.incomplete`.\n", + "enum": [ + "response.incomplete" + ], + "x-stainless-const": true + }, + "response": { + "$ref": "#/components/schemas/Response", + "description": "The response that was incomplete.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "response", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.incomplete", + "group": "responses", + "example": "{\n \"type\": \"response.incomplete\",\n \"response\": {\n \"id\": \"resp_123\",\n \"object\": \"response\",\n \"created_at\": 1740855869,\n \"status\": \"incomplete\",\n \"error\": null, \n \"incomplete_details\": {\n \"reason\": \"max_tokens\"\n },\n \"instructions\": null,\n \"max_output_tokens\": null,\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"output\": [],\n \"previous_response_id\": null,\n \"reasoning_effort\": null,\n \"store\": false,\n \"temperature\": 1,\n \"text\": {\n \"format\": {\n \"type\": \"text\"\n }\n },\n \"tool_choice\": \"auto\",\n \"tools\": [],\n \"top_p\": 1,\n \"truncation\": \"disabled\",\n \"usage\": null,\n \"user\": null,\n \"metadata\": {}\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseItemList": { + "type": "object", + "description": "A list of Response items.", + "properties": { + "object": { + "description": "The type of object returned, must be `list`.", + "x-stainless-const": true, + "const": "list" + }, + "data": { + "type": "array", + "description": "A list of items used to generate this response.", + "items": { + "$ref": "#/components/schemas/ItemResource" + } + }, + "has_more": { + "type": "boolean", + "description": "Whether there are more items available." + }, + "first_id": { + "type": "string", + "description": "The ID of the first item in the list." + }, + "last_id": { + "type": "string", + "description": "The ID of the last item in the list." + } + }, + "required": [ + "object", + "data", + "has_more", + "first_id", + "last_id" + ], + "x-oaiMeta": { + "name": "The input item list", + "group": "responses", + "example": "{\n \"object\": \"list\",\n \"data\": [\n {\n \"id\": \"msg_abc123\",\n \"type\": \"message\",\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"input_text\",\n \"text\": \"Tell me a three sentence bedtime story about a unicorn.\"\n }\n ]\n }\n ],\n \"first_id\": \"msg_abc123\",\n \"last_id\": \"msg_abc123\",\n \"has_more\": false\n}\n" + } + }, + "ResponseLogProb": { + "type": "object", + "description": "A logprob is the logarithmic probability that the model assigns to producing \na particular token at a given position in the sequence. Less-negative (higher) \nlogprob values indicate greater model confidence in that token choice.\n", + "properties": { + "token": { + "description": "A possible text token.", + "type": "string" + }, + "logprob": { + "description": "The log probability of this token.\n", + "type": "number" + }, + "top_logprobs": { + "description": "The log probability of the top 20 most likely tokens.\n", + "type": "array", + "items": { + "type": "object", + "properties": { + "token": { + "description": "A possible text token.", + "type": "string" + }, + "logprob": { + "description": "The log probability of this token.", + "type": "number" + } + } + } + } + }, + "required": [ + "token", + "logprob" + ] + }, + "ResponseMCPCallArgumentsDeltaEvent": { + "type": "object", + "title": "ResponseMCPCallArgumentsDeltaEvent", + "description": "Emitted when there is a delta (partial update) to the arguments of an MCP tool call.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.mcp_call_arguments.delta" + ], + "description": "The type of the event. Always 'response.mcp_call_arguments.delta'.", + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response's output array." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the MCP tool call item being processed." + }, + "delta": { + "type": "string", + "description": "A JSON string containing the partial update to the arguments for the MCP tool call.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "delta", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.mcp_call_arguments.delta", + "group": "responses", + "example": "{\n \"type\": \"response.mcp_call_arguments.delta\",\n \"output_index\": 0,\n \"item_id\": \"item-abc\",\n \"delta\": \"{\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseMCPCallArgumentsDoneEvent": { + "type": "object", + "title": "ResponseMCPCallArgumentsDoneEvent", + "description": "Emitted when the arguments for an MCP tool call are finalized.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.mcp_call_arguments.done" + ], + "description": "The type of the event. Always 'response.mcp_call_arguments.done'.", + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response's output array." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the MCP tool call item being processed." + }, + "arguments": { + "type": "string", + "description": "A JSON string containing the finalized arguments for the MCP tool call.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "arguments", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.mcp_call_arguments.done", + "group": "responses", + "example": "{\n \"type\": \"response.mcp_call_arguments.done\",\n \"output_index\": 0,\n \"item_id\": \"item-abc\",\n \"arguments\": \"{\\\"arg1\\\": \\\"value1\\\", \\\"arg2\\\": \\\"value2\\\"}\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseMCPCallCompletedEvent": { + "type": "object", + "title": "ResponseMCPCallCompletedEvent", + "description": "Emitted when an MCP tool call has completed successfully.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.mcp_call.completed" + ], + "description": "The type of the event. Always 'response.mcp_call.completed'.", + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP tool call item that completed." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that completed." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "item_id", + "output_index", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.mcp_call.completed", + "group": "responses", + "example": "{\n \"type\": \"response.mcp_call.completed\",\n \"sequence_number\": 1,\n \"item_id\": \"mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90\",\n \"output_index\": 0\n}\n" + } + }, + "ResponseMCPCallFailedEvent": { + "type": "object", + "title": "ResponseMCPCallFailedEvent", + "description": "Emitted when an MCP tool call has failed.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.mcp_call.failed" + ], + "description": "The type of the event. Always 'response.mcp_call.failed'.", + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP tool call item that failed." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that failed." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "item_id", + "output_index", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.mcp_call.failed", + "group": "responses", + "example": "{\n \"type\": \"response.mcp_call.failed\",\n \"sequence_number\": 1,\n \"item_id\": \"mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90\",\n \"output_index\": 0\n}\n" + } + }, + "ResponseMCPCallInProgressEvent": { + "type": "object", + "title": "ResponseMCPCallInProgressEvent", + "description": "Emitted when an MCP tool call is in progress.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.mcp_call.in_progress" + ], + "description": "The type of the event. Always 'response.mcp_call.in_progress'.", + "x-stainless-const": true + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response's output array." + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the MCP tool call item being processed." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.mcp_call.in_progress", + "group": "responses", + "example": "{\n \"type\": \"response.mcp_call.in_progress\",\n \"sequence_number\": 1,\n \"output_index\": 0,\n \"item_id\": \"mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90\"\n}\n" + } + }, + "ResponseMCPListToolsCompletedEvent": { + "type": "object", + "title": "ResponseMCPListToolsCompletedEvent", + "description": "Emitted when the list of available MCP tools has been successfully retrieved.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.mcp_list_tools.completed" + ], + "description": "The type of the event. Always 'response.mcp_list_tools.completed'.", + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP tool call item that produced this output." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that was processed." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "item_id", + "output_index", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.mcp_list_tools.completed", + "group": "responses", + "example": "{\n \"type\": \"response.mcp_list_tools.completed\",\n \"sequence_number\": 1,\n \"output_index\": 0,\n \"item_id\": \"mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90\"\n}\n" + } + }, + "ResponseMCPListToolsFailedEvent": { + "type": "object", + "title": "ResponseMCPListToolsFailedEvent", + "description": "Emitted when the attempt to list available MCP tools has failed.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.mcp_list_tools.failed" + ], + "description": "The type of the event. Always 'response.mcp_list_tools.failed'.", + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP tool call item that failed." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that failed." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "item_id", + "output_index", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.mcp_list_tools.failed", + "group": "responses", + "example": "{\n \"type\": \"response.mcp_list_tools.failed\",\n \"sequence_number\": 1,\n \"output_index\": 0,\n \"item_id\": \"mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90\"\n}\n" + } + }, + "ResponseMCPListToolsInProgressEvent": { + "type": "object", + "title": "ResponseMCPListToolsInProgressEvent", + "description": "Emitted when the system is in the process of retrieving the list of available MCP tools.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.mcp_list_tools.in_progress" + ], + "description": "The type of the event. Always 'response.mcp_list_tools.in_progress'.", + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the MCP tool call item that is being processed." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that is being processed." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + } + }, + "required": [ + "type", + "item_id", + "output_index", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.mcp_list_tools.in_progress", + "group": "responses", + "example": "{\n \"type\": \"response.mcp_list_tools.in_progress\",\n \"sequence_number\": 1,\n \"output_index\": 0,\n \"item_id\": \"mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90\"\n}\n" + } + }, + "ResponseModalities": { + "type": "array", + "nullable": true, + "description": "Output types that you would like the model to generate.\nMost models are capable of generating text, which is the default:\n\n`[\"text\"]`\n\nThe `gpt-4o-audio-preview` model can also be used to \n[generate audio](https://platform.openai.com/docs/guides/audio). To request that this model generate \nboth text and audio responses, you can use:\n\n`[\"text\", \"audio\"]`\n", + "items": { + "type": "string", + "enum": [ + "text", + "audio" + ] + } + }, + "ResponseOutputItemAddedEvent": { + "type": "object", + "description": "Emitted when a new output item is added.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.output_item.added`.\n", + "enum": [ + "response.output_item.added" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that was added.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event.\n" + }, + "item": { + "$ref": "#/components/schemas/OutputItem", + "description": "The output item that was added.\n" + } + }, + "required": [ + "type", + "output_index", + "item", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.output_item.added", + "group": "responses", + "example": "{\n \"type\": \"response.output_item.added\",\n \"output_index\": 0,\n \"item\": {\n \"id\": \"msg_123\",\n \"status\": \"in_progress\",\n \"type\": \"message\",\n \"role\": \"assistant\",\n \"content\": []\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseOutputItemDoneEvent": { + "type": "object", + "description": "Emitted when an output item is marked done.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.output_item.done`.\n", + "enum": [ + "response.output_item.done" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that was marked done.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event.\n" + }, + "item": { + "$ref": "#/components/schemas/OutputItem", + "description": "The output item that was marked done.\n" + } + }, + "required": [ + "type", + "output_index", + "item", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.output_item.done", + "group": "responses", + "example": "{\n \"type\": \"response.output_item.done\",\n \"output_index\": 0,\n \"item\": {\n \"id\": \"msg_123\",\n \"status\": \"completed\",\n \"type\": \"message\",\n \"role\": \"assistant\",\n \"content\": [\n {\n \"type\": \"output_text\",\n \"text\": \"In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.\",\n \"annotations\": []\n }\n ]\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseOutputTextAnnotationAddedEvent": { + "type": "object", + "title": "ResponseOutputTextAnnotationAddedEvent", + "description": "Emitted when an annotation is added to output text content.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.output_text.annotation.added" + ], + "description": "The type of the event. Always 'response.output_text.annotation.added'.", + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The unique identifier of the item to which the annotation is being added." + }, + "output_index": { + "type": "integer", + "description": "The index of the output item in the response's output array." + }, + "content_index": { + "type": "integer", + "description": "The index of the content part within the output item." + }, + "annotation_index": { + "type": "integer", + "description": "The index of the annotation within the content part." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event." + }, + "annotation": { + "type": "object", + "description": "The annotation object being added. (See annotation schema for details.)" + } + }, + "required": [ + "type", + "item_id", + "output_index", + "content_index", + "annotation_index", + "annotation", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.output_text.annotation.added", + "group": "responses", + "example": "{\n \"type\": \"response.output_text.annotation.added\",\n \"item_id\": \"item-abc\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"annotation_index\": 0,\n \"annotation\": {\n \"type\": \"text_annotation\",\n \"text\": \"This is a test annotation\",\n \"start\": 0,\n \"end\": 10\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponsePromptVariables": { + "type": "object", + "title": "Prompt Variables", + "description": "Optional map of values to substitute in for variables in your\nprompt. The substitution values can either be strings, or other\nResponse input types like images or files.\n", + "x-oaiExpandable": true, + "x-oaiTypeLabel": "map", + "nullable": true, + "additionalProperties": { + "x-oaiExpandable": true, + "x-oaiTypeLabel": "map", + "anyOf": [ + { + "type": "string" + }, + { + "$ref": "#/components/schemas/InputTextContent" + }, + { + "$ref": "#/components/schemas/InputImageContent" + }, + { + "$ref": "#/components/schemas/InputFileContent" + } + ] + } + }, + "ResponseProperties": { + "type": "object", + "properties": { + "previous_response_id": { + "type": "string", + "description": "The unique ID of the previous response to the model. Use this to\ncreate multi-turn conversations. Learn more about\n[conversation state](https://platform.openai.com/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`.\n", + "nullable": true + }, + "model": { + "description": "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models)\nto browse and compare available models.\n", + "$ref": "#/components/schemas/ModelIdsResponses" + }, + "reasoning": { + "$ref": "#/components/schemas/Reasoning", + "nullable": true + }, + "background": { + "type": "boolean", + "description": "Whether to run the model response in the background.\n[Learn more](https://platform.openai.com/docs/guides/background).\n", + "default": false, + "nullable": true + }, + "max_output_tokens": { + "description": "An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).\n", + "type": "integer", + "nullable": true + }, + "max_tool_calls": { + "description": "The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.\n", + "type": "integer", + "nullable": true + }, + "text": { + "type": "object", + "description": "Configuration options for a text response from the model. Can be plain\ntext or structured JSON data. Learn more:\n- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n- [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)\n", + "properties": { + "format": { + "$ref": "#/components/schemas/TextResponseFormatConfiguration" + }, + "verbosity": { + "$ref": "#/components/schemas/Verbosity" + } + } + }, + "tools": { + "type": "array", + "description": "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search)\n or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about\n [built-in tools](https://platform.openai.com/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](https://platform.openai.com/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](https://platform.openai.com/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n", + "items": { + "$ref": "#/components/schemas/Tool" + } + }, + "tool_choice": { + "description": "How the model should select which tool (or tools) to use when generating\na response. See the `tools` parameter to see how to specify which tools\nthe model can call.\n", + "anyOf": [ + { + "$ref": "#/components/schemas/ToolChoiceOptions" + }, + { + "$ref": "#/components/schemas/ToolChoiceAllowed" + }, + { + "$ref": "#/components/schemas/ToolChoiceTypes" + }, + { + "$ref": "#/components/schemas/ToolChoiceFunction" + }, + { + "$ref": "#/components/schemas/ToolChoiceMCP" + }, + { + "$ref": "#/components/schemas/ToolChoiceCustom" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "prompt": { + "$ref": "#/components/schemas/Prompt" + }, + "truncation": { + "type": "string", + "description": "The truncation strategy to use for the model response.\n- `auto`: If the context of this response and previous ones exceeds\n the model's context window size, the model will truncate the\n response to fit the context window by dropping input items in the\n middle of the conversation.\n- `disabled` (default): If a model response will exceed the context window\n size for a model, the request will fail with a 400 error.\n", + "enum": [ + "auto", + "disabled" + ], + "nullable": true, + "default": "disabled" + } + } + }, + "ResponseQueuedEvent": { + "type": "object", + "title": "ResponseQueuedEvent", + "description": "Emitted when a response is queued and waiting to be processed.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "response.queued" + ], + "description": "The type of the event. Always 'response.queued'.", + "x-stainless-const": true + }, + "response": { + "$ref": "#/components/schemas/Response", + "description": "The full response object that is queued." + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number for this event." + } + }, + "required": [ + "type", + "response", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.queued", + "group": "responses", + "example": "{\n \"type\": \"response.queued\",\n \"response\": {\n \"id\": \"res_123\",\n \"status\": \"queued\",\n \"created_at\": \"2021-01-01T00:00:00Z\",\n \"updated_at\": \"2021-01-01T00:00:00Z\"\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseReasoningSummaryPartAddedEvent": { + "type": "object", + "description": "Emitted when a new reasoning summary part is added.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.reasoning_summary_part.added`.\n", + "enum": [ + "response.reasoning_summary_part.added" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the item this summary part is associated with.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item this summary part is associated with.\n" + }, + "summary_index": { + "type": "integer", + "description": "The index of the summary part within the reasoning summary.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event.\n" + }, + "part": { + "type": "object", + "description": "The summary part that was added.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the summary part. Always `summary_text`.", + "enum": [ + "summary_text" + ], + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text of the summary part." + } + }, + "required": [ + "type", + "text" + ] + } + }, + "required": [ + "type", + "item_id", + "output_index", + "summary_index", + "part", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.reasoning_summary_part.added", + "group": "responses", + "example": "{\n \"type\": \"response.reasoning_summary_part.added\",\n \"item_id\": \"rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476\",\n \"output_index\": 0,\n \"summary_index\": 0,\n \"part\": {\n \"type\": \"summary_text\",\n \"text\": \"\"\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseReasoningSummaryPartDoneEvent": { + "type": "object", + "description": "Emitted when a reasoning summary part is completed.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.reasoning_summary_part.done`.\n", + "enum": [ + "response.reasoning_summary_part.done" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the item this summary part is associated with.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item this summary part is associated with.\n" + }, + "summary_index": { + "type": "integer", + "description": "The index of the summary part within the reasoning summary.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event.\n" + }, + "part": { + "type": "object", + "description": "The completed summary part.\n", + "properties": { + "type": { + "type": "string", + "description": "The type of the summary part. Always `summary_text`.", + "enum": [ + "summary_text" + ], + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text of the summary part." + } + }, + "required": [ + "type", + "text" + ] + } + }, + "required": [ + "type", + "item_id", + "output_index", + "summary_index", + "part", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.reasoning_summary_part.done", + "group": "responses", + "example": "{\n \"type\": \"response.reasoning_summary_part.done\",\n \"item_id\": \"rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476\",\n \"output_index\": 0,\n \"summary_index\": 0,\n \"part\": {\n \"type\": \"summary_text\",\n \"text\": \"**Responding to a greeting**\\n\\nThe user just said, \\\"Hello!\\\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \\\"Hello! How can I assist you today?\\\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!\"\n },\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseReasoningSummaryTextDeltaEvent": { + "type": "object", + "description": "Emitted when a delta is added to a reasoning summary text.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.reasoning_summary_text.delta`.\n", + "enum": [ + "response.reasoning_summary_text.delta" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the item this summary text delta is associated with.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item this summary text delta is associated with.\n" + }, + "summary_index": { + "type": "integer", + "description": "The index of the summary part within the reasoning summary.\n" + }, + "delta": { + "type": "string", + "description": "The text delta that was added to the summary.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event.\n" + } + }, + "required": [ + "type", + "item_id", + "output_index", + "summary_index", + "delta", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.reasoning_summary_text.delta", + "group": "responses", + "example": "{\n \"type\": \"response.reasoning_summary_text.delta\",\n \"item_id\": \"rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476\",\n \"output_index\": 0,\n \"summary_index\": 0,\n \"delta\": \"**Responding to a greeting**\\n\\nThe user just said, \\\"Hello!\\\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \\\"Hello! How can I assist you today?\\\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseReasoningSummaryTextDoneEvent": { + "type": "object", + "description": "Emitted when a reasoning summary text is completed.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.reasoning_summary_text.done`.\n", + "enum": [ + "response.reasoning_summary_text.done" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the item this summary text is associated with.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item this summary text is associated with.\n" + }, + "summary_index": { + "type": "integer", + "description": "The index of the summary part within the reasoning summary.\n" + }, + "text": { + "type": "string", + "description": "The full text of the completed reasoning summary.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event.\n" + } + }, + "required": [ + "type", + "item_id", + "output_index", + "summary_index", + "text", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.reasoning_summary_text.done", + "group": "responses", + "example": "{\n \"type\": \"response.reasoning_summary_text.done\",\n \"item_id\": \"rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476\",\n \"output_index\": 0,\n \"summary_index\": 0,\n \"text\": \"**Responding to a greeting**\\n\\nThe user just said, \\\"Hello!\\\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \\\"Hello! How can I assist you today?\\\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseReasoningTextDeltaEvent": { + "type": "object", + "description": "Emitted when a delta is added to a reasoning text.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.reasoning_text.delta`.\n", + "enum": [ + "response.reasoning_text.delta" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the item this reasoning text delta is associated with.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item this reasoning text delta is associated with.\n" + }, + "content_index": { + "type": "integer", + "description": "The index of the reasoning content part this delta is associated with.\n" + }, + "delta": { + "type": "string", + "description": "The text delta that was added to the reasoning content.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event.\n" + } + }, + "required": [ + "type", + "item_id", + "output_index", + "content_index", + "delta", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.reasoning_text.delta", + "group": "responses", + "example": "{\n \"type\": \"response.reasoning_text.delta\",\n \"item_id\": \"rs_123\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"delta\": \"The\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseReasoningTextDoneEvent": { + "type": "object", + "description": "Emitted when a reasoning text is completed.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.reasoning_text.done`.\n", + "enum": [ + "response.reasoning_text.done" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the item this reasoning text is associated with.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item this reasoning text is associated with.\n" + }, + "content_index": { + "type": "integer", + "description": "The index of the reasoning content part.\n" + }, + "text": { + "type": "string", + "description": "The full text of the completed reasoning content.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event.\n" + } + }, + "required": [ + "type", + "item_id", + "output_index", + "content_index", + "text", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.reasoning_text.done", + "group": "responses", + "example": "{\n \"type\": \"response.reasoning_text.done\",\n \"item_id\": \"rs_123\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"text\": \"The user is asking...\",\n \"sequence_number\": 4\n}\n" + } + }, + "ResponseRefusalDeltaEvent": { + "type": "object", + "description": "Emitted when there is a partial refusal text.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.refusal.delta`.\n", + "enum": [ + "response.refusal.delta" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the output item that the refusal text is added to.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the refusal text is added to.\n" + }, + "content_index": { + "type": "integer", + "description": "The index of the content part that the refusal text is added to.\n" + }, + "delta": { + "type": "string", + "description": "The refusal text that is added.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event.\n" + } + }, + "required": [ + "type", + "item_id", + "output_index", + "content_index", + "delta", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.refusal.delta", + "group": "responses", + "example": "{\n \"type\": \"response.refusal.delta\",\n \"item_id\": \"msg_123\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"delta\": \"refusal text so far\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseRefusalDoneEvent": { + "type": "object", + "description": "Emitted when refusal text is finalized.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.refusal.done`.\n", + "enum": [ + "response.refusal.done" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the output item that the refusal text is finalized.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the refusal text is finalized.\n" + }, + "content_index": { + "type": "integer", + "description": "The index of the content part that the refusal text is finalized.\n" + }, + "refusal": { + "type": "string", + "description": "The refusal text that is finalized.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of this event.\n" + } + }, + "required": [ + "type", + "item_id", + "output_index", + "content_index", + "refusal", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.refusal.done", + "group": "responses", + "example": "{\n \"type\": \"response.refusal.done\",\n \"item_id\": \"item-abc\",\n \"output_index\": 1,\n \"content_index\": 2,\n \"refusal\": \"final refusal text\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseStreamEvent": { + "anyOf": [ + { + "$ref": "#/components/schemas/ResponseAudioDeltaEvent" + }, + { + "$ref": "#/components/schemas/ResponseAudioDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseAudioTranscriptDeltaEvent" + }, + { + "$ref": "#/components/schemas/ResponseAudioTranscriptDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent" + }, + { + "$ref": "#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseCodeInterpreterCallCompletedEvent" + }, + { + "$ref": "#/components/schemas/ResponseCodeInterpreterCallInProgressEvent" + }, + { + "$ref": "#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent" + }, + { + "$ref": "#/components/schemas/ResponseCompletedEvent" + }, + { + "$ref": "#/components/schemas/ResponseContentPartAddedEvent" + }, + { + "$ref": "#/components/schemas/ResponseContentPartDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseCreatedEvent" + }, + { + "$ref": "#/components/schemas/ResponseErrorEvent" + }, + { + "$ref": "#/components/schemas/ResponseFileSearchCallCompletedEvent" + }, + { + "$ref": "#/components/schemas/ResponseFileSearchCallInProgressEvent" + }, + { + "$ref": "#/components/schemas/ResponseFileSearchCallSearchingEvent" + }, + { + "$ref": "#/components/schemas/ResponseFunctionCallArgumentsDeltaEvent" + }, + { + "$ref": "#/components/schemas/ResponseFunctionCallArgumentsDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseInProgressEvent" + }, + { + "$ref": "#/components/schemas/ResponseFailedEvent" + }, + { + "$ref": "#/components/schemas/ResponseIncompleteEvent" + }, + { + "$ref": "#/components/schemas/ResponseOutputItemAddedEvent" + }, + { + "$ref": "#/components/schemas/ResponseOutputItemDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseReasoningSummaryPartAddedEvent" + }, + { + "$ref": "#/components/schemas/ResponseReasoningSummaryPartDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseReasoningSummaryTextDeltaEvent" + }, + { + "$ref": "#/components/schemas/ResponseReasoningSummaryTextDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseReasoningTextDeltaEvent" + }, + { + "$ref": "#/components/schemas/ResponseReasoningTextDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseRefusalDeltaEvent" + }, + { + "$ref": "#/components/schemas/ResponseRefusalDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseTextDeltaEvent" + }, + { + "$ref": "#/components/schemas/ResponseTextDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseWebSearchCallCompletedEvent" + }, + { + "$ref": "#/components/schemas/ResponseWebSearchCallInProgressEvent" + }, + { + "$ref": "#/components/schemas/ResponseWebSearchCallSearchingEvent" + }, + { + "$ref": "#/components/schemas/ResponseImageGenCallCompletedEvent" + }, + { + "$ref": "#/components/schemas/ResponseImageGenCallGeneratingEvent" + }, + { + "$ref": "#/components/schemas/ResponseImageGenCallInProgressEvent" + }, + { + "$ref": "#/components/schemas/ResponseImageGenCallPartialImageEvent" + }, + { + "$ref": "#/components/schemas/ResponseMCPCallArgumentsDeltaEvent" + }, + { + "$ref": "#/components/schemas/ResponseMCPCallArgumentsDoneEvent" + }, + { + "$ref": "#/components/schemas/ResponseMCPCallCompletedEvent" + }, + { + "$ref": "#/components/schemas/ResponseMCPCallFailedEvent" + }, + { + "$ref": "#/components/schemas/ResponseMCPCallInProgressEvent" + }, + { + "$ref": "#/components/schemas/ResponseMCPListToolsCompletedEvent" + }, + { + "$ref": "#/components/schemas/ResponseMCPListToolsFailedEvent" + }, + { + "$ref": "#/components/schemas/ResponseMCPListToolsInProgressEvent" + }, + { + "$ref": "#/components/schemas/ResponseOutputTextAnnotationAddedEvent" + }, + { + "$ref": "#/components/schemas/ResponseQueuedEvent" + }, + { + "$ref": "#/components/schemas/ResponseCustomToolCallInputDeltaEvent" + }, + { + "$ref": "#/components/schemas/ResponseCustomToolCallInputDoneEvent" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "ResponseStreamOptions": { + "description": "Options for streaming responses. Only set this when you set `stream: true`.\n", + "type": "object", + "nullable": true, + "default": null, + "properties": { + "include_obfuscation": { + "type": "boolean", + "description": "When true, stream obfuscation will be enabled. Stream obfuscation adds\nrandom characters to an `obfuscation` field on streaming delta events to\nnormalize payload sizes as a mitigation to certain side-channel attacks.\nThese obfuscation fields are included by default, but add a small amount\nof overhead to the data stream. You can set `include_obfuscation` to\nfalse to optimize for bandwidth if you trust the network links between\nyour application and the OpenAI API.\n" + } + } + }, + "ResponseTextDeltaEvent": { + "type": "object", + "description": "Emitted when there is an additional text delta.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.output_text.delta`.\n", + "enum": [ + "response.output_text.delta" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the output item that the text delta was added to.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the text delta was added to.\n" + }, + "content_index": { + "type": "integer", + "description": "The index of the content part that the text delta was added to.\n" + }, + "delta": { + "type": "string", + "description": "The text delta that was added.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number for this event." + }, + "logprobs": { + "type": "array", + "description": "The log probabilities of the tokens in the delta.\n", + "items": { + "$ref": "#/components/schemas/ResponseLogProb" + } + } + }, + "required": [ + "type", + "item_id", + "output_index", + "content_index", + "delta", + "sequence_number", + "logprobs" + ], + "x-oaiMeta": { + "name": "response.output_text.delta", + "group": "responses", + "example": "{\n \"type\": \"response.output_text.delta\",\n \"item_id\": \"msg_123\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"delta\": \"In\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseTextDoneEvent": { + "type": "object", + "description": "Emitted when text content is finalized.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.output_text.done`.\n", + "enum": [ + "response.output_text.done" + ], + "x-stainless-const": true + }, + "item_id": { + "type": "string", + "description": "The ID of the output item that the text content is finalized.\n" + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the text content is finalized.\n" + }, + "content_index": { + "type": "integer", + "description": "The index of the content part that the text content is finalized.\n" + }, + "text": { + "type": "string", + "description": "The text content that is finalized.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number for this event." + }, + "logprobs": { + "type": "array", + "description": "The log probabilities of the tokens in the delta.\n", + "items": { + "$ref": "#/components/schemas/ResponseLogProb" + } + } + }, + "required": [ + "type", + "item_id", + "output_index", + "content_index", + "text", + "sequence_number", + "logprobs" + ], + "x-oaiMeta": { + "name": "response.output_text.done", + "group": "responses", + "example": "{\n \"type\": \"response.output_text.done\",\n \"item_id\": \"msg_123\",\n \"output_index\": 0,\n \"content_index\": 0,\n \"text\": \"In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.\",\n \"sequence_number\": 1\n}\n" + } + }, + "ResponseUsage": { + "type": "object", + "description": "Represents token usage details including input tokens, output tokens,\na breakdown of output tokens, and the total tokens used.\n", + "properties": { + "input_tokens": { + "type": "integer", + "description": "The number of input tokens." + }, + "input_tokens_details": { + "type": "object", + "description": "A detailed breakdown of the input tokens.", + "properties": { + "cached_tokens": { + "type": "integer", + "description": "The number of tokens that were retrieved from the cache. \n[More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching).\n" + } + }, + "required": [ + "cached_tokens" + ] + }, + "output_tokens": { + "type": "integer", + "description": "The number of output tokens." + }, + "output_tokens_details": { + "type": "object", + "description": "A detailed breakdown of the output tokens.", + "properties": { + "reasoning_tokens": { + "type": "integer", + "description": "The number of reasoning tokens." + } + }, + "required": [ + "reasoning_tokens" + ] + }, + "total_tokens": { + "type": "integer", + "description": "The total number of tokens used." + } + }, + "required": [ + "input_tokens", + "input_tokens_details", + "output_tokens", + "output_tokens_details", + "total_tokens" + ] + }, + "ResponseWebSearchCallCompletedEvent": { + "type": "object", + "description": "Emitted when a web search call is completed.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.web_search_call.completed`.\n", + "enum": [ + "response.web_search_call.completed" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the web search call is associated with.\n" + }, + "item_id": { + "type": "string", + "description": "Unique ID for the output item associated with the web search call.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of the web search call being processed." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.web_search_call.completed", + "group": "responses", + "example": "{\n \"type\": \"response.web_search_call.completed\",\n \"output_index\": 0,\n \"item_id\": \"ws_123\",\n \"sequence_number\": 0\n}\n" + } + }, + "ResponseWebSearchCallInProgressEvent": { + "type": "object", + "description": "Emitted when a web search call is initiated.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.web_search_call.in_progress`.\n", + "enum": [ + "response.web_search_call.in_progress" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the web search call is associated with.\n" + }, + "item_id": { + "type": "string", + "description": "Unique ID for the output item associated with the web search call.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of the web search call being processed." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.web_search_call.in_progress", + "group": "responses", + "example": "{\n \"type\": \"response.web_search_call.in_progress\",\n \"output_index\": 0,\n \"item_id\": \"ws_123\",\n \"sequence_number\": 0\n}\n" + } + }, + "ResponseWebSearchCallSearchingEvent": { + "type": "object", + "description": "Emitted when a web search call is executing.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `response.web_search_call.searching`.\n", + "enum": [ + "response.web_search_call.searching" + ], + "x-stainless-const": true + }, + "output_index": { + "type": "integer", + "description": "The index of the output item that the web search call is associated with.\n" + }, + "item_id": { + "type": "string", + "description": "Unique ID for the output item associated with the web search call.\n" + }, + "sequence_number": { + "type": "integer", + "description": "The sequence number of the web search call being processed." + } + }, + "required": [ + "type", + "output_index", + "item_id", + "sequence_number" + ], + "x-oaiMeta": { + "name": "response.web_search_call.searching", + "group": "responses", + "example": "{\n \"type\": \"response.web_search_call.searching\",\n \"output_index\": 0,\n \"item_id\": \"ws_123\",\n \"sequence_number\": 0\n}\n" + } + }, + "RunCompletionUsage": { + "type": "object", + "description": "Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.).", + "properties": { + "completion_tokens": { + "type": "integer", + "description": "Number of completion tokens used over the course of the run." + }, + "prompt_tokens": { + "type": "integer", + "description": "Number of prompt tokens used over the course of the run." + }, + "total_tokens": { + "type": "integer", + "description": "Total number of tokens used (prompt + completion)." + } + }, + "required": [ + "prompt_tokens", + "completion_tokens", + "total_tokens" + ], + "nullable": true + }, + "RunGraderRequest": { + "type": "object", + "title": "RunGraderRequest", + "properties": { + "grader": { + "type": "object", + "description": "The grader used for the fine-tuning job.", + "anyOf": [ + { + "$ref": "#/components/schemas/GraderStringCheck" + }, + { + "$ref": "#/components/schemas/GraderTextSimilarity" + }, + { + "$ref": "#/components/schemas/GraderPython" + }, + { + "$ref": "#/components/schemas/GraderScoreModel" + }, + { + "$ref": "#/components/schemas/GraderMulti" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "item": { + "type": "object", + "description": "The dataset item provided to the grader. This will be used to populate\nthe `item` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details.\n" + }, + "model_sample": { + "type": "string", + "description": "The model sample to be evaluated. This value will be used to populate\nthe `sample` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details.\nThe `output_json` variable will be populated if the model sample is a\nvalid JSON string.\n" + } + }, + "required": [ + "grader", + "model_sample" + ] + }, + "RunGraderResponse": { + "type": "object", + "properties": { + "reward": { + "type": "number" + }, + "metadata": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "type": { + "type": "string" + }, + "errors": { + "type": "object", + "properties": { + "formula_parse_error": { + "type": "boolean" + }, + "sample_parse_error": { + "type": "boolean" + }, + "truncated_observation_error": { + "type": "boolean" + }, + "unresponsive_reward_error": { + "type": "boolean" + }, + "invalid_variable_error": { + "type": "boolean" + }, + "other_error": { + "type": "boolean" + }, + "python_grader_server_error": { + "type": "boolean" + }, + "python_grader_server_error_type": { + "type": "string", + "nullable": true + }, + "python_grader_runtime_error": { + "type": "boolean" + }, + "python_grader_runtime_error_details": { + "type": "string", + "nullable": true + }, + "model_grader_server_error": { + "type": "boolean" + }, + "model_grader_refusal_error": { + "type": "boolean" + }, + "model_grader_parse_error": { + "type": "boolean" + }, + "model_grader_server_error_details": { + "type": "string", + "nullable": true + } + }, + "required": [ + "formula_parse_error", + "sample_parse_error", + "truncated_observation_error", + "unresponsive_reward_error", + "invalid_variable_error", + "other_error", + "python_grader_server_error", + "python_grader_server_error_type", + "python_grader_runtime_error", + "python_grader_runtime_error_details", + "model_grader_server_error", + "model_grader_refusal_error", + "model_grader_parse_error", + "model_grader_server_error_details" + ] + }, + "execution_time": { + "type": "number" + }, + "scores": { + "type": "object", + "additionalProperties": {} + }, + "token_usage": { + "type": "integer", + "nullable": true + }, + "sampled_model_name": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "type", + "errors", + "execution_time", + "scores", + "token_usage", + "sampled_model_name" + ] + }, + "sub_rewards": { + "type": "object", + "additionalProperties": {} + }, + "model_grader_token_usage_per_model": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "reward", + "metadata", + "sub_rewards", + "model_grader_token_usage_per_model" + ] + }, + "RunObject": { + "type": "object", + "title": "A run on a thread", + "description": "Represents an execution run on a [thread](https://platform.openai.com/docs/api-reference/threads).", + "properties": { + "id": { + "description": "The identifier, which can be referenced in API endpoints.", + "type": "string" + }, + "object": { + "description": "The object type, which is always `thread.run`.", + "type": "string", + "enum": [ + "thread.run" + ], + "x-stainless-const": true + }, + "created_at": { + "description": "The Unix timestamp (in seconds) for when the run was created.", + "type": "integer" + }, + "thread_id": { + "description": "The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was executed on as a part of this run.", + "type": "string" + }, + "assistant_id": { + "description": "The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for execution of this run.", + "type": "string" + }, + "status": { + "$ref": "#/components/schemas/RunStatus" + }, + "required_action": { + "type": "object", + "description": "Details on the action required to continue the run. Will be `null` if no action is required.", + "nullable": true, + "properties": { + "type": { + "description": "For now, this is always `submit_tool_outputs`.", + "type": "string", + "enum": [ + "submit_tool_outputs" + ], + "x-stainless-const": true + }, + "submit_tool_outputs": { + "type": "object", + "description": "Details on the tool outputs needed for this run to continue.", + "properties": { + "tool_calls": { + "type": "array", + "description": "A list of the relevant tool calls.", + "items": { + "$ref": "#/components/schemas/RunToolCallObject" + } + } + }, + "required": [ + "tool_calls" + ] + } + }, + "required": [ + "type", + "submit_tool_outputs" + ] + }, + "last_error": { + "type": "object", + "description": "The last error associated with this run. Will be `null` if there are no errors.", + "nullable": true, + "properties": { + "code": { + "type": "string", + "description": "One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`.", + "enum": [ + "server_error", + "rate_limit_exceeded", + "invalid_prompt" + ] + }, + "message": { + "type": "string", + "description": "A human-readable description of the error." + } + }, + "required": [ + "code", + "message" + ] + }, + "expires_at": { + "description": "The Unix timestamp (in seconds) for when the run will expire.", + "type": "integer", + "nullable": true + }, + "started_at": { + "description": "The Unix timestamp (in seconds) for when the run was started.", + "type": "integer", + "nullable": true + }, + "cancelled_at": { + "description": "The Unix timestamp (in seconds) for when the run was cancelled.", + "type": "integer", + "nullable": true + }, + "failed_at": { + "description": "The Unix timestamp (in seconds) for when the run failed.", + "type": "integer", + "nullable": true + }, + "completed_at": { + "description": "The Unix timestamp (in seconds) for when the run was completed.", + "type": "integer", + "nullable": true + }, + "incomplete_details": { + "description": "Details on why the run is incomplete. Will be `null` if the run is not incomplete.", + "type": "object", + "nullable": true, + "properties": { + "reason": { + "description": "The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run.", + "type": "string", + "enum": [ + "max_completion_tokens", + "max_prompt_tokens" + ] + } + } + }, + "model": { + "description": "The model that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.", + "type": "string" + }, + "instructions": { + "description": "The instructions that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.", + "type": "string" + }, + "tools": { + "description": "The list of tools that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.", + "default": [], + "type": "array", + "maxItems": 20, + "items": { + "$ref": "#/components/schemas/AssistantTool" + } + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "usage": { + "$ref": "#/components/schemas/RunCompletionUsage" + }, + "temperature": { + "description": "The sampling temperature used for this run. If not set, defaults to 1.", + "type": "number", + "nullable": true + }, + "top_p": { + "description": "The nucleus sampling value used for this run. If not set, defaults to 1.", + "type": "number", + "nullable": true + }, + "max_prompt_tokens": { + "type": "integer", + "nullable": true, + "description": "The maximum number of prompt tokens specified to have been used over the course of the run.\n", + "minimum": 256 + }, + "max_completion_tokens": { + "type": "integer", + "nullable": true, + "description": "The maximum number of completion tokens specified to have been used over the course of the run.\n", + "minimum": 256 + }, + "truncation_strategy": { + "allOf": [ + { + "$ref": "#/components/schemas/TruncationObject" + }, + { + "nullable": true + } + ] + }, + "tool_choice": { + "allOf": [ + { + "$ref": "#/components/schemas/AssistantsApiToolChoiceOption" + }, + { + "nullable": true + } + ] + }, + "parallel_tool_calls": { + "$ref": "#/components/schemas/ParallelToolCalls" + }, + "response_format": { + "$ref": "#/components/schemas/AssistantsApiResponseFormatOption", + "nullable": true + } + }, + "required": [ + "id", + "object", + "created_at", + "thread_id", + "assistant_id", + "status", + "required_action", + "last_error", + "expires_at", + "started_at", + "cancelled_at", + "failed_at", + "completed_at", + "model", + "instructions", + "tools", + "metadata", + "usage", + "incomplete_details", + "max_prompt_tokens", + "max_completion_tokens", + "truncation_strategy", + "tool_choice", + "parallel_tool_calls", + "response_format" + ], + "x-oaiMeta": { + "name": "The run object", + "beta": true, + "example": "{\n \"id\": \"run_abc123\",\n \"object\": \"thread.run\",\n \"created_at\": 1698107661,\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"status\": \"completed\",\n \"started_at\": 1699073476,\n \"expires_at\": null,\n \"cancelled_at\": null,\n \"failed_at\": null,\n \"completed_at\": 1699073498,\n \"last_error\": null,\n \"model\": \"gpt-4o\",\n \"instructions\": null,\n \"tools\": [{\"type\": \"file_search\"}, {\"type\": \"code_interpreter\"}],\n \"metadata\": {},\n \"incomplete_details\": null,\n \"usage\": {\n \"prompt_tokens\": 123,\n \"completion_tokens\": 456,\n \"total_tokens\": 579\n },\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"max_prompt_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"truncation_strategy\": {\n \"type\": \"auto\",\n \"last_messages\": null\n },\n \"response_format\": \"auto\",\n \"tool_choice\": \"auto\",\n \"parallel_tool_calls\": true\n}\n" + } + }, + "RunStepCompletionUsage": { + "type": "object", + "description": "Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`.", + "properties": { + "completion_tokens": { + "type": "integer", + "description": "Number of completion tokens used over the course of the run step." + }, + "prompt_tokens": { + "type": "integer", + "description": "Number of prompt tokens used over the course of the run step." + }, + "total_tokens": { + "type": "integer", + "description": "Total number of tokens used (prompt + completion)." + } + }, + "required": [ + "prompt_tokens", + "completion_tokens", + "total_tokens" + ], + "nullable": true + }, + "RunStepDeltaObject": { + "type": "object", + "title": "Run step delta object", + "description": "Represents a run step delta i.e. any changed fields on a run step during streaming.\n", + "properties": { + "id": { + "description": "The identifier of the run step, which can be referenced in API endpoints.", + "type": "string" + }, + "object": { + "description": "The object type, which is always `thread.run.step.delta`.", + "type": "string", + "enum": [ + "thread.run.step.delta" + ], + "x-stainless-const": true + }, + "delta": { + "$ref": "#/components/schemas/RunStepDeltaObjectDelta" + } + }, + "required": [ + "id", + "object", + "delta" + ], + "x-oaiMeta": { + "name": "The run step delta object", + "beta": true, + "example": "{\n \"id\": \"step_123\",\n \"object\": \"thread.run.step.delta\",\n \"delta\": {\n \"step_details\": {\n \"type\": \"tool_calls\",\n \"tool_calls\": [\n {\n \"index\": 0,\n \"id\": \"call_123\",\n \"type\": \"code_interpreter\",\n \"code_interpreter\": { \"input\": \"\", \"outputs\": [] }\n }\n ]\n }\n }\n}\n" + } + }, + "RunStepDeltaStepDetailsMessageCreationObject": { + "title": "Message creation", + "type": "object", + "description": "Details of the message creation by the run step.", + "properties": { + "type": { + "description": "Always `message_creation`.", + "type": "string", + "enum": [ + "message_creation" + ], + "x-stainless-const": true + }, + "message_creation": { + "type": "object", + "properties": { + "message_id": { + "type": "string", + "description": "The ID of the message that was created by this run step." + } + } + } + }, + "required": [ + "type" + ] + }, + "RunStepDeltaStepDetailsToolCallsCodeObject": { + "title": "Code interpreter tool call", + "type": "object", + "description": "Details of the Code Interpreter tool call the run step was involved in.", + "properties": { + "index": { + "type": "integer", + "description": "The index of the tool call in the tool calls array." + }, + "id": { + "type": "string", + "description": "The ID of the tool call." + }, + "type": { + "type": "string", + "description": "The type of tool call. This is always going to be `code_interpreter` for this type of tool call.", + "enum": [ + "code_interpreter" + ], + "x-stainless-const": true + }, + "code_interpreter": { + "type": "object", + "description": "The Code Interpreter tool call definition.", + "properties": { + "input": { + "type": "string", + "description": "The input to the Code Interpreter tool call." + }, + "outputs": { + "type": "array", + "description": "The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type.", + "items": { + "type": "object", + "anyOf": [ + { + "$ref": "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject" + }, + { + "$ref": "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputImageObject" + } + ], + "discriminator": { + "propertyName": "type" + } + } + } + } + } + }, + "required": [ + "index", + "type" + ] + }, + "RunStepDeltaStepDetailsToolCallsCodeOutputImageObject": { + "title": "Code interpreter image output", + "type": "object", + "properties": { + "index": { + "type": "integer", + "description": "The index of the output in the outputs array." + }, + "type": { + "description": "Always `image`.", + "type": "string", + "enum": [ + "image" + ], + "x-stainless-const": true + }, + "image": { + "type": "object", + "properties": { + "file_id": { + "description": "The [file](https://platform.openai.com/docs/api-reference/files) ID of the image.", + "type": "string" + } + } + } + }, + "required": [ + "index", + "type" + ] + }, + "RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject": { + "title": "Code interpreter log output", + "type": "object", + "description": "Text output from the Code Interpreter tool call as part of a run step.", + "properties": { + "index": { + "type": "integer", + "description": "The index of the output in the outputs array." + }, + "type": { + "description": "Always `logs`.", + "type": "string", + "enum": [ + "logs" + ], + "x-stainless-const": true + }, + "logs": { + "type": "string", + "description": "The text output from the Code Interpreter tool call." + } + }, + "required": [ + "index", + "type" + ] + }, + "RunStepDeltaStepDetailsToolCallsFileSearchObject": { + "title": "File search tool call", + "type": "object", + "properties": { + "index": { + "type": "integer", + "description": "The index of the tool call in the tool calls array." + }, + "id": { + "type": "string", + "description": "The ID of the tool call object." + }, + "type": { + "type": "string", + "description": "The type of tool call. This is always going to be `file_search` for this type of tool call.", + "enum": [ + "file_search" + ], + "x-stainless-const": true + }, + "file_search": { + "type": "object", + "description": "For now, this is always going to be an empty object.", + "x-oaiTypeLabel": "map" + } + }, + "required": [ + "index", + "type", + "file_search" + ] + }, + "RunStepDeltaStepDetailsToolCallsFunctionObject": { + "type": "object", + "title": "Function tool call", + "properties": { + "index": { + "type": "integer", + "description": "The index of the tool call in the tool calls array." + }, + "id": { + "type": "string", + "description": "The ID of the tool call object." + }, + "type": { + "type": "string", + "description": "The type of tool call. This is always going to be `function` for this type of tool call.", + "enum": [ + "function" + ], + "x-stainless-const": true + }, + "function": { + "type": "object", + "description": "The definition of the function that was called.", + "properties": { + "name": { + "type": "string", + "description": "The name of the function." + }, + "arguments": { + "type": "string", + "description": "The arguments passed to the function." + }, + "output": { + "type": "string", + "description": "The output of the function. This will be `null` if the outputs have not been [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) yet.", + "nullable": true + } + } + } + }, + "required": [ + "index", + "type" + ] + }, + "RunStepDeltaStepDetailsToolCallsObject": { + "title": "Tool calls", + "type": "object", + "description": "Details of the tool call.", + "properties": { + "type": { + "description": "Always `tool_calls`.", + "type": "string", + "enum": [ + "tool_calls" + ], + "x-stainless-const": true + }, + "tool_calls": { + "type": "array", + "description": "An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n", + "items": { + "$ref": "#/components/schemas/RunStepDeltaStepDetailsToolCall" + } + } + }, + "required": [ + "type" + ] + }, + "RunStepDetailsMessageCreationObject": { + "title": "Message creation", + "type": "object", + "description": "Details of the message creation by the run step.", + "properties": { + "type": { + "description": "Always `message_creation`.", + "type": "string", + "enum": [ + "message_creation" + ], + "x-stainless-const": true + }, + "message_creation": { + "type": "object", + "properties": { + "message_id": { + "type": "string", + "description": "The ID of the message that was created by this run step." + } + }, + "required": [ + "message_id" + ] + } + }, + "required": [ + "type", + "message_creation" + ] + }, + "RunStepDetailsToolCallsCodeObject": { + "title": "Code Interpreter tool call", + "type": "object", + "description": "Details of the Code Interpreter tool call the run step was involved in.", + "properties": { + "id": { + "type": "string", + "description": "The ID of the tool call." + }, + "type": { + "type": "string", + "description": "The type of tool call. This is always going to be `code_interpreter` for this type of tool call.", + "enum": [ + "code_interpreter" + ], + "x-stainless-const": true + }, + "code_interpreter": { + "type": "object", + "description": "The Code Interpreter tool call definition.", + "required": [ + "input", + "outputs" + ], + "properties": { + "input": { + "type": "string", + "description": "The input to the Code Interpreter tool call." + }, + "outputs": { + "type": "array", + "description": "The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type.", + "items": { + "type": "object", + "anyOf": [ + { + "$ref": "#/components/schemas/RunStepDetailsToolCallsCodeOutputLogsObject" + }, + { + "$ref": "#/components/schemas/RunStepDetailsToolCallsCodeOutputImageObject" + } + ], + "discriminator": { + "propertyName": "type" + } + } + } + } + } + }, + "required": [ + "id", + "type", + "code_interpreter" + ] + }, + "RunStepDetailsToolCallsCodeOutputImageObject": { + "title": "Code Interpreter image output", + "type": "object", + "properties": { + "type": { + "description": "Always `image`.", + "type": "string", + "enum": [ + "image" + ], + "x-stainless-const": true + }, + "image": { + "type": "object", + "properties": { + "file_id": { + "description": "The [file](https://platform.openai.com/docs/api-reference/files) ID of the image.", + "type": "string" + } + }, + "required": [ + "file_id" + ] + } + }, + "required": [ + "type", + "image" + ], + "x-stainless-naming": { + "java": { + "type_name": "ImageOutput" + }, + "kotlin": { + "type_name": "ImageOutput" + } + } + }, + "RunStepDetailsToolCallsCodeOutputLogsObject": { + "title": "Code Interpreter log output", + "type": "object", + "description": "Text output from the Code Interpreter tool call as part of a run step.", + "properties": { + "type": { + "description": "Always `logs`.", + "type": "string", + "enum": [ + "logs" + ], + "x-stainless-const": true + }, + "logs": { + "type": "string", + "description": "The text output from the Code Interpreter tool call." + } + }, + "required": [ + "type", + "logs" + ], + "x-stainless-naming": { + "java": { + "type_name": "LogsOutput" + }, + "kotlin": { + "type_name": "LogsOutput" + } + } + }, + "RunStepDetailsToolCallsFileSearchObject": { + "title": "File search tool call", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The ID of the tool call object." + }, + "type": { + "type": "string", + "description": "The type of tool call. This is always going to be `file_search` for this type of tool call.", + "enum": [ + "file_search" + ], + "x-stainless-const": true + }, + "file_search": { + "type": "object", + "description": "For now, this is always going to be an empty object.", + "x-oaiTypeLabel": "map", + "properties": { + "ranking_options": { + "$ref": "#/components/schemas/RunStepDetailsToolCallsFileSearchRankingOptionsObject" + }, + "results": { + "type": "array", + "description": "The results of the file search.", + "items": { + "$ref": "#/components/schemas/RunStepDetailsToolCallsFileSearchResultObject" + } + } + } + } + }, + "required": [ + "id", + "type", + "file_search" + ] + }, + "RunStepDetailsToolCallsFileSearchRankingOptionsObject": { + "title": "File search tool call ranking options", + "type": "object", + "description": "The ranking options for the file search.", + "properties": { + "ranker": { + "$ref": "#/components/schemas/FileSearchRanker" + }, + "score_threshold": { + "type": "number", + "description": "The score threshold for the file search. All values must be a floating point number between 0 and 1.", + "minimum": 0, + "maximum": 1 + } + }, + "required": [ + "ranker", + "score_threshold" + ] + }, + "RunStepDetailsToolCallsFileSearchResultObject": { + "title": "File search tool call result", + "type": "object", + "description": "A result instance of the file search.", + "x-oaiTypeLabel": "map", + "properties": { + "file_id": { + "type": "string", + "description": "The ID of the file that result was found in." + }, + "file_name": { + "type": "string", + "description": "The name of the file that result was found in." + }, + "score": { + "type": "number", + "description": "The score of the result. All values must be a floating point number between 0 and 1.", + "minimum": 0, + "maximum": 1 + }, + "content": { + "type": "array", + "description": "The content of the result that was found. The content is only included if requested via the include query parameter.", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "The type of the content.", + "enum": [ + "text" + ], + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text content of the file." + } + } + } + } + }, + "required": [ + "file_id", + "file_name", + "score" + ] + }, + "RunStepDetailsToolCallsFunctionObject": { + "type": "object", + "title": "Function tool call", + "properties": { + "id": { + "type": "string", + "description": "The ID of the tool call object." + }, + "type": { + "type": "string", + "description": "The type of tool call. This is always going to be `function` for this type of tool call.", + "enum": [ + "function" + ], + "x-stainless-const": true + }, + "function": { + "type": "object", + "description": "The definition of the function that was called.", + "properties": { + "name": { + "type": "string", + "description": "The name of the function." + }, + "arguments": { + "type": "string", + "description": "The arguments passed to the function." + }, + "output": { + "type": "string", + "description": "The output of the function. This will be `null` if the outputs have not been [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) yet.", + "nullable": true + } + }, + "required": [ + "name", + "arguments", + "output" + ] + } + }, + "required": [ + "id", + "type", + "function" + ] + }, + "RunStepDetailsToolCallsObject": { + "title": "Tool calls", + "type": "object", + "description": "Details of the tool call.", + "properties": { + "type": { + "description": "Always `tool_calls`.", + "type": "string", + "enum": [ + "tool_calls" + ], + "x-stainless-const": true + }, + "tool_calls": { + "type": "array", + "description": "An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n", + "items": { + "$ref": "#/components/schemas/RunStepDetailsToolCall" + } + } + }, + "required": [ + "type", + "tool_calls" + ] + }, + "RunStepObject": { + "type": "object", + "title": "Run steps", + "description": "Represents a step in execution of a run.\n", + "properties": { + "id": { + "description": "The identifier of the run step, which can be referenced in API endpoints.", + "type": "string" + }, + "object": { + "description": "The object type, which is always `thread.run.step`.", + "type": "string", + "enum": [ + "thread.run.step" + ], + "x-stainless-const": true + }, + "created_at": { + "description": "The Unix timestamp (in seconds) for when the run step was created.", + "type": "integer" + }, + "assistant_id": { + "description": "The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) associated with the run step.", + "type": "string" + }, + "thread_id": { + "description": "The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run.", + "type": "string" + }, + "run_id": { + "description": "The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that this run step is a part of.", + "type": "string" + }, + "type": { + "description": "The type of run step, which can be either `message_creation` or `tool_calls`.", + "type": "string", + "enum": [ + "message_creation", + "tool_calls" + ] + }, + "status": { + "description": "The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`.", + "type": "string", + "enum": [ + "in_progress", + "cancelled", + "failed", + "completed", + "expired" + ] + }, + "step_details": { + "type": "object", + "description": "The details of the run step.", + "anyOf": [ + { + "$ref": "#/components/schemas/RunStepDetailsMessageCreationObject" + }, + { + "$ref": "#/components/schemas/RunStepDetailsToolCallsObject" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "last_error": { + "type": "object", + "description": "The last error associated with this run step. Will be `null` if there are no errors.", + "nullable": true, + "properties": { + "code": { + "type": "string", + "description": "One of `server_error` or `rate_limit_exceeded`.", + "enum": [ + "server_error", + "rate_limit_exceeded" + ] + }, + "message": { + "type": "string", + "description": "A human-readable description of the error." + } + }, + "required": [ + "code", + "message" + ] + }, + "expired_at": { + "description": "The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired.", + "type": "integer", + "nullable": true + }, + "cancelled_at": { + "description": "The Unix timestamp (in seconds) for when the run step was cancelled.", + "type": "integer", + "nullable": true + }, + "failed_at": { + "description": "The Unix timestamp (in seconds) for when the run step failed.", + "type": "integer", + "nullable": true + }, + "completed_at": { + "description": "The Unix timestamp (in seconds) for when the run step completed.", + "type": "integer", + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "usage": { + "$ref": "#/components/schemas/RunStepCompletionUsage" + } + }, + "required": [ + "id", + "object", + "created_at", + "assistant_id", + "thread_id", + "run_id", + "type", + "status", + "step_details", + "last_error", + "expired_at", + "cancelled_at", + "failed_at", + "completed_at", + "metadata", + "usage" + ], + "x-oaiMeta": { + "name": "The run step object", + "beta": true, + "example": "{\n \"id\": \"step_abc123\",\n \"object\": \"thread.run.step\",\n \"created_at\": 1699063291,\n \"run_id\": \"run_abc123\",\n \"assistant_id\": \"asst_abc123\",\n \"thread_id\": \"thread_abc123\",\n \"type\": \"message_creation\",\n \"status\": \"completed\",\n \"cancelled_at\": null,\n \"completed_at\": 1699063291,\n \"expired_at\": null,\n \"failed_at\": null,\n \"last_error\": null,\n \"step_details\": {\n \"type\": \"message_creation\",\n \"message_creation\": {\n \"message_id\": \"msg_abc123\"\n }\n },\n \"usage\": {\n \"prompt_tokens\": 123,\n \"completion_tokens\": 456,\n \"total_tokens\": 579\n }\n}\n" + } + }, + "RunStepStreamEvent": { + "anyOf": [ + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.step.created" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunStepObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) is created.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run step](/docs/api-reference/run-steps/step-object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.step.in_progress" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunStepObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) moves to an `in_progress` state.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run step](/docs/api-reference/run-steps/step-object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.step.delta" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunStepDeltaObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when parts of a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) are being streamed.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run step delta](/docs/api-reference/assistants-streaming/run-step-delta-object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.step.completed" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunStepObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) is completed.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run step](/docs/api-reference/run-steps/step-object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.step.failed" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunStepObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) fails.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run step](/docs/api-reference/run-steps/step-object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.step.cancelled" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunStepObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) is cancelled.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run step](/docs/api-reference/run-steps/step-object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.step.expired" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunStepObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) expires.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run step](/docs/api-reference/run-steps/step-object)" + } + } + ], + "discriminator": { + "propertyName": "event" + } + }, + "RunStreamEvent": { + "anyOf": [ + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.created" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a new [run](https://platform.openai.com/docs/api-reference/runs/object) is created.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run](/docs/api-reference/runs/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.queued" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to a `queued` status.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run](/docs/api-reference/runs/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.in_progress" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to an `in_progress` status.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run](/docs/api-reference/runs/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.requires_action" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to a `requires_action` status.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run](/docs/api-reference/runs/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.completed" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) is completed.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run](/docs/api-reference/runs/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.incomplete" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) ends with status `incomplete`.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run](/docs/api-reference/runs/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.failed" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) fails.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run](/docs/api-reference/runs/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.cancelling" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) moves to a `cancelling` status.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run](/docs/api-reference/runs/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.cancelled" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) is cancelled.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run](/docs/api-reference/runs/object)" + } + }, + { + "type": "object", + "properties": { + "event": { + "type": "string", + "enum": [ + "thread.run.expired" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/RunObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) expires.", + "x-oaiMeta": { + "dataDescription": "`data` is a [run](/docs/api-reference/runs/object)" + } + } + ], + "discriminator": { + "propertyName": "event" + } + }, + "RunToolCallObject": { + "type": "object", + "description": "Tool call objects", + "properties": { + "id": { + "type": "string", + "description": "The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) endpoint." + }, + "type": { + "type": "string", + "description": "The type of tool call the output is required for. For now, this is always `function`.", + "enum": [ + "function" + ], + "x-stainless-const": true + }, + "function": { + "type": "object", + "description": "The function definition.", + "properties": { + "name": { + "type": "string", + "description": "The name of the function." + }, + "arguments": { + "type": "string", + "description": "The arguments that the model expects you to pass to the function." + } + }, + "required": [ + "name", + "arguments" + ] + } + }, + "required": [ + "id", + "type", + "function" + ] + }, + "Screenshot": { + "type": "object", + "title": "Screenshot", + "description": "A screenshot action.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "screenshot" + ], + "default": "screenshot", + "description": "Specifies the event type. For a screenshot action, this property is \nalways set to `screenshot`.\n", + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + "Scroll": { + "type": "object", + "title": "Scroll", + "description": "A scroll action.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "scroll" + ], + "default": "scroll", + "description": "Specifies the event type. For a scroll action, this property is \nalways set to `scroll`.\n", + "x-stainless-const": true + }, + "x": { + "type": "integer", + "description": "The x-coordinate where the scroll occurred.\n" + }, + "y": { + "type": "integer", + "description": "The y-coordinate where the scroll occurred.\n" + }, + "scroll_x": { + "type": "integer", + "description": "The horizontal scroll distance.\n" + }, + "scroll_y": { + "type": "integer", + "description": "The vertical scroll distance.\n" + } + }, + "required": [ + "type", + "x", + "y", + "scroll_x", + "scroll_y" + ] + }, + "ServiceTier": { + "type": "string", + "description": "Specifies the processing type used for serving the request.\n - If set to 'auto', then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use 'default'.\n - If set to 'default', then the request will be processed with the standard pricing and performance for the selected model.\n - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or '[priority](https://openai.com/api-priority-processing/)', then the request will be processed with the corresponding service tier.\n - When not set, the default behavior is 'auto'.\n\n When the `service_tier` parameter is set, the response body will include the `service_tier` value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter.\n", + "enum": [ + "auto", + "default", + "flex", + "scale", + "priority" + ], + "nullable": true, + "default": "auto" + }, + "SpeechAudioDeltaEvent": { + "type": "object", + "description": "Emitted for each chunk of audio data generated during speech synthesis.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `speech.audio.delta`.\n", + "enum": [ + "speech.audio.delta" + ], + "x-stainless-const": true + }, + "audio": { + "type": "string", + "description": "A chunk of Base64-encoded audio data.\n" + } + }, + "required": [ + "type", + "audio" + ], + "x-oaiMeta": { + "name": "Stream Event (speech.audio.delta)", + "group": "speech", + "example": "{\n \"type\": \"speech.audio.delta\",\n \"audio\": \"base64-encoded-audio-data\"\n}\n" + } + }, + "SpeechAudioDoneEvent": { + "type": "object", + "description": "Emitted when the speech synthesis is complete and all audio has been streamed.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `speech.audio.done`.\n", + "enum": [ + "speech.audio.done" + ], + "x-stainless-const": true + }, + "usage": { + "type": "object", + "description": "Token usage statistics for the request.\n", + "properties": { + "input_tokens": { + "type": "integer", + "description": "Number of input tokens in the prompt." + }, + "output_tokens": { + "type": "integer", + "description": "Number of output tokens generated." + }, + "total_tokens": { + "type": "integer", + "description": "Total number of tokens used (input + output)." + } + }, + "required": [ + "input_tokens", + "output_tokens", + "total_tokens" + ] + } + }, + "required": [ + "type", + "usage" + ], + "x-oaiMeta": { + "name": "Stream Event (speech.audio.done)", + "group": "speech", + "example": "{\n \"type\": \"speech.audio.done\",\n \"usage\": {\n \"input_tokens\": 14,\n \"output_tokens\": 101,\n \"total_tokens\": 115\n }\n}\n" + } + }, + "StaticChunkingStrategy": { + "type": "object", + "additionalProperties": false, + "properties": { + "max_chunk_size_tokens": { + "type": "integer", + "minimum": 100, + "maximum": 4096, + "description": "The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`." + }, + "chunk_overlap_tokens": { + "type": "integer", + "description": "The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" + } + }, + "required": [ + "max_chunk_size_tokens", + "chunk_overlap_tokens" + ] + }, + "StaticChunkingStrategyRequestParam": { + "type": "object", + "title": "Static Chunking Strategy", + "description": "Customize your own chunking strategy by setting chunk size and chunk overlap.", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "Always `static`.", + "enum": [ + "static" + ], + "x-stainless-const": true + }, + "static": { + "$ref": "#/components/schemas/StaticChunkingStrategy" + } + }, + "required": [ + "type", + "static" + ] + }, + "StaticChunkingStrategyResponseParam": { + "type": "object", + "title": "Static Chunking Strategy", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "description": "Always `static`.", + "enum": [ + "static" + ], + "x-stainless-const": true + }, + "static": { + "$ref": "#/components/schemas/StaticChunkingStrategy" + } + }, + "required": [ + "type", + "static" + ] + }, + "StopConfiguration": { + "description": "Not supported with latest reasoning models `o3` and `o4-mini`.\n\nUp to 4 sequences where the API will stop generating further tokens. The\nreturned text will not contain the stop sequence.\n", + "nullable": true, + "anyOf": [ + { + "type": "string", + "default": "<|endoftext|>", + "example": "\n\n", + "nullable": true + }, + { + "type": "array", + "minItems": 1, + "maxItems": 4, + "items": { + "type": "string", + "example": "[\"\\n\"]" + } + } + ] + }, + "SubmitToolOutputsRunRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "tool_outputs": { + "description": "A list of tools for which the outputs are being submitted.", + "type": "array", + "items": { + "type": "object", + "properties": { + "tool_call_id": { + "type": "string", + "description": "The ID of the tool call in the `required_action` object within the run object the output is being submitted for." + }, + "output": { + "type": "string", + "description": "The output of the tool call to be submitted to continue the run." + } + } + } + }, + "stream": { + "type": "boolean", + "nullable": true, + "description": "If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" + } + }, + "required": [ + "tool_outputs" + ] + }, + "TextResponseFormatConfiguration": { + "description": "An object specifying the format that the model must output.\n\nConfiguring `{ \"type\": \"json_schema\" }` enables Structured Outputs, \nwhich ensures the model will match your supplied JSON schema. Learn more in the \n[Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n\nThe default format is `{ \"type\": \"text\" }` with no additional options.\n\n**Not recommended for gpt-4o and newer models:**\n\nSetting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n", + "anyOf": [ + { + "$ref": "#/components/schemas/ResponseFormatText" + }, + { + "$ref": "#/components/schemas/TextResponseFormatJsonSchema" + }, + { + "$ref": "#/components/schemas/ResponseFormatJsonObject" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "TextResponseFormatJsonSchema": { + "type": "object", + "title": "JSON schema", + "description": "JSON Schema response format. Used to generate structured JSON responses.\nLearn more about [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs).\n", + "properties": { + "type": { + "type": "string", + "description": "The type of response format being defined. Always `json_schema`.", + "enum": [ + "json_schema" + ], + "x-stainless-const": true + }, + "description": { + "type": "string", + "description": "A description of what the response format is for, used by the model to\ndetermine how to respond in the format.\n" + }, + "name": { + "type": "string", + "description": "The name of the response format. Must be a-z, A-Z, 0-9, or contain\nunderscores and dashes, with a maximum length of 64.\n" + }, + "schema": { + "$ref": "#/components/schemas/ResponseFormatJsonSchemaSchema" + }, + "strict": { + "type": "boolean", + "nullable": true, + "default": false, + "description": "Whether to enable strict schema adherence when generating the output.\nIf set to true, the model will always follow the exact schema defined\nin the `schema` field. Only a subset of JSON Schema is supported when\n`strict` is `true`. To learn more, read the [Structured Outputs\nguide](https://platform.openai.com/docs/guides/structured-outputs).\n" + } + }, + "required": [ + "type", + "schema", + "name" + ] + }, + "ThreadObject": { + "type": "object", + "title": "Thread", + "description": "Represents a thread that contains [messages](https://platform.openai.com/docs/api-reference/messages).", + "properties": { + "id": { + "description": "The identifier, which can be referenced in API endpoints.", + "type": "string" + }, + "object": { + "description": "The object type, which is always `thread`.", + "type": "string", + "enum": [ + "thread" + ], + "x-stainless-const": true + }, + "created_at": { + "description": "The Unix timestamp (in seconds) for when the thread was created.", + "type": "integer" + }, + "tool_resources": { + "type": "object", + "description": "A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n", + "properties": { + "code_interpreter": { + "type": "object", + "properties": { + "file_ids": { + "type": "array", + "description": "A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + "default": [], + "maxItems": 20, + "items": { + "type": "string" + } + } + } + }, + "file_search": { + "type": "object", + "properties": { + "vector_store_ids": { + "type": "array", + "description": "The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n", + "maxItems": 1, + "items": { + "type": "string" + } + } + } + } + }, + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + }, + "required": [ + "id", + "object", + "created_at", + "tool_resources", + "metadata" + ], + "x-oaiMeta": { + "name": "The thread object", + "beta": true, + "example": "{\n \"id\": \"thread_abc123\",\n \"object\": \"thread\",\n \"created_at\": 1698107661,\n \"metadata\": {}\n}\n" + } + }, + "ThreadStreamEvent": { + "anyOf": [ + { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Whether to enable input audio transcription." + }, + "event": { + "type": "string", + "enum": [ + "thread.created" + ], + "x-stainless-const": true + }, + "data": { + "$ref": "#/components/schemas/ThreadObject" + } + }, + "required": [ + "event", + "data" + ], + "description": "Occurs when a new [thread](https://platform.openai.com/docs/api-reference/threads/object) is created.", + "x-oaiMeta": { + "dataDescription": "`data` is a [thread](/docs/api-reference/threads/object)" + } + } + ], + "discriminator": { + "propertyName": "event" + } + }, + "ToggleCertificatesRequest": { + "type": "object", + "properties": { + "certificate_ids": { + "type": "array", + "items": { + "type": "string", + "example": "cert_abc" + }, + "minItems": 1, + "maxItems": 10 + } + }, + "required": [ + "certificate_ids" + ] + }, + "Tool": { + "description": "A tool that can be used to generate a response.\n", + "discriminator": { + "propertyName": "type" + }, + "anyOf": [ + { + "$ref": "#/components/schemas/FunctionTool" + }, + { + "$ref": "#/components/schemas/FileSearchTool" + }, + { + "$ref": "#/components/schemas/ComputerUsePreviewTool" + }, + { + "$ref": "#/components/schemas/WebSearchTool" + }, + { + "$ref": "#/components/schemas/MCPTool" + }, + { + "$ref": "#/components/schemas/CodeInterpreterTool" + }, + { + "$ref": "#/components/schemas/ImageGenTool" + }, + { + "$ref": "#/components/schemas/LocalShellTool" + }, + { + "$ref": "#/components/schemas/CustomTool" + }, + { + "$ref": "#/components/schemas/WebSearchPreviewTool" + } + ] + }, + "ToolChoiceAllowed": { + "type": "object", + "title": "Allowed tools", + "description": "Constrains the tools available to the model to a pre-defined set.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "allowed_tools" + ], + "description": "Allowed tool configuration type. Always `allowed_tools`.", + "x-stainless-const": true + }, + "mode": { + "type": "string", + "enum": [ + "auto", + "required" + ], + "description": "Constrains the tools available to the model to a pre-defined set.\n\n`auto` allows the model to pick from among the allowed tools and generate a\nmessage.\n\n`required` requires the model to call one or more of the allowed tools.\n" + }, + "tools": { + "type": "array", + "description": "A list of tool definitions that the model should be allowed to call.\n\nFor the Responses API, the list of tool definitions might look like:\n```json\n[\n { \"type\": \"function\", \"name\": \"get_weather\" },\n { \"type\": \"mcp\", \"server_label\": \"deepwiki\" },\n { \"type\": \"image_generation\" }\n]\n```\n", + "items": { + "type": "object", + "description": "A tool definition that the model should be allowed to call.\n", + "additionalProperties": true, + "x-oaiExpandable": false + } + } + }, + "required": [ + "type", + "mode", + "tools" + ] + }, + "ToolChoiceCustom": { + "type": "object", + "title": "Custom tool", + "description": "Use this option to force the model to call a specific custom tool.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "custom" + ], + "description": "For custom tool calling, the type is always `custom`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the custom tool to call." + } + }, + "required": [ + "type", + "name" + ] + }, + "ToolChoiceFunction": { + "type": "object", + "title": "Function tool", + "description": "Use this option to force the model to call a specific function.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "function" + ], + "description": "For function calling, the type is always `function`.", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the function to call." + } + }, + "required": [ + "type", + "name" + ] + }, + "ToolChoiceMCP": { + "type": "object", + "title": "MCP tool", + "description": "Use this option to force the model to call a specific tool on a remote MCP server.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "mcp" + ], + "description": "For MCP tools, the type is always `mcp`.", + "x-stainless-const": true + }, + "server_label": { + "type": "string", + "description": "The label of the MCP server to use.\n" + }, + "name": { + "type": "string", + "description": "The name of the tool to call on the server.\n", + "nullable": true + } + }, + "required": [ + "type", + "server_label" + ] + }, + "ToolChoiceOptions": { + "type": "string", + "title": "Tool choice mode", + "description": "Controls which (if any) tool is called by the model.\n\n`none` means the model will not call any tool and instead generates a message.\n\n`auto` means the model can pick between generating a message or calling one or\nmore tools.\n\n`required` means the model must call one or more tools.\n", + "enum": [ + "none", + "auto", + "required" + ] + }, + "ToolChoiceTypes": { + "type": "object", + "title": "Hosted tool", + "description": "Indicates that the model should use a built-in tool to generate a response.\n[Learn more about built-in tools](https://platform.openai.com/docs/guides/tools).\n", + "properties": { + "type": { + "type": "string", + "description": "The type of hosted tool the model should to use. Learn more about\n[built-in tools](https://platform.openai.com/docs/guides/tools).\n\nAllowed values are:\n- `file_search`\n- `web_search_preview`\n- `computer_use_preview`\n- `code_interpreter`\n- `image_generation`\n", + "enum": [ + "file_search", + "web_search_preview", + "computer_use_preview", + "web_search_preview_2025_03_11", + "image_generation", + "code_interpreter" + ] + } + }, + "required": [ + "type" + ] + }, + "TranscriptTextDeltaEvent": { + "type": "object", + "description": "Emitted when there is an additional text delta. This is also the first event emitted when the transcription starts. Only emitted when you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `Stream` parameter set to `true`.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `transcript.text.delta`.\n", + "enum": [ + "transcript.text.delta" + ], + "x-stainless-const": true + }, + "delta": { + "type": "string", + "description": "The text delta that was additionally transcribed.\n" + }, + "logprobs": { + "type": "array", + "description": "The log probabilities of the delta. Only included if you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`.\n", + "items": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "The token that was used to generate the log probability.\n" + }, + "logprob": { + "type": "number", + "description": "The log probability of the token.\n" + }, + "bytes": { + "type": "array", + "items": { + "type": "integer" + }, + "description": "The bytes that were used to generate the log probability.\n" + } + } + } + } + }, + "required": [ + "type", + "delta" + ], + "x-oaiMeta": { + "name": "Stream Event (transcript.text.delta)", + "group": "transcript", + "example": "{\n \"type\": \"transcript.text.delta\",\n \"delta\": \" wonderful\"\n}\n" + } + }, + "TranscriptTextDoneEvent": { + "type": "object", + "description": "Emitted when the transcription is complete. Contains the complete transcription text. Only emitted when you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `Stream` parameter set to `true`.", + "properties": { + "type": { + "type": "string", + "description": "The type of the event. Always `transcript.text.done`.\n", + "enum": [ + "transcript.text.done" + ], + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text that was transcribed.\n" + }, + "logprobs": { + "type": "array", + "description": "The log probabilities of the individual tokens in the transcription. Only included if you [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`.\n", + "items": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "The token that was used to generate the log probability.\n" + }, + "logprob": { + "type": "number", + "description": "The log probability of the token.\n" + }, + "bytes": { + "type": "array", + "items": { + "type": "integer" + }, + "description": "The bytes that were used to generate the log probability.\n" + } + } + } + }, + "usage": { + "$ref": "#/components/schemas/TranscriptTextUsageTokens" + } + }, + "required": [ + "type", + "text" + ], + "x-oaiMeta": { + "name": "Stream Event (transcript.text.done)", + "group": "transcript", + "example": "{\n \"type\": \"transcript.text.done\",\n \"text\": \"I see skies of blue and clouds of white, the bright blessed days, the dark sacred nights, and I think to myself, what a wonderful world.\",\n \"usage\": {\n \"type\": \"tokens\",\n \"input_tokens\": 14,\n \"input_token_details\": {\n \"text_tokens\": 10,\n \"audio_tokens\": 4\n },\n \"output_tokens\": 31,\n \"total_tokens\": 45\n }\n}\n" + } + }, + "TranscriptTextUsageDuration": { + "type": "object", + "title": "Duration Usage", + "description": "Usage statistics for models billed by audio input duration.", + "properties": { + "type": { + "type": "string", + "enum": [ + "duration" + ], + "description": "The type of the usage object. Always `duration` for this variant.", + "x-stainless-const": true + }, + "seconds": { + "type": "number", + "description": "Duration of the input audio in seconds." + } + }, + "required": [ + "type", + "seconds" + ] + }, + "TranscriptTextUsageTokens": { + "type": "object", + "title": "Token Usage", + "description": "Usage statistics for models billed by token usage.", + "properties": { + "type": { + "type": "string", + "enum": [ + "tokens" + ], + "description": "The type of the usage object. Always `tokens` for this variant.", + "x-stainless-const": true + }, + "input_tokens": { + "type": "integer", + "description": "Number of input tokens billed for this request." + }, + "input_token_details": { + "type": "object", + "description": "Details about the input tokens billed for this request.", + "properties": { + "text_tokens": { + "type": "integer", + "description": "Number of text tokens billed for this request." + }, + "audio_tokens": { + "type": "integer", + "description": "Number of audio tokens billed for this request." + } + } + }, + "output_tokens": { + "type": "integer", + "description": "Number of output tokens generated." + }, + "total_tokens": { + "type": "integer", + "description": "Total number of tokens used (input + output)." + } + }, + "required": [ + "type", + "input_tokens", + "output_tokens", + "total_tokens" + ] + }, + "TranscriptionChunkingStrategy": { + "description": "Controls how the audio is cut into chunks. When set to `\"auto\"`, the server first normalizes loudness and then uses voice activity detection (VAD) to choose boundaries. `server_vad` object can be provided to tweak VAD detection parameters manually. If unset, the audio is transcribed as a single block.", + "anyOf": [ + { + "type": "string", + "enum": [ + "auto" + ], + "description": "Automatically set chunking parameters based on the audio. Must be set to `\"auto\"`.\n", + "x-stainless-const": true + }, + { + "$ref": "#/components/schemas/VadConfig" + } + ], + "nullable": true, + "x-oaiTypeLabel": "string" + }, + "TranscriptionInclude": { + "type": "string", + "enum": [ + "logprobs" + ] + }, + "TranscriptionSegment": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "description": "Unique identifier of the segment." + }, + "seek": { + "type": "integer", + "description": "Seek offset of the segment." + }, + "start": { + "type": "number", + "format": "float", + "description": "Start time of the segment in seconds." + }, + "end": { + "type": "number", + "format": "float", + "description": "End time of the segment in seconds." + }, + "text": { + "type": "string", + "description": "Text content of the segment." + }, + "tokens": { + "type": "array", + "items": { + "type": "integer" + }, + "description": "Array of token IDs for the text content." + }, + "temperature": { + "type": "number", + "format": "float", + "description": "Temperature parameter used for generating the segment." + }, + "avg_logprob": { + "type": "number", + "format": "float", + "description": "Average logprob of the segment. If the value is lower than -1, consider the logprobs failed." + }, + "compression_ratio": { + "type": "number", + "format": "float", + "description": "Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed." + }, + "no_speech_prob": { + "type": "number", + "format": "float", + "description": "Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent." + } + }, + "required": [ + "id", + "seek", + "start", + "end", + "text", + "tokens", + "temperature", + "avg_logprob", + "compression_ratio", + "no_speech_prob" + ] + }, + "TranscriptionWord": { + "type": "object", + "properties": { + "word": { + "type": "string", + "description": "The text content of the word." + }, + "start": { + "type": "number", + "format": "float", + "description": "Start time of the word in seconds." + }, + "end": { + "type": "number", + "format": "float", + "description": "End time of the word in seconds." + } + }, + "required": [ + "word", + "start", + "end" + ] + }, + "TruncationObject": { + "type": "object", + "title": "Thread Truncation Controls", + "description": "Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run.", + "properties": { + "type": { + "type": "string", + "description": "The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`.", + "enum": [ + "auto", + "last_messages" + ] + }, + "last_messages": { + "type": "integer", + "description": "The number of most recent messages from the thread when constructing the context for the run.", + "minimum": 1, + "nullable": true + } + }, + "required": [ + "type" + ] + }, + "Type": { + "type": "object", + "title": "Type", + "description": "An action to type in text.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "type" + ], + "default": "type", + "description": "Specifies the event type. For a type action, this property is \nalways set to `type`.\n", + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text to type.\n" + } + }, + "required": [ + "type", + "text" + ] + }, + "UpdateVectorStoreFileAttributesRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "attributes": { + "$ref": "#/components/schemas/VectorStoreFileAttributes" + } + }, + "required": [ + "attributes" + ], + "x-oaiMeta": { + "name": "Update vector store file attributes request" + } + }, + "UpdateVectorStoreRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "description": "The name of the vector store.", + "type": "string", + "nullable": true + }, + "expires_after": { + "allOf": [ + { + "$ref": "#/components/schemas/VectorStoreExpirationAfter" + }, + { + "nullable": true + } + ] + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + } + }, + "Upload": { + "type": "object", + "title": "Upload", + "description": "The Upload object can accept byte chunks in the form of Parts.\n", + "properties": { + "id": { + "type": "string", + "description": "The Upload unique identifier, which can be referenced in API endpoints." + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the Upload was created." + }, + "filename": { + "type": "string", + "description": "The name of the file to be uploaded." + }, + "bytes": { + "type": "integer", + "description": "The intended number of bytes to be uploaded." + }, + "purpose": { + "type": "string", + "description": "The intended purpose of the file. [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) for acceptable values." + }, + "status": { + "type": "string", + "description": "The status of the Upload.", + "enum": [ + "pending", + "completed", + "cancelled", + "expired" + ] + }, + "expires_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the Upload will expire." + }, + "object": { + "type": "string", + "description": "The object type, which is always \"upload\".", + "enum": [ + "upload" + ], + "x-stainless-const": true + }, + "file": { + "allOf": [ + { + "$ref": "#/components/schemas/OpenAIFile" + }, + { + "nullable": true, + "description": "The ready File object after the Upload is completed." + } + ] + } + }, + "required": [ + "bytes", + "created_at", + "expires_at", + "filename", + "id", + "purpose", + "status", + "object" + ], + "x-oaiMeta": { + "name": "The upload object", + "example": "{\n \"id\": \"upload_abc123\",\n \"object\": \"upload\",\n \"bytes\": 2147483648,\n \"created_at\": 1719184911,\n \"filename\": \"training_examples.jsonl\",\n \"purpose\": \"fine-tune\",\n \"status\": \"completed\",\n \"expires_at\": 1719127296,\n \"file\": {\n \"id\": \"file-xyz321\",\n \"object\": \"file\",\n \"bytes\": 2147483648,\n \"created_at\": 1719186911,\n \"filename\": \"training_examples.jsonl\",\n \"purpose\": \"fine-tune\",\n }\n}\n" + } + }, + "UploadCertificateRequest": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "An optional name for the certificate" + }, + "content": { + "type": "string", + "description": "The certificate content in PEM format" + } + }, + "required": [ + "content" + ] + }, + "UploadPart": { + "type": "object", + "title": "UploadPart", + "description": "The upload Part represents a chunk of bytes we can add to an Upload object.\n", + "properties": { + "id": { + "type": "string", + "description": "The upload Part unique identifier, which can be referenced in API endpoints." + }, + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) for when the Part was created." + }, + "upload_id": { + "type": "string", + "description": "The ID of the Upload object that this Part was added to." + }, + "object": { + "type": "string", + "description": "The object type, which is always `upload.part`.", + "enum": [ + "upload.part" + ], + "x-stainless-const": true + } + }, + "required": [ + "created_at", + "id", + "object", + "upload_id" + ], + "x-oaiMeta": { + "name": "The upload part object", + "example": "{\n \"id\": \"part_def456\",\n \"object\": \"upload.part\",\n \"created_at\": 1719186911,\n \"upload_id\": \"upload_abc123\"\n}\n" + } + }, + "UsageAudioSpeechesResult": { + "type": "object", + "description": "The aggregated audio speeches usage details of the specific time bucket.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.usage.audio_speeches.result" + ], + "x-stainless-const": true + }, + "characters": { + "type": "integer", + "description": "The number of characters processed." + }, + "num_model_requests": { + "type": "integer", + "description": "The count of requests made to the model." + }, + "project_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }, + "user_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }, + "api_key_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }, + "model": { + "type": "string", + "nullable": true, + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + } + }, + "required": [ + "object", + "characters", + "num_model_requests" + ], + "x-oaiMeta": { + "name": "Audio speeches usage object", + "example": "{\n \"object\": \"organization.usage.audio_speeches.result\",\n \"characters\": 45,\n \"num_model_requests\": 1,\n \"project_id\": \"proj_abc\",\n \"user_id\": \"user-abc\",\n \"api_key_id\": \"key_abc\",\n \"model\": \"tts-1\"\n}\n" + } + }, + "UsageAudioTranscriptionsResult": { + "type": "object", + "description": "The aggregated audio transcriptions usage details of the specific time bucket.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.usage.audio_transcriptions.result" + ], + "x-stainless-const": true + }, + "seconds": { + "type": "integer", + "description": "The number of seconds processed." + }, + "num_model_requests": { + "type": "integer", + "description": "The count of requests made to the model." + }, + "project_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }, + "user_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }, + "api_key_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }, + "model": { + "type": "string", + "nullable": true, + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + } + }, + "required": [ + "object", + "seconds", + "num_model_requests" + ], + "x-oaiMeta": { + "name": "Audio transcriptions usage object", + "example": "{\n \"object\": \"organization.usage.audio_transcriptions.result\",\n \"seconds\": 10,\n \"num_model_requests\": 1,\n \"project_id\": \"proj_abc\",\n \"user_id\": \"user-abc\",\n \"api_key_id\": \"key_abc\",\n \"model\": \"tts-1\"\n}\n" + } + }, + "UsageCodeInterpreterSessionsResult": { + "type": "object", + "description": "The aggregated code interpreter sessions usage details of the specific time bucket.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.usage.code_interpreter_sessions.result" + ], + "x-stainless-const": true + }, + "num_sessions": { + "type": "integer", + "description": "The number of code interpreter sessions." + }, + "project_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + } + }, + "required": [ + "object", + "sessions" + ], + "x-oaiMeta": { + "name": "Code interpreter sessions usage object", + "example": "{\n \"object\": \"organization.usage.code_interpreter_sessions.result\",\n \"num_sessions\": 1,\n \"project_id\": \"proj_abc\"\n}\n" + } + }, + "UsageCompletionsResult": { + "type": "object", + "description": "The aggregated completions usage details of the specific time bucket.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.usage.completions.result" + ], + "x-stainless-const": true + }, + "input_tokens": { + "type": "integer", + "description": "The aggregated number of text input tokens used, including cached tokens. For customers subscribe to scale tier, this includes scale tier tokens." + }, + "input_cached_tokens": { + "type": "integer", + "description": "The aggregated number of text input tokens that has been cached from previous requests. For customers subscribe to scale tier, this includes scale tier tokens." + }, + "output_tokens": { + "type": "integer", + "description": "The aggregated number of text output tokens used. For customers subscribe to scale tier, this includes scale tier tokens." + }, + "input_audio_tokens": { + "type": "integer", + "description": "The aggregated number of audio input tokens used, including cached tokens." + }, + "output_audio_tokens": { + "type": "integer", + "description": "The aggregated number of audio output tokens used." + }, + "num_model_requests": { + "type": "integer", + "description": "The count of requests made to the model." + }, + "project_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }, + "user_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }, + "api_key_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }, + "model": { + "type": "string", + "nullable": true, + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + }, + "batch": { + "type": "boolean", + "nullable": true, + "description": "When `group_by=batch`, this field tells whether the grouped usage result is batch or not." + } + }, + "required": [ + "object", + "input_tokens", + "output_tokens", + "num_model_requests" + ], + "x-oaiMeta": { + "name": "Completions usage object", + "example": "{\n \"object\": \"organization.usage.completions.result\",\n \"input_tokens\": 5000,\n \"output_tokens\": 1000,\n \"input_cached_tokens\": 4000,\n \"input_audio_tokens\": 300,\n \"output_audio_tokens\": 200,\n \"num_model_requests\": 5,\n \"project_id\": \"proj_abc\",\n \"user_id\": \"user-abc\",\n \"api_key_id\": \"key_abc\",\n \"model\": \"gpt-4o-mini-2024-07-18\",\n \"batch\": false\n}\n" + } + }, + "UsageEmbeddingsResult": { + "type": "object", + "description": "The aggregated embeddings usage details of the specific time bucket.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.usage.embeddings.result" + ], + "x-stainless-const": true + }, + "input_tokens": { + "type": "integer", + "description": "The aggregated number of input tokens used." + }, + "num_model_requests": { + "type": "integer", + "description": "The count of requests made to the model." + }, + "project_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }, + "user_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }, + "api_key_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }, + "model": { + "type": "string", + "nullable": true, + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + } + }, + "required": [ + "object", + "input_tokens", + "num_model_requests" + ], + "x-oaiMeta": { + "name": "Embeddings usage object", + "example": "{\n \"object\": \"organization.usage.embeddings.result\",\n \"input_tokens\": 20,\n \"num_model_requests\": 2,\n \"project_id\": \"proj_abc\",\n \"user_id\": \"user-abc\",\n \"api_key_id\": \"key_abc\",\n \"model\": \"text-embedding-ada-002-v2\"\n}\n" + } + }, + "UsageImagesResult": { + "type": "object", + "description": "The aggregated images usage details of the specific time bucket.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.usage.images.result" + ], + "x-stainless-const": true + }, + "images": { + "type": "integer", + "description": "The number of images processed." + }, + "num_model_requests": { + "type": "integer", + "description": "The count of requests made to the model." + }, + "source": { + "type": "string", + "nullable": true, + "description": "When `group_by=source`, this field provides the source of the grouped usage result, possible values are `image.generation`, `image.edit`, `image.variation`." + }, + "size": { + "type": "string", + "nullable": true, + "description": "When `group_by=size`, this field provides the image size of the grouped usage result." + }, + "project_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }, + "user_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }, + "api_key_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }, + "model": { + "type": "string", + "nullable": true, + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + } + }, + "required": [ + "object", + "images", + "num_model_requests" + ], + "x-oaiMeta": { + "name": "Images usage object", + "example": "{\n \"object\": \"organization.usage.images.result\",\n \"images\": 2,\n \"num_model_requests\": 2,\n \"size\": \"1024x1024\",\n \"source\": \"image.generation\",\n \"project_id\": \"proj_abc\",\n \"user_id\": \"user-abc\",\n \"api_key_id\": \"key_abc\",\n \"model\": \"dall-e-3\"\n}\n" + } + }, + "UsageModerationsResult": { + "type": "object", + "description": "The aggregated moderations usage details of the specific time bucket.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.usage.moderations.result" + ], + "x-stainless-const": true + }, + "input_tokens": { + "type": "integer", + "description": "The aggregated number of input tokens used." + }, + "num_model_requests": { + "type": "integer", + "description": "The count of requests made to the model." + }, + "project_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }, + "user_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }, + "api_key_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }, + "model": { + "type": "string", + "nullable": true, + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + } + }, + "required": [ + "object", + "input_tokens", + "num_model_requests" + ], + "x-oaiMeta": { + "name": "Moderations usage object", + "example": "{\n \"object\": \"organization.usage.moderations.result\",\n \"input_tokens\": 20,\n \"num_model_requests\": 2,\n \"project_id\": \"proj_abc\",\n \"user_id\": \"user-abc\",\n \"api_key_id\": \"key_abc\",\n \"model\": \"text-moderation\"\n}\n" + } + }, + "UsageResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "page" + ], + "x-stainless-const": true + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UsageTimeBucket" + } + }, + "has_more": { + "type": "boolean" + }, + "next_page": { + "type": "string" + } + }, + "required": [ + "object", + "data", + "has_more", + "next_page" + ] + }, + "UsageTimeBucket": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "bucket" + ], + "x-stainless-const": true + }, + "start_time": { + "type": "integer" + }, + "end_time": { + "type": "integer" + }, + "result": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/UsageCompletionsResult" + }, + { + "$ref": "#/components/schemas/UsageEmbeddingsResult" + }, + { + "$ref": "#/components/schemas/UsageModerationsResult" + }, + { + "$ref": "#/components/schemas/UsageImagesResult" + }, + { + "$ref": "#/components/schemas/UsageAudioSpeechesResult" + }, + { + "$ref": "#/components/schemas/UsageAudioTranscriptionsResult" + }, + { + "$ref": "#/components/schemas/UsageVectorStoresResult" + }, + { + "$ref": "#/components/schemas/UsageCodeInterpreterSessionsResult" + }, + { + "$ref": "#/components/schemas/CostsResult" + } + ], + "discriminator": { + "propertyName": "object" + } + } + } + }, + "required": [ + "object", + "start_time", + "end_time", + "result" + ] + }, + "UsageVectorStoresResult": { + "type": "object", + "description": "The aggregated vector stores usage details of the specific time bucket.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.usage.vector_stores.result" + ], + "x-stainless-const": true + }, + "usage_bytes": { + "type": "integer", + "description": "The vector stores usage in bytes." + }, + "project_id": { + "type": "string", + "nullable": true, + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + } + }, + "required": [ + "object", + "usage_bytes" + ], + "x-oaiMeta": { + "name": "Vector stores usage object", + "example": "{\n \"object\": \"organization.usage.vector_stores.result\",\n \"usage_bytes\": 1024,\n \"project_id\": \"proj_abc\"\n}\n" + } + }, + "User": { + "type": "object", + "description": "Represents an individual `user` within an organization.", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.user" + ], + "description": "The object type, which is always `organization.user`", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The identifier, which can be referenced in API endpoints" + }, + "name": { + "type": "string", + "description": "The name of the user" + }, + "email": { + "type": "string", + "description": "The email address of the user" + }, + "role": { + "type": "string", + "enum": [ + "owner", + "reader" + ], + "description": "`owner` or `reader`" + }, + "added_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the user was added." + } + }, + "required": [ + "object", + "id", + "name", + "email", + "role", + "added_at" + ], + "x-oaiMeta": { + "name": "The user object", + "example": "{\n \"object\": \"organization.user\",\n \"id\": \"user_abc\",\n \"name\": \"First Last\",\n \"email\": \"user@example.com\",\n \"role\": \"owner\",\n \"added_at\": 1711471533\n}\n" + } + }, + "UserDeleteResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "organization.user.deleted" + ], + "x-stainless-const": true + }, + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean" + } + }, + "required": [ + "object", + "id", + "deleted" + ] + }, + "UserListResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "enum": [ + "list" + ], + "x-stainless-const": true + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/User" + } + }, + "first_id": { + "type": "string" + }, + "last_id": { + "type": "string" + }, + "has_more": { + "type": "boolean" + } + }, + "required": [ + "object", + "data", + "first_id", + "last_id", + "has_more" + ] + }, + "UserRoleUpdateRequest": { + "type": "object", + "properties": { + "role": { + "type": "string", + "enum": [ + "owner", + "reader" + ], + "description": "`owner` or `reader`" + } + }, + "required": [ + "role" + ] + }, + "VadConfig": { + "type": "object", + "additionalProperties": false, + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "server_vad" + ], + "description": "Must be set to `server_vad` to enable manual chunking using server side VAD." + }, + "prefix_padding_ms": { + "type": "integer", + "default": 300, + "description": "Amount of audio to include before the VAD detected speech (in \nmilliseconds).\n" + }, + "silence_duration_ms": { + "type": "integer", + "default": 200, + "description": "Duration of silence to detect speech stop (in milliseconds).\nWith shorter values the model will respond more quickly, \nbut may jump in on short pauses from the user.\n" + }, + "threshold": { + "type": "number", + "default": 0.5, + "description": "Sensitivity threshold (0.0 to 1.0) for voice activity detection. A \nhigher threshold will require louder audio to activate the model, and \nthus might perform better in noisy environments.\n" + } + } + }, + "ValidateGraderRequest": { + "type": "object", + "title": "ValidateGraderRequest", + "properties": { + "grader": { + "type": "object", + "description": "The grader used for the fine-tuning job.", + "anyOf": [ + { + "$ref": "#/components/schemas/GraderStringCheck" + }, + { + "$ref": "#/components/schemas/GraderTextSimilarity" + }, + { + "$ref": "#/components/schemas/GraderPython" + }, + { + "$ref": "#/components/schemas/GraderScoreModel" + }, + { + "$ref": "#/components/schemas/GraderMulti" + } + ] + } + }, + "required": [ + "grader" + ] + }, + "ValidateGraderResponse": { + "type": "object", + "title": "ValidateGraderResponse", + "properties": { + "grader": { + "type": "object", + "description": "The grader used for the fine-tuning job.", + "anyOf": [ + { + "$ref": "#/components/schemas/GraderStringCheck" + }, + { + "$ref": "#/components/schemas/GraderTextSimilarity" + }, + { + "$ref": "#/components/schemas/GraderPython" + }, + { + "$ref": "#/components/schemas/GraderScoreModel" + }, + { + "$ref": "#/components/schemas/GraderMulti" + } + ] + } + } + }, + "VectorStoreExpirationAfter": { + "type": "object", + "title": "Vector store expiration policy", + "description": "The expiration policy for a vector store.", + "properties": { + "anchor": { + "description": "Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`.", + "type": "string", + "enum": [ + "last_active_at" + ], + "x-stainless-const": true + }, + "days": { + "description": "The number of days after the anchor time that the vector store will expire.", + "type": "integer", + "minimum": 1, + "maximum": 365 + } + }, + "required": [ + "anchor", + "days" + ] + }, + "VectorStoreFileAttributes": { + "type": "object", + "description": "Set of 16 key-value pairs that can be attached to an object. This can be \nuseful for storing additional information about the object in a structured \nformat, and querying for objects via API or the dashboard. Keys are strings \nwith a maximum length of 64 characters. Values are strings with a maximum \nlength of 512 characters, booleans, or numbers.\n", + "maxProperties": 16, + "propertyNames": { + "type": "string", + "maxLength": 64 + }, + "additionalProperties": { + "anyOf": [ + { + "type": "string", + "maxLength": 512 + }, + { + "type": "number" + }, + { + "type": "boolean" + } + ] + }, + "x-oaiTypeLabel": "map", + "nullable": true + }, + "VectorStoreFileBatchObject": { + "type": "object", + "title": "Vector store file batch", + "description": "A batch of files attached to a vector store.", + "properties": { + "id": { + "description": "The identifier, which can be referenced in API endpoints.", + "type": "string" + }, + "object": { + "description": "The object type, which is always `vector_store.file_batch`.", + "type": "string", + "enum": [ + "vector_store.files_batch" + ], + "x-stainless-const": true + }, + "created_at": { + "description": "The Unix timestamp (in seconds) for when the vector store files batch was created.", + "type": "integer" + }, + "vector_store_id": { + "description": "The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to.", + "type": "string" + }, + "status": { + "description": "The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`.", + "type": "string", + "enum": [ + "in_progress", + "completed", + "cancelled", + "failed" + ] + }, + "file_counts": { + "type": "object", + "properties": { + "in_progress": { + "description": "The number of files that are currently being processed.", + "type": "integer" + }, + "completed": { + "description": "The number of files that have been processed.", + "type": "integer" + }, + "failed": { + "description": "The number of files that have failed to process.", + "type": "integer" + }, + "cancelled": { + "description": "The number of files that where cancelled.", + "type": "integer" + }, + "total": { + "description": "The total number of files.", + "type": "integer" + } + }, + "required": [ + "in_progress", + "completed", + "cancelled", + "failed", + "total" + ] + } + }, + "required": [ + "id", + "object", + "created_at", + "vector_store_id", + "status", + "file_counts" + ], + "x-oaiMeta": { + "name": "The vector store files batch object", + "beta": true, + "example": "{\n \"id\": \"vsfb_123\",\n \"object\": \"vector_store.files_batch\",\n \"created_at\": 1698107661,\n \"vector_store_id\": \"vs_abc123\",\n \"status\": \"completed\",\n \"file_counts\": {\n \"in_progress\": 0,\n \"completed\": 100,\n \"failed\": 0,\n \"cancelled\": 0,\n \"total\": 100\n }\n}\n" + } + }, + "VectorStoreFileContentResponse": { + "type": "object", + "description": "Represents the parsed content of a vector store file.", + "properties": { + "object": { + "type": "string", + "enum": [ + "vector_store.file_content.page" + ], + "description": "The object type, which is always `vector_store.file_content.page`", + "x-stainless-const": true + }, + "data": { + "type": "array", + "description": "Parsed content of the file.", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "The content type (currently only `\"text\"`)" + }, + "text": { + "type": "string", + "description": "The text content" + } + } + } + }, + "has_more": { + "type": "boolean", + "description": "Indicates if there are more content pages to fetch." + }, + "next_page": { + "type": "string", + "description": "The token for the next page, if any.", + "nullable": true + } + }, + "required": [ + "object", + "data", + "has_more", + "next_page" + ] + }, + "VectorStoreFileObject": { + "type": "object", + "title": "Vector store files", + "description": "A list of files attached to a vector store.", + "properties": { + "id": { + "description": "The identifier, which can be referenced in API endpoints.", + "type": "string" + }, + "object": { + "description": "The object type, which is always `vector_store.file`.", + "type": "string", + "enum": [ + "vector_store.file" + ], + "x-stainless-const": true + }, + "usage_bytes": { + "description": "The total vector store usage in bytes. Note that this may be different from the original file size.", + "type": "integer" + }, + "created_at": { + "description": "The Unix timestamp (in seconds) for when the vector store file was created.", + "type": "integer" + }, + "vector_store_id": { + "description": "The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to.", + "type": "string" + }, + "status": { + "description": "The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use.", + "type": "string", + "enum": [ + "in_progress", + "completed", + "cancelled", + "failed" + ] + }, + "last_error": { + "type": "object", + "description": "The last error associated with this vector store file. Will be `null` if there are no errors.", + "nullable": true, + "properties": { + "code": { + "type": "string", + "description": "One of `server_error` or `rate_limit_exceeded`.", + "enum": [ + "server_error", + "unsupported_file", + "invalid_file" + ] + }, + "message": { + "type": "string", + "description": "A human-readable description of the error." + } + }, + "required": [ + "code", + "message" + ] + }, + "chunking_strategy": { + "$ref": "#/components/schemas/ChunkingStrategyResponse" + }, + "attributes": { + "$ref": "#/components/schemas/VectorStoreFileAttributes" + } + }, + "required": [ + "id", + "object", + "usage_bytes", + "created_at", + "vector_store_id", + "status", + "last_error" + ], + "x-oaiMeta": { + "name": "The vector store file object", + "beta": true, + "example": "{\n \"id\": \"file-abc123\",\n \"object\": \"vector_store.file\",\n \"usage_bytes\": 1234,\n \"created_at\": 1698107661,\n \"vector_store_id\": \"vs_abc123\",\n \"status\": \"completed\",\n \"last_error\": null,\n \"chunking_strategy\": {\n \"type\": \"static\",\n \"static\": {\n \"max_chunk_size_tokens\": 800,\n \"chunk_overlap_tokens\": 400\n }\n }\n}\n" + } + }, + "VectorStoreObject": { + "type": "object", + "title": "Vector store", + "description": "A vector store is a collection of processed files can be used by the `file_search` tool.", + "properties": { + "id": { + "description": "The identifier, which can be referenced in API endpoints.", + "type": "string" + }, + "object": { + "description": "The object type, which is always `vector_store`.", + "type": "string", + "enum": [ + "vector_store" + ], + "x-stainless-const": true + }, + "created_at": { + "description": "The Unix timestamp (in seconds) for when the vector store was created.", + "type": "integer" + }, + "name": { + "description": "The name of the vector store.", + "type": "string" + }, + "usage_bytes": { + "description": "The total number of bytes used by the files in the vector store.", + "type": "integer" + }, + "file_counts": { + "type": "object", + "properties": { + "in_progress": { + "description": "The number of files that are currently being processed.", + "type": "integer" + }, + "completed": { + "description": "The number of files that have been successfully processed.", + "type": "integer" + }, + "failed": { + "description": "The number of files that have failed to process.", + "type": "integer" + }, + "cancelled": { + "description": "The number of files that were cancelled.", + "type": "integer" + }, + "total": { + "description": "The total number of files.", + "type": "integer" + } + }, + "required": [ + "in_progress", + "completed", + "failed", + "cancelled", + "total" + ] + }, + "status": { + "description": "The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use.", + "type": "string", + "enum": [ + "expired", + "in_progress", + "completed" + ] + }, + "expires_after": { + "$ref": "#/components/schemas/VectorStoreExpirationAfter" + }, + "expires_at": { + "description": "The Unix timestamp (in seconds) for when the vector store will expire.", + "type": "integer", + "nullable": true + }, + "last_active_at": { + "description": "The Unix timestamp (in seconds) for when the vector store was last active.", + "type": "integer", + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + } + }, + "required": [ + "id", + "object", + "usage_bytes", + "created_at", + "status", + "last_active_at", + "name", + "file_counts", + "metadata" + ], + "x-oaiMeta": { + "name": "The vector store object", + "example": "{\n \"id\": \"vs_123\",\n \"object\": \"vector_store\",\n \"created_at\": 1698107661,\n \"usage_bytes\": 123456,\n \"last_active_at\": 1698107661,\n \"name\": \"my_vector_store\",\n \"status\": \"completed\",\n \"file_counts\": {\n \"in_progress\": 0,\n \"completed\": 100,\n \"cancelled\": 0,\n \"failed\": 0,\n \"total\": 100\n },\n \"last_used_at\": 1698107661\n}\n" + } + }, + "VectorStoreSearchRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "query": { + "description": "A query string for a search", + "anyOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string", + "description": "A list of queries to search for.", + "minItems": 1 + } + } + ] + }, + "rewrite_query": { + "description": "Whether to rewrite the natural language query for vector search.", + "type": "boolean", + "default": false + }, + "max_num_results": { + "description": "The maximum number of results to return. This number should be between 1 and 50 inclusive.", + "type": "integer", + "default": 10, + "minimum": 1, + "maximum": 50 + }, + "filters": { + "description": "A filter to apply based on file attributes.", + "anyOf": [ + { + "$ref": "#/components/schemas/ComparisonFilter" + }, + { + "$ref": "#/components/schemas/CompoundFilter" + } + ] + }, + "ranking_options": { + "description": "Ranking options for search.", + "type": "object", + "additionalProperties": false, + "properties": { + "ranker": { + "description": "Enable re-ranking; set to `none` to disable, which can help reduce latency.", + "type": "string", + "enum": [ + "none", + "auto", + "default-2024-11-15" + ], + "default": "auto" + }, + "score_threshold": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 0 + } + } + } + }, + "required": [ + "query" + ], + "x-oaiMeta": { + "name": "Vector store search request" + } + }, + "VectorStoreSearchResultContentObject": { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "description": "The type of content.", + "type": "string", + "enum": [ + "text" + ] + }, + "text": { + "description": "The text content returned from search.", + "type": "string" + } + }, + "required": [ + "type", + "text" + ], + "x-oaiMeta": { + "name": "Vector store search result content object" + } + }, + "VectorStoreSearchResultItem": { + "type": "object", + "additionalProperties": false, + "properties": { + "file_id": { + "type": "string", + "description": "The ID of the vector store file." + }, + "filename": { + "type": "string", + "description": "The name of the vector store file." + }, + "score": { + "type": "number", + "description": "The similarity score for the result.", + "minimum": 0, + "maximum": 1 + }, + "attributes": { + "$ref": "#/components/schemas/VectorStoreFileAttributes" + }, + "content": { + "type": "array", + "description": "Content chunks from the file.", + "items": { + "$ref": "#/components/schemas/VectorStoreSearchResultContentObject" + } + } + }, + "required": [ + "file_id", + "filename", + "score", + "attributes", + "content" + ], + "x-oaiMeta": { + "name": "Vector store search result item" + } + }, + "VectorStoreSearchResultsPage": { + "type": "object", + "additionalProperties": false, + "properties": { + "object": { + "type": "string", + "enum": [ + "vector_store.search_results.page" + ], + "description": "The object type, which is always `vector_store.search_results.page`", + "x-stainless-const": true + }, + "search_query": { + "type": "array", + "items": { + "type": "string", + "description": "The query used for this search.", + "minItems": 1 + } + }, + "data": { + "type": "array", + "description": "The list of search result items.", + "items": { + "$ref": "#/components/schemas/VectorStoreSearchResultItem" + } + }, + "has_more": { + "type": "boolean", + "description": "Indicates if there are more results to fetch." + }, + "next_page": { + "type": "string", + "description": "The token for the next page, if any.", + "nullable": true + } + }, + "required": [ + "object", + "search_query", + "data", + "has_more", + "next_page" + ], + "x-oaiMeta": { + "name": "Vector store search results page" + } + }, + "Verbosity": { + "type": "string", + "enum": [ + "low", + "medium", + "high" + ], + "default": "medium", + "nullable": true, + "description": "Constrains the verbosity of the model's response. Lower values will result in\nmore concise responses, while higher values will result in more verbose responses.\nCurrently supported values are `low`, `medium`, and `high`.\n" + }, + "VoiceIdsShared": { + "example": "ash", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "alloy", + "ash", + "ballad", + "coral", + "echo", + "sage", + "shimmer", + "verse", + "marin", + "cedar" + ] + } + ] + }, + "Wait": { + "type": "object", + "title": "Wait", + "description": "A wait action.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "wait" + ], + "default": "wait", + "description": "Specifies the event type. For a wait action, this property is \nalways set to `wait`.\n", + "x-stainless-const": true + } + }, + "required": [ + "type" + ] + }, + "WebSearchActionFind": { + "type": "object", + "title": "Find action", + "description": "Action type \"find\": Searches for a pattern within a loaded page.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "find" + ], + "description": "The action type.\n", + "x-stainless-const": true + }, + "url": { + "type": "string", + "format": "uri", + "description": "The URL of the page searched for the pattern.\n" + }, + "pattern": { + "type": "string", + "description": "The pattern or text to search for within the page.\n" + } + }, + "required": [ + "type", + "url", + "pattern" + ] + }, + "WebSearchActionOpenPage": { + "type": "object", + "title": "Open page action", + "description": "Action type \"open_page\" - Opens a specific URL from search results.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "open_page" + ], + "description": "The action type.\n", + "x-stainless-const": true + }, + "url": { + "type": "string", + "format": "uri", + "description": "The URL opened by the model.\n" + } + }, + "required": [ + "type", + "url" + ] + }, + "WebSearchActionSearch": { + "type": "object", + "title": "Search action", + "description": "Action type \"search\" - Performs a web search query.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "search" + ], + "description": "The action type.\n", + "x-stainless-const": true + }, + "query": { + "type": "string", + "description": "The search query.\n" + }, + "sources": { + "type": "array", + "title": "Web search sources", + "description": "The sources used in the search.\n", + "items": { + "type": "object", + "title": "Web search source", + "description": "A source used in the search.\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "url" + ], + "description": "The type of source. Always `url`.\n", + "x-stainless-const": true + }, + "url": { + "type": "string", + "description": "The URL of the source.\n" + } + }, + "required": [ + "type", + "url" + ] + } + } + }, + "required": [ + "type", + "query" + ] + }, + "WebSearchApproximateLocation": { + "type": "object", + "title": "Web search approximate location", + "description": "The approximate location of the user.\n", + "nullable": true, + "properties": { + "type": { + "type": "string", + "enum": [ + "approximate" + ], + "description": "The type of location approximation. Always `approximate`.", + "default": "approximate", + "x-stainless-const": true + }, + "country": { + "type": "string", + "description": "The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`.", + "nullable": true + }, + "region": { + "type": "string", + "description": "Free text input for the region of the user, e.g. `California`.", + "nullable": true + }, + "city": { + "type": "string", + "description": "Free text input for the city of the user, e.g. `San Francisco`.", + "nullable": true + }, + "timezone": { + "type": "string", + "description": "The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`.", + "nullable": true + } + } + }, + "WebSearchContextSize": { + "type": "string", + "description": "High level guidance for the amount of context window space to use for the \nsearch. One of `low`, `medium`, or `high`. `medium` is the default.\n", + "enum": [ + "low", + "medium", + "high" + ], + "default": "medium" + }, + "WebSearchLocation": { + "type": "object", + "title": "Web search location", + "description": "Approximate location parameters for the search.", + "properties": { + "country": { + "type": "string", + "description": "The two-letter \n[ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user,\ne.g. `US`.\n" + }, + "region": { + "type": "string", + "description": "Free text input for the region of the user, e.g. `California`.\n" + }, + "city": { + "type": "string", + "description": "Free text input for the city of the user, e.g. `San Francisco`.\n" + }, + "timezone": { + "type": "string", + "description": "The [IANA timezone](https://timeapi.io/documentation/iana-timezones) \nof the user, e.g. `America/Los_Angeles`.\n" + } + } + }, + "WebSearchTool": { + "type": "object", + "title": "Web search", + "description": "Search the Internet for sources related to the prompt. Learn more about the \n[web search tool](https://platform.openai.com/docs/guides/tools-web-search).\n", + "properties": { + "type": { + "type": "string", + "enum": [ + "web_search", + "web_search_2025_08_26" + ], + "description": "The type of the web search tool. One of `web_search` or `web_search_2025_08_26`.", + "default": "web_search" + }, + "filters": { + "type": "object", + "description": "Filters for the search.\n", + "nullable": true, + "properties": { + "allowed_domains": { + "type": "array", + "title": "Allowed domains for the search.", + "description": "Allowed domains for the search. If not provided, all domains are allowed.\nSubdomains of the provided domains are allowed as well.\n\nExample: `[\"pubmed.ncbi.nlm.nih.gov\"]`\n", + "items": { + "type": "string", + "description": "Allowed domain for the search." + }, + "default": [], + "nullable": true + } + } + }, + "user_location": { + "$ref": "#/components/schemas/WebSearchApproximateLocation" + }, + "search_context_size": { + "type": "string", + "enum": [ + "low", + "medium", + "high" + ], + "default": "medium", + "description": "High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default." + } + }, + "required": [ + "type" + ] + }, + "WebSearchToolCall": { + "type": "object", + "title": "Web search tool call", + "description": "The results of a web search tool call. See the \n[web search guide](https://platform.openai.com/docs/guides/tools-web-search) for more information.\n", + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the web search tool call.\n" + }, + "type": { + "type": "string", + "enum": [ + "web_search_call" + ], + "description": "The type of the web search tool call. Always `web_search_call`.\n", + "x-stainless-const": true + }, + "status": { + "type": "string", + "description": "The status of the web search tool call.\n", + "enum": [ + "in_progress", + "searching", + "completed", + "failed" + ] + }, + "action": { + "type": "object", + "description": "An object describing the specific action taken in this web search call.\nIncludes details on how the model used the web (search, open_page, find).\n", + "anyOf": [ + { + "$ref": "#/components/schemas/WebSearchActionSearch" + }, + { + "$ref": "#/components/schemas/WebSearchActionOpenPage" + }, + { + "$ref": "#/components/schemas/WebSearchActionFind" + } + ], + "discriminator": { + "propertyName": "type" + } + } + }, + "required": [ + "id", + "type", + "status", + "action" + ] + }, + "WebhookBatchCancelled": { + "type": "object", + "title": "batch.cancelled", + "description": "Sent when a batch API request has been cancelled.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the batch API request was cancelled.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the batch API request.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `batch.cancelled`.\n", + "enum": [ + "batch.cancelled" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "batch.cancelled", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"batch.cancelled\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"batch_abc123\"\n }\n}\n" + } + }, + "WebhookBatchCompleted": { + "type": "object", + "title": "batch.completed", + "description": "Sent when a batch API request has been completed.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the batch API request was completed.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the batch API request.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `batch.completed`.\n", + "enum": [ + "batch.completed" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "batch.completed", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"batch.completed\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"batch_abc123\"\n }\n}\n" + } + }, + "WebhookBatchExpired": { + "type": "object", + "title": "batch.expired", + "description": "Sent when a batch API request has expired.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the batch API request expired.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the batch API request.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `batch.expired`.\n", + "enum": [ + "batch.expired" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "batch.expired", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"batch.expired\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"batch_abc123\"\n }\n}\n" + } + }, + "WebhookBatchFailed": { + "type": "object", + "title": "batch.failed", + "description": "Sent when a batch API request has failed.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the batch API request failed.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the batch API request.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `batch.failed`.\n", + "enum": [ + "batch.failed" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "batch.failed", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"batch.failed\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"batch_abc123\"\n }\n}\n" + } + }, + "WebhookEvalRunCanceled": { + "type": "object", + "title": "eval.run.canceled", + "description": "Sent when an eval run has been canceled.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the eval run was canceled.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the eval run.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `eval.run.canceled`.\n", + "enum": [ + "eval.run.canceled" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "eval.run.canceled", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"eval.run.canceled\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"evalrun_abc123\"\n }\n}\n" + } + }, + "WebhookEvalRunFailed": { + "type": "object", + "title": "eval.run.failed", + "description": "Sent when an eval run has failed.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the eval run failed.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the eval run.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `eval.run.failed`.\n", + "enum": [ + "eval.run.failed" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "eval.run.failed", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"eval.run.failed\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"evalrun_abc123\"\n }\n}\n" + } + }, + "WebhookEvalRunSucceeded": { + "type": "object", + "title": "eval.run.succeeded", + "description": "Sent when an eval run has succeeded.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the eval run succeeded.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the eval run.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `eval.run.succeeded`.\n", + "enum": [ + "eval.run.succeeded" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "eval.run.succeeded", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"eval.run.succeeded\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"evalrun_abc123\"\n }\n}\n" + } + }, + "WebhookFineTuningJobCancelled": { + "type": "object", + "title": "fine_tuning.job.cancelled", + "description": "Sent when a fine-tuning job has been cancelled.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the fine-tuning job was cancelled.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the fine-tuning job.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `fine_tuning.job.cancelled`.\n", + "enum": [ + "fine_tuning.job.cancelled" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "fine_tuning.job.cancelled", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"fine_tuning.job.cancelled\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"ftjob_abc123\"\n }\n}\n" + } + }, + "WebhookFineTuningJobFailed": { + "type": "object", + "title": "fine_tuning.job.failed", + "description": "Sent when a fine-tuning job has failed.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the fine-tuning job failed.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the fine-tuning job.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `fine_tuning.job.failed`.\n", + "enum": [ + "fine_tuning.job.failed" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "fine_tuning.job.failed", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"fine_tuning.job.failed\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"ftjob_abc123\"\n }\n}\n" + } + }, + "WebhookFineTuningJobSucceeded": { + "type": "object", + "title": "fine_tuning.job.succeeded", + "description": "Sent when a fine-tuning job has succeeded.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the fine-tuning job succeeded.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the fine-tuning job.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `fine_tuning.job.succeeded`.\n", + "enum": [ + "fine_tuning.job.succeeded" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "fine_tuning.job.succeeded", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"fine_tuning.job.succeeded\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"ftjob_abc123\"\n }\n}\n" + } + }, + "WebhookRealtimeCallIncoming": { + "type": "object", + "title": "realtime.call.incoming", + "description": "Sent when Realtime API Receives a incoming SIP call.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the model response was completed.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "call_id", + "sip_headers" + ], + "properties": { + "call_id": { + "type": "string", + "description": "The unique ID of this call.\n" + }, + "sip_headers": { + "type": "array", + "description": "Headers from the SIP Invite.\n", + "items": { + "type": "object", + "description": "A header from the SIP Invite.\n", + "required": [ + "name", + "value" + ], + "properties": { + "name": { + "type": "string", + "description": "Name of the SIP Header.\n" + }, + "value": { + "type": "string", + "description": "Value of the SIP Header.\n" + } + } + } + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `realtime.call.incoming`.\n", + "enum": [ + "realtime.call.incoming" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "realtime.call.incoming", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"realtime.call.incoming\",\n \"created_at\": 1719168000,\n \"data\": {\n \"call_id\": \"rtc_479a275623b54bdb9b6fbae2f7cbd408\",\n \"sip_headers\": [\n {\"name\": \"Max-Forwards\", \"value\": \"63\"},\n {\"name\": \"CSeq\", \"value\": \"851287 INVITE\"},\n {\"name\": \"Content-Type\", \"value\": \"application/sdp\"},\n ]\n }\n}\n" + } + }, + "WebhookResponseCancelled": { + "type": "object", + "title": "response.cancelled", + "description": "Sent when a background response has been cancelled.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the model response was cancelled.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the model response.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `response.cancelled`.\n", + "enum": [ + "response.cancelled" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "response.cancelled", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"response.cancelled\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"resp_abc123\"\n }\n}\n" + } + }, + "WebhookResponseCompleted": { + "type": "object", + "title": "response.completed", + "description": "Sent when a background response has been completed.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the model response was completed.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the model response.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `response.completed`.\n", + "enum": [ + "response.completed" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "response.completed", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"response.completed\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"resp_abc123\"\n }\n}\n" + } + }, + "WebhookResponseFailed": { + "type": "object", + "title": "response.failed", + "description": "Sent when a background response has failed.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the model response failed.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the model response.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `response.failed`.\n", + "enum": [ + "response.failed" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "response.failed", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"response.failed\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"resp_abc123\"\n }\n}\n" + } + }, + "WebhookResponseIncomplete": { + "type": "object", + "title": "response.incomplete", + "description": "Sent when a background response has been interrupted.\n", + "required": [ + "created_at", + "id", + "data", + "type" + ], + "properties": { + "created_at": { + "type": "integer", + "description": "The Unix timestamp (in seconds) of when the model response was interrupted.\n" + }, + "id": { + "type": "string", + "description": "The unique ID of the event.\n" + }, + "data": { + "type": "object", + "description": "Event data payload.\n", + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the model response.\n" + } + } + }, + "object": { + "type": "string", + "description": "The object of the event. Always `event`.\n", + "enum": [ + "event" + ], + "x-stainless-const": true + }, + "type": { + "type": "string", + "description": "The type of the event. Always `response.incomplete`.\n", + "enum": [ + "response.incomplete" + ], + "x-stainless-const": true + } + }, + "x-oaiMeta": { + "name": "response.incomplete", + "group": "webhook-events", + "example": "{\n \"id\": \"evt_abc123\",\n \"type\": \"response.incomplete\",\n \"created_at\": 1719168000,\n \"data\": {\n \"id\": \"resp_abc123\"\n }\n}\n" + } + }, + "InputTextContent": { + "properties": { + "type": { + "type": "string", + "enum": [ + "input_text" + ], + "description": "The type of the input item. Always `input_text`.", + "default": "input_text", + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text input to the model." + } + }, + "type": "object", + "required": [ + "type", + "text" + ], + "title": "Input text", + "description": "A text input to the model." + }, + "InputImageContent": { + "properties": { + "type": { + "type": "string", + "enum": [ + "input_image" + ], + "description": "The type of the input item. Always `input_image`.", + "default": "input_image", + "x-stainless-const": true + }, + "image_url": { + "anyOf": [ + { + "type": "string", + "description": "The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL." + }, + { + "type": "null" + } + ] + }, + "file_id": { + "anyOf": [ + { + "type": "string", + "description": "The ID of the file to be sent to the model." + }, + { + "type": "null" + } + ] + }, + "detail": { + "type": "string", + "enum": [ + "low", + "high", + "auto" + ], + "description": "The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`." + } + }, + "type": "object", + "required": [ + "type", + "detail" + ], + "title": "Input image", + "description": "An image input to the model. Learn about [image inputs](https://platform.openai.com/docs/guides/vision)." + }, + "InputFileContent": { + "properties": { + "type": { + "type": "string", + "enum": [ + "input_file" + ], + "description": "The type of the input item. Always `input_file`.", + "default": "input_file", + "x-stainless-const": true + }, + "file_id": { + "anyOf": [ + { + "type": "string", + "description": "The ID of the file to be sent to the model." + }, + { + "type": "null" + } + ] + }, + "filename": { + "type": "string", + "description": "The name of the file to be sent to the model." + }, + "file_url": { + "type": "string", + "description": "The URL of the file to be sent to the model." + }, + "file_data": { + "type": "string", + "description": "The content of the file to be sent to the model.\n" + } + }, + "type": "object", + "required": [ + "type" + ], + "title": "Input file", + "description": "A file input to the model." + }, + "FileCitationBody": { + "properties": { + "type": { + "type": "string", + "enum": [ + "file_citation" + ], + "description": "The type of the file citation. Always `file_citation`.", + "default": "file_citation", + "x-stainless-const": true + }, + "file_id": { + "type": "string", + "description": "The ID of the file." + }, + "index": { + "type": "integer", + "description": "The index of the file in the list of files." + }, + "filename": { + "type": "string", + "description": "The filename of the file cited." + } + }, + "type": "object", + "required": [ + "type", + "file_id", + "index", + "filename" + ], + "title": "File citation", + "description": "A citation to a file." + }, + "UrlCitationBody": { + "properties": { + "type": { + "type": "string", + "enum": [ + "url_citation" + ], + "description": "The type of the URL citation. Always `url_citation`.", + "default": "url_citation", + "x-stainless-const": true + }, + "url": { + "type": "string", + "description": "The URL of the web resource." + }, + "start_index": { + "type": "integer", + "description": "The index of the first character of the URL citation in the message." + }, + "end_index": { + "type": "integer", + "description": "The index of the last character of the URL citation in the message." + }, + "title": { + "type": "string", + "description": "The title of the web resource." + } + }, + "type": "object", + "required": [ + "type", + "url", + "start_index", + "end_index", + "title" + ], + "title": "URL citation", + "description": "A citation for a web resource used to generate a model response." + }, + "ContainerFileCitationBody": { + "properties": { + "type": { + "type": "string", + "enum": [ + "container_file_citation" + ], + "description": "The type of the container file citation. Always `container_file_citation`.", + "default": "container_file_citation", + "x-stainless-const": true + }, + "container_id": { + "type": "string", + "description": "The ID of the container file." + }, + "file_id": { + "type": "string", + "description": "The ID of the file." + }, + "start_index": { + "type": "integer", + "description": "The index of the first character of the container file citation in the message." + }, + "end_index": { + "type": "integer", + "description": "The index of the last character of the container file citation in the message." + }, + "filename": { + "type": "string", + "description": "The filename of the container file cited." + } + }, + "type": "object", + "required": [ + "type", + "container_id", + "file_id", + "start_index", + "end_index", + "filename" + ], + "title": "Container file citation", + "description": "A citation for a container file used to generate a model response." + }, + "Annotation": { + "discriminator": { + "propertyName": "type" + }, + "anyOf": [ + { + "$ref": "#/components/schemas/FileCitationBody" + }, + { + "$ref": "#/components/schemas/UrlCitationBody" + }, + { + "$ref": "#/components/schemas/ContainerFileCitationBody" + }, + { + "$ref": "#/components/schemas/FilePath" + } + ] + }, + "TopLogProb": { + "properties": { + "token": { + "type": "string" + }, + "logprob": { + "type": "number" + }, + "bytes": { + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "type": "object", + "required": [ + "token", + "logprob", + "bytes" + ], + "title": "Top log probability", + "description": "The top log probability of a token." + }, + "LogProb": { + "properties": { + "token": { + "type": "string" + }, + "logprob": { + "type": "number" + }, + "bytes": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "top_logprobs": { + "items": { + "$ref": "#/components/schemas/TopLogProb" + }, + "type": "array" + } + }, + "type": "object", + "required": [ + "token", + "logprob", + "bytes", + "top_logprobs" + ], + "title": "Log probability", + "description": "The log probability of a token." + }, + "OutputTextContent": { + "properties": { + "type": { + "type": "string", + "enum": [ + "output_text" + ], + "description": "The type of the output text. Always `output_text`.", + "default": "output_text", + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text output from the model." + }, + "annotations": { + "items": { + "$ref": "#/components/schemas/Annotation" + }, + "type": "array", + "description": "The annotations of the text output." + }, + "logprobs": { + "items": { + "$ref": "#/components/schemas/LogProb" + }, + "type": "array" + } + }, + "type": "object", + "required": [ + "type", + "text", + "annotations" + ], + "title": "Output text", + "description": "A text output from the model." + }, + "RefusalContent": { + "properties": { + "type": { + "type": "string", + "enum": [ + "refusal" + ], + "description": "The type of the refusal. Always `refusal`.", + "default": "refusal", + "x-stainless-const": true + }, + "refusal": { + "type": "string", + "description": "The refusal explanation from the model." + } + }, + "type": "object", + "required": [ + "type", + "refusal" + ], + "title": "Refusal", + "description": "A refusal from the model." + }, + "ComputerCallSafetyCheckParam": { + "properties": { + "id": { + "type": "string", + "description": "The ID of the pending safety check." + }, + "code": { + "anyOf": [ + { + "type": "string", + "description": "The type of the pending safety check." + }, + { + "type": "null" + } + ] + }, + "message": { + "anyOf": [ + { + "type": "string", + "description": "Details about the pending safety check." + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "required": [ + "id" + ], + "description": "A pending safety check for the computer call." + }, + "ComputerCallOutputItemParam": { + "properties": { + "id": { + "anyOf": [ + { + "type": "string", + "description": "The ID of the computer tool call output." + }, + { + "type": "null" + } + ] + }, + "call_id": { + "type": "string", + "maxLength": 64, + "minLength": 1, + "description": "The ID of the computer tool call that produced the output." + }, + "type": { + "type": "string", + "enum": [ + "computer_call_output" + ], + "description": "The type of the computer tool call output. Always `computer_call_output`.", + "default": "computer_call_output", + "x-stainless-const": true + }, + "output": { + "$ref": "#/components/schemas/ComputerScreenshotImage" + }, + "acknowledged_safety_checks": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/ComputerCallSafetyCheckParam" + }, + "type": "array", + "description": "The safety checks reported by the API that have been acknowledged by the developer." + }, + { + "type": "null" + } + ] + }, + "status": { + "anyOf": [ + { + "type": "string", + "enum": [ + "in_progress", + "completed", + "incomplete" + ], + "description": "The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API." + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "required": [ + "call_id", + "type", + "output" + ], + "title": "Computer tool call output", + "description": "The output of a computer tool call." + }, + "FunctionCallOutputItemParam": { + "properties": { + "id": { + "anyOf": [ + { + "type": "string", + "description": "The unique ID of the function tool call output. Populated when this item is returned via API." + }, + { + "type": "null" + } + ] + }, + "call_id": { + "type": "string", + "maxLength": 64, + "minLength": 1, + "description": "The unique ID of the function tool call generated by the model." + }, + "type": { + "type": "string", + "enum": [ + "function_call_output" + ], + "description": "The type of the function tool call output. Always `function_call_output`.", + "default": "function_call_output", + "x-stainless-const": true + }, + "output": { + "type": "string", + "maxLength": 10485760, + "description": "A JSON string of the output of the function tool call." + }, + "status": { + "anyOf": [ + { + "type": "string", + "enum": [ + "in_progress", + "completed", + "incomplete" + ], + "description": "The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API." + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "required": [ + "call_id", + "type", + "output" + ], + "title": "Function tool call output", + "description": "The output of a function tool call." + }, + "ItemReferenceParam": { + "properties": { + "type": { + "anyOf": [ + { + "type": "string", + "enum": [ + "item_reference" + ], + "description": "The type of item to reference. Always `item_reference`.", + "default": "item_reference", + "x-stainless-const": true + }, + { + "type": "null" + } + ] + }, + "id": { + "type": "string", + "description": "The ID of the item to reference." + } + }, + "type": "object", + "required": [ + "id" + ], + "title": "Item reference", + "description": "An internal identifier for an item to reference." + }, + "ConversationResource": { + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the conversation." + }, + "object": { + "type": "string", + "enum": [ + "conversation" + ], + "description": "The object type, which is always `conversation`.", + "default": "conversation", + "x-stainless-const": true + }, + "metadata": { + "description": "Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters." + }, + "created_at": { + "type": "integer", + "description": "The time at which the conversation was created, measured in seconds since the Unix epoch." + } + }, + "type": "object", + "required": [ + "id", + "object", + "metadata", + "created_at" + ] + }, + "MetadataParam": { + "additionalProperties": { + "type": "string", + "maxLength": 512 + }, + "type": "object", + "maxProperties": 16 + }, + "UpdateConversationBody": { + "properties": { + "metadata": { + "$ref": "#/components/schemas/MetadataParam", + "description": "Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters." + } + }, + "type": "object", + "required": [ + "metadata" + ] + }, + "DeletedConversationResource": { + "properties": { + "object": { + "type": "string", + "enum": [ + "conversation.deleted" + ], + "default": "conversation.deleted", + "x-stainless-const": true + }, + "deleted": { + "type": "boolean" + }, + "id": { + "type": "string" + } + }, + "type": "object", + "required": [ + "object", + "deleted", + "id" + ] + }, + "InputTextContent-2": { + "properties": { + "type": { + "type": "string", + "enum": [ + "input_text" + ], + "description": "The type of the input item. Always `input_text`.", + "default": "input_text", + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text input to the model." + } + }, + "type": "object", + "required": [ + "type", + "text" + ], + "title": "Input text" + }, + "FileCitationBody-2": { + "properties": { + "type": { + "type": "string", + "enum": [ + "file_citation" + ], + "description": "The type of the file citation. Always `file_citation`.", + "default": "file_citation", + "x-stainless-const": true + }, + "file_id": { + "type": "string", + "description": "The ID of the file." + }, + "index": { + "type": "integer", + "description": "The index of the file in the list of files." + }, + "filename": { + "type": "string", + "description": "The filename of the file cited." + } + }, + "type": "object", + "required": [ + "type", + "file_id", + "index", + "filename" + ], + "title": "File citation" + }, + "UrlCitationBody-2": { + "properties": { + "type": { + "type": "string", + "enum": [ + "url_citation" + ], + "description": "The type of the URL citation. Always `url_citation`.", + "default": "url_citation", + "x-stainless-const": true + }, + "url": { + "type": "string", + "description": "The URL of the web resource." + }, + "start_index": { + "type": "integer", + "description": "The index of the first character of the URL citation in the message." + }, + "end_index": { + "type": "integer", + "description": "The index of the last character of the URL citation in the message." + }, + "title": { + "type": "string", + "description": "The title of the web resource." + } + }, + "type": "object", + "required": [ + "type", + "url", + "start_index", + "end_index", + "title" + ], + "title": "URL citation" + }, + "ContainerFileCitationBody-2": { + "properties": { + "type": { + "type": "string", + "enum": [ + "container_file_citation" + ], + "description": "The type of the container file citation. Always `container_file_citation`.", + "default": "container_file_citation", + "x-stainless-const": true + }, + "container_id": { + "type": "string", + "description": "The ID of the container file." + }, + "file_id": { + "type": "string", + "description": "The ID of the file." + }, + "start_index": { + "type": "integer", + "description": "The index of the first character of the container file citation in the message." + }, + "end_index": { + "type": "integer", + "description": "The index of the last character of the container file citation in the message." + }, + "filename": { + "type": "string", + "description": "The filename of the container file cited." + } + }, + "type": "object", + "required": [ + "type", + "container_id", + "file_id", + "start_index", + "end_index", + "filename" + ], + "title": "Container file citation" + }, + "Annotation-2": { + "discriminator": { + "propertyName": "type" + }, + "anyOf": [ + { + "$ref": "#/components/schemas/FileCitationBody-2" + }, + { + "$ref": "#/components/schemas/UrlCitationBody-2" + }, + { + "$ref": "#/components/schemas/ContainerFileCitationBody-2" + } + ] + }, + "TopLogProb-2": { + "properties": { + "token": { + "type": "string" + }, + "logprob": { + "type": "number" + }, + "bytes": { + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "type": "object", + "required": [ + "token", + "logprob", + "bytes" + ], + "title": "Top log probability" + }, + "LogProb-2": { + "properties": { + "token": { + "type": "string" + }, + "logprob": { + "type": "number" + }, + "bytes": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "top_logprobs": { + "items": { + "$ref": "#/components/schemas/TopLogProb-2" + }, + "type": "array" + } + }, + "type": "object", + "required": [ + "token", + "logprob", + "bytes", + "top_logprobs" + ], + "title": "Log probability" + }, + "OutputTextContent-2": { + "properties": { + "type": { + "type": "string", + "enum": [ + "output_text" + ], + "description": "The type of the output text. Always `output_text`.", + "default": "output_text", + "x-stainless-const": true + }, + "text": { + "type": "string", + "description": "The text output from the model." + }, + "annotations": { + "items": { + "$ref": "#/components/schemas/Annotation-2" + }, + "type": "array", + "description": "The annotations of the text output." + }, + "logprobs": { + "items": { + "$ref": "#/components/schemas/LogProb-2" + }, + "type": "array" + } + }, + "type": "object", + "required": [ + "type", + "text", + "annotations" + ], + "title": "Output text" + }, + "TextContent": { + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ], + "default": "text", + "x-stainless-const": true + }, + "text": { + "type": "string" + } + }, + "type": "object", + "required": [ + "type", + "text" + ], + "title": "Text Content" + }, + "SummaryTextContent": { + "properties": { + "type": { + "type": "string", + "enum": [ + "summary_text" + ], + "default": "summary_text", + "x-stainless-const": true + }, + "text": { + "type": "string" + } + }, + "type": "object", + "required": [ + "type", + "text" + ], + "title": "Summary text" + }, + "RefusalContent-2": { + "properties": { + "type": { + "type": "string", + "enum": [ + "refusal" + ], + "description": "The type of the refusal. Always `refusal`.", + "default": "refusal", + "x-stainless-const": true + }, + "refusal": { + "type": "string", + "description": "The refusal explanation from the model." + } + }, + "type": "object", + "required": [ + "type", + "refusal" + ], + "title": "Refusal" + }, + "InputImageContent-2": { + "properties": { + "type": { + "type": "string", + "enum": [ + "input_image" + ], + "description": "The type of the input item. Always `input_image`.", + "default": "input_image", + "x-stainless-const": true + }, + "image_url": { + "anyOf": [ + { + "type": "string", + "description": "The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL." + }, + { + "type": "null" + } + ] + }, + "file_id": { + "anyOf": [ + { + "type": "string", + "description": "The ID of the file to be sent to the model." + }, + { + "type": "null" + } + ] + }, + "detail": { + "type": "string", + "enum": [ + "low", + "high", + "auto" + ], + "description": "The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`." + } + }, + "type": "object", + "required": [ + "type", + "image_url", + "file_id", + "detail" + ], + "title": "Input image" + }, + "ComputerScreenshotContent": { + "properties": { + "type": { + "type": "string", + "enum": [ + "computer_screenshot" + ], + "description": "Specifies the event type. For a computer screenshot, this property is always set to `computer_screenshot`.", + "default": "computer_screenshot", + "x-stainless-const": true + }, + "image_url": { + "anyOf": [ + { + "type": "string", + "description": "The URL of the screenshot image." + }, + { + "type": "null" + } + ] + }, + "file_id": { + "anyOf": [ + { + "type": "string", + "description": "The identifier of an uploaded file that contains the screenshot." + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "required": [ + "type", + "image_url", + "file_id" + ], + "title": "Computer screenshot" + }, + "InputFileContent-2": { + "properties": { + "type": { + "type": "string", + "enum": [ + "input_file" + ], + "description": "The type of the input item. Always `input_file`.", + "default": "input_file", + "x-stainless-const": true + }, + "file_id": { + "anyOf": [ + { + "type": "string", + "description": "The ID of the file to be sent to the model." + }, + { + "type": "null" + } + ] + }, + "filename": { + "type": "string", + "description": "The name of the file to be sent to the model." + }, + "file_url": { + "type": "string", + "description": "The URL of the file to be sent to the model." + } + }, + "type": "object", + "required": [ + "type", + "file_id" + ], + "title": "Input file" + }, + "Message": { + "properties": { + "type": { + "type": "string", + "enum": [ + "message" + ], + "description": "The type of the message. Always set to `message`.", + "default": "message", + "x-stainless-const": true + }, + "id": { + "type": "string", + "description": "The unique ID of the message." + }, + "status": { + "type": "string", + "enum": [ + "in_progress", + "completed", + "incomplete" + ], + "description": "The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API." + }, + "role": { + "type": "string", + "enum": [ + "unknown", + "user", + "assistant", + "system", + "critic", + "discriminator", + "developer", + "tool" + ], + "description": "The role of the message. One of `unknown`, `user`, `assistant`, `system`, `critic`, `discriminator`, `developer`, or `tool`." + }, + "content": { + "items": { + "discriminator": { + "propertyName": "type" + }, + "anyOf": [ + { + "$ref": "#/components/schemas/InputTextContent-2" + }, + { + "$ref": "#/components/schemas/OutputTextContent-2" + }, + { + "$ref": "#/components/schemas/TextContent" + }, + { + "$ref": "#/components/schemas/SummaryTextContent" + }, + { + "$ref": "#/components/schemas/RefusalContent-2" + }, + { + "$ref": "#/components/schemas/InputImageContent-2" + }, + { + "$ref": "#/components/schemas/ComputerScreenshotContent" + }, + { + "$ref": "#/components/schemas/InputFileContent-2" + } + ] + }, + "type": "array", + "description": "The content of the message" + } + }, + "type": "object", + "required": [ + "type", + "id", + "status", + "role", + "content" + ], + "title": "Message" + }, + "FunctionTool": { + "properties": { + "type": { + "type": "string", + "enum": [ + "function" + ], + "description": "The type of the function tool. Always `function`.", + "default": "function", + "x-stainless-const": true + }, + "name": { + "type": "string", + "description": "The name of the function to call." + }, + "description": { + "anyOf": [ + { + "type": "string", + "description": "A description of the function. Used by the model to determine whether or not to call the function." + }, + { + "type": "null" + } + ] + }, + "parameters": { + "anyOf": [ + { + "additionalProperties": {}, + "type": "object", + "description": "A JSON schema object describing the parameters of the function." + }, + { + "type": "null" + } + ] + }, + "strict": { + "anyOf": [ + { + "type": "boolean", + "description": "Whether to enforce strict parameter validation. Default `true`." + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "required": [ + "type", + "name", + "strict", + "parameters" + ], + "title": "Function", + "description": "Defines a function in your own code the model can choose to call. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling)." + }, + "RankingOptions": { + "properties": { + "ranker": { + "type": "string", + "enum": [ + "auto", + "default-2024-11-15" + ], + "description": "The ranker to use for the file search." + }, + "score_threshold": { + "type": "number", + "description": "The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results." + } + }, + "type": "object", + "required": [] + }, + "Filters": { + "anyOf": [ + { + "$ref": "#/components/schemas/ComparisonFilter" + }, + { + "$ref": "#/components/schemas/CompoundFilter" + } + ] + }, + "FileSearchTool": { + "properties": { + "type": { + "type": "string", + "enum": [ + "file_search" + ], + "description": "The type of the file search tool. Always `file_search`.", + "default": "file_search", + "x-stainless-const": true + }, + "vector_store_ids": { + "items": { + "type": "string" + }, + "type": "array", + "description": "The IDs of the vector stores to search." + }, + "max_num_results": { + "type": "integer", + "description": "The maximum number of results to return. This number should be between 1 and 50 inclusive." + }, + "ranking_options": { + "$ref": "#/components/schemas/RankingOptions", + "description": "Ranking options for search." + }, + "filters": { + "anyOf": [ + { + "$ref": "#/components/schemas/Filters", + "description": "A filter to apply." + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "required": [ + "type", + "vector_store_ids" + ], + "title": "File search", + "description": "A tool that searches for relevant content from uploaded files. Learn more about the [file search tool](https://platform.openai.com/docs/guides/tools-file-search)." + }, + "ComputerUsePreviewTool": { + "properties": { + "type": { + "type": "string", + "enum": [ + "computer_use_preview" + ], + "description": "The type of the computer use tool. Always `computer_use_preview`.", + "default": "computer_use_preview", + "x-stainless-const": true + }, + "environment": { + "type": "string", + "enum": [ + "windows", + "mac", + "linux", + "ubuntu", + "browser" + ], + "description": "The type of computer environment to control." + }, + "display_width": { + "type": "integer", + "description": "The width of the computer display." + }, + "display_height": { + "type": "integer", + "description": "The height of the computer display." + } + }, + "type": "object", + "required": [ + "type", + "environment", + "display_width", + "display_height" + ], + "title": "Computer use preview", + "description": "A tool that controls a virtual computer. Learn more about the [computer tool](https://platform.openai.com/docs/guides/tools-computer-use)." + }, + "ApproximateLocation": { + "properties": { + "type": { + "type": "string", + "enum": [ + "approximate" + ], + "description": "The type of location approximation. Always `approximate`.", + "default": "approximate", + "x-stainless-const": true + }, + "country": { + "anyOf": [ + { + "type": "string", + "description": "The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`." + }, + { + "type": "null" + } + ] + }, + "region": { + "anyOf": [ + { + "type": "string", + "description": "Free text input for the region of the user, e.g. `California`." + }, + { + "type": "null" + } + ] + }, + "city": { + "anyOf": [ + { + "type": "string", + "description": "Free text input for the city of the user, e.g. `San Francisco`." + }, + { + "type": "null" + } + ] + }, + "timezone": { + "anyOf": [ + { + "type": "string", + "description": "The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`." + }, + { + "type": "null" + } + ] + } + }, + "type": "object", + "required": [ + "type" + ] + }, + "WebSearchPreviewTool": { + "properties": { + "type": { + "type": "string", + "enum": [ + "web_search_preview", + "web_search_preview_2025_03_11" + ], + "description": "The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`.", + "default": "web_search_preview", + "x-stainless-const": true + }, + "user_location": { + "anyOf": [ + { + "$ref": "#/components/schemas/ApproximateLocation", + "description": "The user's location." + }, + { + "type": "null" + } + ] + }, + "search_context_size": { + "type": "string", + "enum": [ + "low", + "medium", + "high" + ], + "description": "High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default." + } + }, + "type": "object", + "required": [ + "type" + ], + "title": "Web search preview", + "description": "This tool searches the web for relevant results to use in a response. Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search)." + }, + "ImageGenInputUsageDetails": { + "properties": { + "text_tokens": { + "type": "integer", + "description": "The number of text tokens in the input prompt." + }, + "image_tokens": { + "type": "integer", + "description": "The number of image tokens in the input prompt." + } + }, + "type": "object", + "required": [ + "text_tokens", + "image_tokens" + ], + "title": "Input usage details", + "description": "The input tokens detailed information for the image generation." + }, + "ImageGenUsage": { + "properties": { + "input_tokens": { + "type": "integer", + "description": "The number of tokens (images and text) in the input prompt." + }, + "total_tokens": { + "type": "integer", + "description": "The total number of tokens (images and text) used for the image generation." + }, + "output_tokens": { + "type": "integer", + "description": "The number of output tokens generated by the model." + }, + "input_tokens_details": { + "$ref": "#/components/schemas/ImageGenInputUsageDetails" + } + }, + "type": "object", + "required": [ + "input_tokens", + "total_tokens", + "output_tokens", + "input_tokens_details" + ], + "title": "Image generation usage", + "description": "For `gpt-image-1` only, the token usage information for the image generation." + }, + "ConversationParam": { + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the conversation." + } + }, + "type": "object", + "required": [ + "id" + ], + "title": "Conversation object", + "description": "The conversation that this response belongs to." + }, + "Conversation-2": { + "properties": { + "id": { + "type": "string", + "description": "The unique ID of the conversation." + } + }, + "type": "object", + "required": [ + "id" + ], + "title": "Conversation", + "description": "The conversation that this response belongs to. Input items and output items from this response are automatically added to this conversation." + }, + "RealtimeConnectParams": { + "type": "object", + "properties": { + "model": { + "type": "string" + } + }, + "required": [ + "model" + ] + }, + "ModerationImageURLInput": { + "type": "object", + "description": "An object describing an image to classify.", + "properties": { + "type": { + "description": "Always `image_url`.", + "type": "string", + "enum": [ + "image_url" + ], + "x-stainless-const": true + }, + "image_url": { + "type": "object", + "description": "Contains either an image URL or a data URL for a base64 encoded image.", + "properties": { + "url": { + "type": "string", + "description": "Either a URL of the image or the base64 encoded image data.", + "format": "uri", + "example": "https://example.com/image.jpg" + } + }, + "required": [ + "url" + ] + } + }, + "required": [ + "type", + "image_url" + ] + }, + "ModerationTextInput": { + "type": "object", + "description": "An object describing text to classify.", + "properties": { + "type": { + "description": "Always `text`.", + "type": "string", + "enum": [ + "text" + ], + "x-stainless-const": true + }, + "text": { + "description": "A string of text to classify.", + "type": "string", + "example": "I want to kill them" + } + }, + "required": [ + "type", + "text" + ] + }, + "ChunkingStrategyResponse": { + "type": "object", + "description": "The strategy used to chunk the file.", + "anyOf": [ + { + "$ref": "#/components/schemas/StaticChunkingStrategyResponseParam" + }, + { + "$ref": "#/components/schemas/OtherChunkingStrategyResponseParam" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "FilePurpose": { + "description": "The intended purpose of the uploaded file. One of: - `assistants`: Used in the Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: Flexible file type for any purpose - `evals`: Used for eval data sets\n", + "type": "string", + "enum": [ + "assistants", + "batch", + "fine-tune", + "vision", + "user_data", + "evals" + ] + }, + "BatchError": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "An error code identifying the error type." + }, + "message": { + "type": "string", + "description": "A human-readable message providing more details about the error." + }, + "param": { + "type": "string", + "description": "The name of the parameter that caused the error, if applicable.", + "nullable": true + }, + "line": { + "type": "integer", + "description": "The line number of the input file where the error occurred, if applicable.", + "nullable": true + } + } + }, + "BatchRequestCounts": { + "type": "object", + "properties": { + "total": { + "type": "integer", + "description": "Total number of requests in the batch." + }, + "completed": { + "type": "integer", + "description": "Number of requests that have been completed successfully." + }, + "failed": { + "type": "integer", + "description": "Number of requests that have failed." + } + }, + "required": [ + "total", + "completed", + "failed" + ], + "description": "The request counts for different statuses within the batch." + }, + "AssistantTool": { + "anyOf": [ + { + "$ref": "#/components/schemas/AssistantToolsCode" + }, + { + "$ref": "#/components/schemas/AssistantToolsFileSearch" + }, + { + "$ref": "#/components/schemas/AssistantToolsFunction" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "TextAnnotationDelta": { + "anyOf": [ + { + "$ref": "#/components/schemas/MessageDeltaContentTextAnnotationsFileCitationObject" + }, + { + "$ref": "#/components/schemas/MessageDeltaContentTextAnnotationsFilePathObject" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "TextAnnotation": { + "anyOf": [ + { + "$ref": "#/components/schemas/MessageContentTextAnnotationsFileCitationObject" + }, + { + "$ref": "#/components/schemas/MessageContentTextAnnotationsFilePathObject" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "RunStepDetailsToolCall": { + "anyOf": [ + { + "$ref": "#/components/schemas/RunStepDetailsToolCallsCodeObject" + }, + { + "$ref": "#/components/schemas/RunStepDetailsToolCallsFileSearchObject" + }, + { + "$ref": "#/components/schemas/RunStepDetailsToolCallsFunctionObject" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "RunStepDeltaStepDetailsToolCall": { + "anyOf": [ + { + "$ref": "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeObject" + }, + { + "$ref": "#/components/schemas/RunStepDeltaStepDetailsToolCallsFileSearchObject" + }, + { + "$ref": "#/components/schemas/RunStepDeltaStepDetailsToolCallsFunctionObject" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "MessageContent": { + "anyOf": [ + { + "$ref": "#/components/schemas/MessageContentImageFileObject" + }, + { + "$ref": "#/components/schemas/MessageContentImageUrlObject" + }, + { + "$ref": "#/components/schemas/MessageContentTextObject" + }, + { + "$ref": "#/components/schemas/MessageContentRefusalObject" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "MessageContentDelta": { + "anyOf": [ + { + "$ref": "#/components/schemas/MessageDeltaContentImageFileObject" + }, + { + "$ref": "#/components/schemas/MessageDeltaContentTextObject" + }, + { + "$ref": "#/components/schemas/MessageDeltaContentRefusalObject" + }, + { + "$ref": "#/components/schemas/MessageDeltaContentImageUrlObject" + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "ChatModel": { + "type": "string", + "enum": [ + "gpt-5", + "gpt-5-mini", + "gpt-5-nano", + "gpt-5-2025-08-07", + "gpt-5-mini-2025-08-07", + "gpt-5-nano-2025-08-07", + "gpt-5-chat-latest", + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", + "o4-mini", + "o4-mini-2025-04-16", + "o3", + "o3-2025-04-16", + "o3-mini", + "o3-mini-2025-01-31", + "o1", + "o1-2024-12-17", + "o1-preview", + "o1-preview-2024-09-12", + "o1-mini", + "o1-mini-2024-09-12", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-audio-preview", + "gpt-4o-audio-preview-2024-10-01", + "gpt-4o-audio-preview-2024-12-17", + "gpt-4o-audio-preview-2025-06-03", + "gpt-4o-mini-audio-preview", + "gpt-4o-mini-audio-preview-2024-12-17", + "gpt-4o-search-preview", + "gpt-4o-mini-search-preview", + "gpt-4o-search-preview-2025-03-11", + "gpt-4o-mini-search-preview-2025-03-11", + "chatgpt-4o-latest", + "codex-mini-latest", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613" + ], + "x-stainless-nominal": false + }, + "CreateThreadAndRunRequestWithoutStream": { + "type": "object", + "additionalProperties": false, + "properties": { + "assistant_id": { + "description": "The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.", + "type": "string" + }, + "thread": { + "$ref": "#/components/schemas/CreateThreadRequest" + }, + "model": { + "description": "The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "gpt-5", + "gpt-5-mini", + "gpt-5-nano", + "gpt-5-2025-08-07", + "gpt-5-mini-2025-08-07", + "gpt-5-nano-2025-08-07", + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613" + ] + } + ], + "x-oaiTypeLabel": "string", + "nullable": true + }, + "instructions": { + "description": "Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis.", + "type": "string", + "nullable": true + }, + "tools": { + "description": "Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.", + "nullable": true, + "type": "array", + "maxItems": 20, + "items": { + "$ref": "#/components/schemas/AssistantTool" + } + }, + "tool_resources": { + "type": "object", + "description": "A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n", + "properties": { + "code_interpreter": { + "type": "object", + "properties": { + "file_ids": { + "type": "array", + "description": "A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n", + "default": [], + "maxItems": 20, + "items": { + "type": "string" + } + } + } + }, + "file_search": { + "type": "object", + "properties": { + "vector_store_ids": { + "type": "array", + "description": "The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n", + "maxItems": 1, + "items": { + "type": "string" + } + } + } + } + }, + "nullable": true + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "temperature": { + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 1, + "example": 1, + "nullable": true, + "description": "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n" + }, + "top_p": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 1, + "example": 1, + "nullable": true, + "description": "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }, + "max_prompt_tokens": { + "type": "integer", + "nullable": true, + "description": "The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + "minimum": 256 + }, + "max_completion_tokens": { + "type": "integer", + "nullable": true, + "description": "The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + "minimum": 256 + }, + "truncation_strategy": { + "allOf": [ + { + "$ref": "#/components/schemas/TruncationObject" + }, + { + "nullable": true + } + ] + }, + "tool_choice": { + "allOf": [ + { + "$ref": "#/components/schemas/AssistantsApiToolChoiceOption" + }, + { + "nullable": true + } + ] + }, + "parallel_tool_calls": { + "$ref": "#/components/schemas/ParallelToolCalls" + }, + "response_format": { + "$ref": "#/components/schemas/AssistantsApiResponseFormatOption", + "nullable": true + } + }, + "required": [ + "assistant_id" + ] + }, + "CreateRunRequestWithoutStream": { + "type": "object", + "additionalProperties": false, + "properties": { + "assistant_id": { + "description": "The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.", + "type": "string" + }, + "model": { + "description": "The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.", + "anyOf": [ + { + "type": "string" + }, + { + "$ref": "#/components/schemas/AssistantSupportedModels" + } + ], + "x-oaiTypeLabel": "string", + "nullable": true + }, + "reasoning_effort": { + "$ref": "#/components/schemas/ReasoningEffort" + }, + "instructions": { + "description": "Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis.", + "type": "string", + "nullable": true + }, + "additional_instructions": { + "description": "Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.", + "type": "string", + "nullable": true + }, + "additional_messages": { + "description": "Adds additional messages to the thread before creating the run.", + "type": "array", + "items": { + "$ref": "#/components/schemas/CreateMessageRequest" + }, + "nullable": true + }, + "tools": { + "description": "Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.", + "nullable": true, + "type": "array", + "maxItems": 20, + "items": { + "$ref": "#/components/schemas/AssistantTool" + } + }, + "metadata": { + "$ref": "#/components/schemas/Metadata" + }, + "temperature": { + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 1, + "example": 1, + "nullable": true, + "description": "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n" + }, + "top_p": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 1, + "example": 1, + "nullable": true, + "description": "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }, + "max_prompt_tokens": { + "type": "integer", + "nullable": true, + "description": "The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + "minimum": 256 + }, + "max_completion_tokens": { + "type": "integer", + "nullable": true, + "description": "The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n", + "minimum": 256 + }, + "truncation_strategy": { + "allOf": [ + { + "$ref": "#/components/schemas/TruncationObject" + }, + { + "nullable": true + } + ] + }, + "tool_choice": { + "allOf": [ + { + "$ref": "#/components/schemas/AssistantsApiToolChoiceOption" + }, + { + "nullable": true + } + ] + }, + "parallel_tool_calls": { + "$ref": "#/components/schemas/ParallelToolCalls" + }, + "response_format": { + "$ref": "#/components/schemas/AssistantsApiResponseFormatOption", + "nullable": true + } + }, + "required": [ + "assistant_id" + ] + }, + "SubmitToolOutputsRunRequestWithoutStream": { + "type": "object", + "additionalProperties": false, + "properties": { + "tool_outputs": { + "description": "A list of tools for which the outputs are being submitted.", + "type": "array", + "items": { + "type": "object", + "properties": { + "tool_call_id": { + "type": "string", + "description": "The ID of the tool call in the `required_action` object within the run object the output is being submitted for." + }, + "output": { + "type": "string", + "description": "The output of the tool call to be submitted to continue the run." + } + } + } + } + }, + "required": [ + "tool_outputs" + ] + }, + "RunStatus": { + "description": "The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`.", + "type": "string", + "enum": [ + "queued", + "in_progress", + "requires_action", + "cancelling", + "cancelled", + "failed", + "completed", + "incomplete", + "expired" + ] + }, + "RunStepDeltaObjectDelta": { + "description": "The delta containing the fields that have changed on the run step.", + "type": "object", + "properties": { + "step_details": { + "type": "object", + "description": "The details of the run step.", + "anyOf": [ + { + "$ref": "#/components/schemas/RunStepDeltaStepDetailsMessageCreationObject" + }, + { + "$ref": "#/components/schemas/RunStepDeltaStepDetailsToolCallsObject" + } + ], + "discriminator": { + "propertyName": "type" + } + } + } + } + }, + "securitySchemes": { + "ApiKeyAuth": { + "type": "http", + "scheme": "bearer" + } + } + }, + "x-oaiMeta": { + "navigationGroups": [ + { + "id": "responses", + "title": "Responses API" + }, + { + "id": "webhooks", + "title": "Webhooks" + }, + { + "id": "endpoints", + "title": "Platform APIs" + }, + { + "id": "vector_stores", + "title": "Vector stores" + }, + { + "id": "containers", + "title": "Containers" + }, + { + "id": "realtime", + "title": "Realtime" + }, + { + "id": "chat", + "title": "Chat Completions" + }, + { + "id": "assistants", + "title": "Assistants", + "beta": true + }, + { + "id": "administration", + "title": "Administration" + }, + { + "id": "legacy", + "title": "Legacy" + } + ], + "groups": [ + { + "id": "responses", + "title": "Responses", + "description": "OpenAI's most advanced interface for generating model responses. Supports\ntext and image inputs, and text outputs. Create stateful interactions\nwith the model, using the output of previous responses as input. Extend\nthe model's capabilities with built-in tools for file search, web search,\ncomputer use, and more. Allow the model access to external systems and data\nusing function calling.\n\nRelated guides:\n- [Quickstart](https://platform.openai.com/docs/quickstart?api-mode=responses)\n- [Text inputs and outputs](https://platform.openai.com/docs/guides/text?api-mode=responses)\n- [Image inputs](https://platform.openai.com/docs/guides/images?api-mode=responses)\n- [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses)\n- [Function calling](https://platform.openai.com/docs/guides/function-calling?api-mode=responses)\n- [Conversation state](https://platform.openai.com/docs/guides/conversation-state?api-mode=responses)\n- [Extend the models with tools](https://platform.openai.com/docs/guides/tools?api-mode=responses)\n", + "navigationGroup": "responses", + "sections": [ + { + "type": "endpoint", + "key": "createResponse", + "path": "create" + }, + { + "type": "endpoint", + "key": "getResponse", + "path": "get" + }, + { + "type": "endpoint", + "key": "deleteResponse", + "path": "delete" + }, + { + "type": "endpoint", + "key": "cancelResponse", + "path": "cancel" + }, + { + "type": "endpoint", + "key": "listInputItems", + "path": "input-items" + }, + { + "type": "object", + "key": "Response", + "path": "object" + }, + { + "type": "object", + "key": "ResponseItemList", + "path": "list" + } + ] + }, + { + "id": "conversations", + "title": "Conversations", + "description": "Create and manage conversations to store and retrieve conversation state across Response API calls.\n", + "navigationGroup": "responses", + "sections": [ + { + "type": "endpoint", + "key": "createConversation", + "path": "create" + }, + { + "type": "endpoint", + "key": "getConversation", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "updateConversation", + "path": "update" + }, + { + "type": "endpoint", + "key": "deleteConversation", + "path": "delete" + }, + { + "type": "endpoint", + "key": "listConversationItems", + "path": "list-items" + }, + { + "type": "endpoint", + "key": "createConversationItems", + "path": "create-items" + }, + { + "type": "endpoint", + "key": "getConversationItem", + "path": "get-item" + }, + { + "type": "endpoint", + "key": "deleteConversationItem", + "path": "delete-item" + }, + { + "type": "object", + "key": "Conversation", + "path": "object" + }, + { + "type": "object", + "key": "ConversationItemList", + "path": "list-items-object" + } + ] + }, + { + "id": "responses-streaming", + "title": "Streaming events", + "description": "When you [create a Response](https://platform.openai.com/docs/api-reference/responses/create) with\n`stream` set to `true`, the server will emit server-sent events to the\nclient as the Response is generated. This section contains the events that\nare emitted by the server.\n\n[Learn more about streaming responses](https://platform.openai.com/docs/guides/streaming-responses?api-mode=responses).\n", + "navigationGroup": "responses", + "sections": [ + { + "type": "object", + "key": "ResponseCreatedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseInProgressEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseCompletedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseFailedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseIncompleteEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseOutputItemAddedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseOutputItemDoneEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseContentPartAddedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseContentPartDoneEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseTextDeltaEvent", + "path": "response/output_text/delta" + }, + { + "type": "object", + "key": "ResponseTextDoneEvent", + "path": "response/output_text/done" + }, + { + "type": "object", + "key": "ResponseRefusalDeltaEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseRefusalDoneEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseFunctionCallArgumentsDeltaEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseFunctionCallArgumentsDoneEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseFileSearchCallInProgressEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseFileSearchCallSearchingEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseFileSearchCallCompletedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseWebSearchCallInProgressEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseWebSearchCallSearchingEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseWebSearchCallCompletedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseReasoningSummaryPartAddedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseReasoningSummaryPartDoneEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseReasoningSummaryTextDeltaEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseReasoningSummaryTextDoneEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseReasoningTextDeltaEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseReasoningTextDoneEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseImageGenCallCompletedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseImageGenCallGeneratingEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseImageGenCallInProgressEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseImageGenCallPartialImageEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseMCPCallArgumentsDeltaEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseMCPCallArgumentsDoneEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseMCPCallCompletedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseMCPCallFailedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseMCPCallInProgressEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseMCPListToolsCompletedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseMCPListToolsFailedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseMCPListToolsInProgressEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseCodeInterpreterCallInProgressEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseCodeInterpreterCallInterpretingEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseCodeInterpreterCallCompletedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseCodeInterpreterCallCodeDeltaEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseCodeInterpreterCallCodeDoneEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseOutputTextAnnotationAddedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseQueuedEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseCustomToolCallInputDeltaEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseCustomToolCallInputDoneEvent", + "path": "" + }, + { + "type": "object", + "key": "ResponseErrorEvent", + "path": "" + } + ] + }, + { + "id": "webhook-events", + "title": "Webhook Events", + "description": "Webhooks are HTTP requests sent by OpenAI to a URL you specify when certain\nevents happen during the course of API usage.\n\n[Learn more about webhooks](https://platform.openai.com/docs/guides/webhooks).\n", + "navigationGroup": "webhooks", + "sections": [ + { + "type": "object", + "key": "WebhookResponseCompleted", + "path": "" + }, + { + "type": "object", + "key": "WebhookResponseCancelled", + "path": "" + }, + { + "type": "object", + "key": "WebhookResponseFailed", + "path": "" + }, + { + "type": "object", + "key": "WebhookResponseIncomplete", + "path": "" + }, + { + "type": "object", + "key": "WebhookBatchCompleted", + "path": "" + }, + { + "type": "object", + "key": "WebhookBatchCancelled", + "path": "" + }, + { + "type": "object", + "key": "WebhookBatchExpired", + "path": "" + }, + { + "type": "object", + "key": "WebhookBatchFailed", + "path": "" + }, + { + "type": "object", + "key": "WebhookFineTuningJobSucceeded", + "path": "" + }, + { + "type": "object", + "key": "WebhookFineTuningJobFailed", + "path": "" + }, + { + "type": "object", + "key": "WebhookFineTuningJobCancelled", + "path": "" + }, + { + "type": "object", + "key": "WebhookEvalRunSucceeded", + "path": "" + }, + { + "type": "object", + "key": "WebhookEvalRunFailed", + "path": "" + }, + { + "type": "object", + "key": "WebhookEvalRunCanceled", + "path": "" + }, + { + "type": "object", + "key": "WebhookRealtimeCallIncoming", + "path": "" + } + ] + }, + { + "id": "audio", + "title": "Audio", + "description": "Learn how to turn audio into text or text into audio.\n\nRelated guide: [Speech to text](https://platform.openai.com/docs/guides/speech-to-text)\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "endpoint", + "key": "createSpeech", + "path": "createSpeech" + }, + { + "type": "endpoint", + "key": "createTranscription", + "path": "createTranscription" + }, + { + "type": "endpoint", + "key": "createTranslation", + "path": "createTranslation" + }, + { + "type": "object", + "key": "CreateTranscriptionResponseJson", + "path": "json-object" + }, + { + "type": "object", + "key": "CreateTranscriptionResponseVerboseJson", + "path": "verbose-json-object" + }, + { + "type": "object", + "key": "SpeechAudioDeltaEvent", + "path": "speech-audio-delta-event" + }, + { + "type": "object", + "key": "SpeechAudioDoneEvent", + "path": "speech-audio-done-event" + }, + { + "type": "object", + "key": "TranscriptTextDeltaEvent", + "path": "transcript-text-delta-event" + }, + { + "type": "object", + "key": "TranscriptTextDoneEvent", + "path": "transcript-text-done-event" + } + ] + }, + { + "id": "images", + "title": "Images", + "description": "Given a prompt and/or an input image, the model will generate a new image.\nRelated guide: [Image generation](https://platform.openai.com/docs/guides/images)\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "endpoint", + "key": "createImage", + "path": "create" + }, + { + "type": "endpoint", + "key": "createImageEdit", + "path": "createEdit" + }, + { + "type": "endpoint", + "key": "createImageVariation", + "path": "createVariation" + }, + { + "type": "object", + "key": "ImagesResponse", + "path": "object" + } + ] + }, + { + "id": "images-streaming", + "title": "Image Streaming", + "description": "Stream image generation and editing in real time with server-sent events.\n[Learn more about image streaming](https://platform.openai.com/docs/guides/image-generation).\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "object", + "key": "ImageGenPartialImageEvent", + "path": "" + }, + { + "type": "object", + "key": "ImageGenCompletedEvent", + "path": "" + }, + { + "type": "object", + "key": "ImageEditPartialImageEvent", + "path": "" + }, + { + "type": "object", + "key": "ImageEditCompletedEvent", + "path": "" + } + ] + }, + { + "id": "embeddings", + "title": "Embeddings", + "description": "Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.\nRelated guide: [Embeddings](https://platform.openai.com/docs/guides/embeddings)\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "endpoint", + "key": "createEmbedding", + "path": "create" + }, + { + "type": "object", + "key": "Embedding", + "path": "object" + } + ] + }, + { + "id": "evals", + "title": "Evals", + "description": "Create, manage, and run evals in the OpenAI platform.\nRelated guide: [Evals](https://platform.openai.com/docs/guides/evals)\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "endpoint", + "key": "createEval", + "path": "create" + }, + { + "type": "endpoint", + "key": "getEval", + "path": "get" + }, + { + "type": "endpoint", + "key": "updateEval", + "path": "update" + }, + { + "type": "endpoint", + "key": "deleteEval", + "path": "delete" + }, + { + "type": "endpoint", + "key": "listEvals", + "path": "list" + }, + { + "type": "endpoint", + "key": "getEvalRuns", + "path": "getRuns" + }, + { + "type": "endpoint", + "key": "getEvalRun", + "path": "getRun" + }, + { + "type": "endpoint", + "key": "createEvalRun", + "path": "createRun" + }, + { + "type": "endpoint", + "key": "cancelEvalRun", + "path": "cancelRun" + }, + { + "type": "endpoint", + "key": "deleteEvalRun", + "path": "deleteRun" + }, + { + "type": "endpoint", + "key": "getEvalRunOutputItem", + "path": "getRunOutputItem" + }, + { + "type": "endpoint", + "key": "getEvalRunOutputItems", + "path": "getRunOutputItems" + }, + { + "type": "object", + "key": "Eval", + "path": "object" + }, + { + "type": "object", + "key": "EvalRun", + "path": "run-object" + }, + { + "type": "object", + "key": "EvalRunOutputItem", + "path": "run-output-item-object" + } + ] + }, + { + "id": "fine-tuning", + "title": "Fine-tuning", + "description": "Manage fine-tuning jobs to tailor a model to your specific training data.\nRelated guide: [Fine-tune models](https://platform.openai.com/docs/guides/fine-tuning)\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "endpoint", + "key": "createFineTuningJob", + "path": "create" + }, + { + "type": "endpoint", + "key": "listPaginatedFineTuningJobs", + "path": "list" + }, + { + "type": "endpoint", + "key": "listFineTuningEvents", + "path": "list-events" + }, + { + "type": "endpoint", + "key": "listFineTuningJobCheckpoints", + "path": "list-checkpoints" + }, + { + "type": "endpoint", + "key": "listFineTuningCheckpointPermissions", + "path": "list-permissions" + }, + { + "type": "endpoint", + "key": "createFineTuningCheckpointPermission", + "path": "create-permission" + }, + { + "type": "endpoint", + "key": "deleteFineTuningCheckpointPermission", + "path": "delete-permission" + }, + { + "type": "endpoint", + "key": "retrieveFineTuningJob", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "cancelFineTuningJob", + "path": "cancel" + }, + { + "type": "endpoint", + "key": "resumeFineTuningJob", + "path": "resume" + }, + { + "type": "endpoint", + "key": "pauseFineTuningJob", + "path": "pause" + }, + { + "type": "object", + "key": "FineTuneChatRequestInput", + "path": "chat-input" + }, + { + "type": "object", + "key": "FineTunePreferenceRequestInput", + "path": "preference-input" + }, + { + "type": "object", + "key": "FineTuneReinforcementRequestInput", + "path": "reinforcement-input" + }, + { + "type": "object", + "key": "FineTuningJob", + "path": "object" + }, + { + "type": "object", + "key": "FineTuningJobEvent", + "path": "event-object" + }, + { + "type": "object", + "key": "FineTuningJobCheckpoint", + "path": "checkpoint-object" + }, + { + "type": "object", + "key": "FineTuningCheckpointPermission", + "path": "permission-object" + } + ] + }, + { + "id": "graders", + "title": "Graders", + "description": "Manage and run graders in the OpenAI platform.\nRelated guide: [Graders](https://platform.openai.com/docs/guides/graders)\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "object", + "key": "GraderStringCheck", + "path": "string-check" + }, + { + "type": "object", + "key": "GraderTextSimilarity", + "path": "text-similarity" + }, + { + "type": "object", + "key": "GraderScoreModel", + "path": "score-model" + }, + { + "type": "object", + "key": "GraderLabelModel", + "path": "label-model" + }, + { + "type": "object", + "key": "GraderPython", + "path": "python" + }, + { + "type": "object", + "key": "GraderMulti", + "path": "multi" + }, + { + "type": "endpoint", + "key": "runGrader", + "path": "run" + }, + { + "type": "endpoint", + "key": "validateGrader", + "path": "validate", + "beta": true + } + ] + }, + { + "id": "batch", + "title": "Batch", + "description": "Create large batches of API requests for asynchronous processing. The Batch API returns completions within 24 hours for a 50% discount.\nRelated guide: [Batch](https://platform.openai.com/docs/guides/batch)\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "endpoint", + "key": "createBatch", + "path": "create" + }, + { + "type": "endpoint", + "key": "retrieveBatch", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "cancelBatch", + "path": "cancel" + }, + { + "type": "endpoint", + "key": "listBatches", + "path": "list" + }, + { + "type": "object", + "key": "Batch", + "path": "object" + }, + { + "type": "object", + "key": "BatchRequestInput", + "path": "request-input" + }, + { + "type": "object", + "key": "BatchRequestOutput", + "path": "request-output" + } + ] + }, + { + "id": "files", + "title": "Files", + "description": "Files are used to upload documents that can be used with features like [Assistants](https://platform.openai.com/docs/api-reference/assistants), [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning), and [Batch API](https://platform.openai.com/docs/guides/batch).\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "endpoint", + "key": "createFile", + "path": "create" + }, + { + "type": "endpoint", + "key": "listFiles", + "path": "list" + }, + { + "type": "endpoint", + "key": "retrieveFile", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "deleteFile", + "path": "delete" + }, + { + "type": "endpoint", + "key": "downloadFile", + "path": "retrieve-contents" + }, + { + "type": "object", + "key": "OpenAIFile", + "path": "object" + } + ] + }, + { + "id": "uploads", + "title": "Uploads", + "description": "Allows you to upload large files in multiple parts.\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "endpoint", + "key": "createUpload", + "path": "create" + }, + { + "type": "endpoint", + "key": "addUploadPart", + "path": "add-part" + }, + { + "type": "endpoint", + "key": "completeUpload", + "path": "complete" + }, + { + "type": "endpoint", + "key": "cancelUpload", + "path": "cancel" + }, + { + "type": "object", + "key": "Upload", + "path": "object" + }, + { + "type": "object", + "key": "UploadPart", + "path": "part-object" + } + ] + }, + { + "id": "models", + "title": "Models", + "description": "List and describe the various models available in the API. You can refer to the [Models](https://platform.openai.com/docs/models) documentation to understand what models are available and the differences between them.\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "endpoint", + "key": "listModels", + "path": "list" + }, + { + "type": "endpoint", + "key": "retrieveModel", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "deleteModel", + "path": "delete" + }, + { + "type": "object", + "key": "Model", + "path": "object" + } + ] + }, + { + "id": "moderations", + "title": "Moderations", + "description": "Given text and/or image inputs, classifies if those inputs are potentially harmful across several categories.\nRelated guide: [Moderations](https://platform.openai.com/docs/guides/moderation)\n", + "navigationGroup": "endpoints", + "sections": [ + { + "type": "endpoint", + "key": "createModeration", + "path": "create" + }, + { + "type": "object", + "key": "CreateModerationResponse", + "path": "object" + } + ] + }, + { + "id": "vector-stores", + "title": "Vector stores", + "description": "Vector stores power semantic search for the Retrieval API and the `file_search` tool in the Responses and Assistants APIs.\n\nRelated guide: [File Search](https://platform.openai.com/docs/assistants/tools/file-search)\n", + "navigationGroup": "vector_stores", + "sections": [ + { + "type": "endpoint", + "key": "createVectorStore", + "path": "create" + }, + { + "type": "endpoint", + "key": "listVectorStores", + "path": "list" + }, + { + "type": "endpoint", + "key": "getVectorStore", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "modifyVectorStore", + "path": "modify" + }, + { + "type": "endpoint", + "key": "deleteVectorStore", + "path": "delete" + }, + { + "type": "endpoint", + "key": "searchVectorStore", + "path": "search" + }, + { + "type": "object", + "key": "VectorStoreObject", + "path": "object" + } + ] + }, + { + "id": "vector-stores-files", + "title": "Vector store files", + "description": "Vector store files represent files inside a vector store.\n\nRelated guide: [File Search](https://platform.openai.com/docs/assistants/tools/file-search)\n", + "navigationGroup": "vector_stores", + "sections": [ + { + "type": "endpoint", + "key": "createVectorStoreFile", + "path": "createFile" + }, + { + "type": "endpoint", + "key": "listVectorStoreFiles", + "path": "listFiles" + }, + { + "type": "endpoint", + "key": "getVectorStoreFile", + "path": "getFile" + }, + { + "type": "endpoint", + "key": "retrieveVectorStoreFileContent", + "path": "getContent" + }, + { + "type": "endpoint", + "key": "updateVectorStoreFileAttributes", + "path": "updateAttributes" + }, + { + "type": "endpoint", + "key": "deleteVectorStoreFile", + "path": "deleteFile" + }, + { + "type": "object", + "key": "VectorStoreFileObject", + "path": "file-object" + } + ] + }, + { + "id": "vector-stores-file-batches", + "title": "Vector store file batches", + "description": "Vector store file batches represent operations to add multiple files to a vector store.\nRelated guide: [File Search](https://platform.openai.com/docs/assistants/tools/file-search)\n", + "navigationGroup": "vector_stores", + "sections": [ + { + "type": "endpoint", + "key": "createVectorStoreFileBatch", + "path": "createBatch" + }, + { + "type": "endpoint", + "key": "getVectorStoreFileBatch", + "path": "getBatch" + }, + { + "type": "endpoint", + "key": "cancelVectorStoreFileBatch", + "path": "cancelBatch" + }, + { + "type": "endpoint", + "key": "listFilesInVectorStoreBatch", + "path": "listBatchFiles" + }, + { + "type": "object", + "key": "VectorStoreFileBatchObject", + "path": "batch-object" + } + ] + }, + { + "id": "containers", + "title": "Containers", + "description": "Create and manage containers for use with the Code Interpreter tool.\n", + "navigationGroup": "containers", + "sections": [ + { + "type": "endpoint", + "key": "CreateContainer", + "path": "createContainers" + }, + { + "type": "endpoint", + "key": "ListContainers", + "path": "listContainers" + }, + { + "type": "endpoint", + "key": "RetrieveContainer", + "path": "retrieveContainer" + }, + { + "type": "endpoint", + "key": "DeleteContainer", + "path": "deleteContainer" + }, + { + "type": "object", + "key": "ContainerResource", + "path": "object" + } + ] + }, + { + "id": "container-files", + "title": "Container Files", + "description": "Create and manage container files for use with the Code Interpreter tool.\n", + "navigationGroup": "containers", + "sections": [ + { + "type": "endpoint", + "key": "CreateContainerFile", + "path": "createContainerFile" + }, + { + "type": "endpoint", + "key": "ListContainerFiles", + "path": "listContainerFiles" + }, + { + "type": "endpoint", + "key": "RetrieveContainerFile", + "path": "retrieveContainerFile" + }, + { + "type": "endpoint", + "key": "RetrieveContainerFileContent", + "path": "retrieveContainerFileContent" + }, + { + "type": "endpoint", + "key": "DeleteContainerFile", + "path": "deleteContainerFile" + }, + { + "type": "object", + "key": "ContainerFileResource", + "path": "object" + } + ] + }, + { + "id": "realtime", + "title": "Realtime", + "description": "Communicate with a multimodal model in real time over low latency interfaces\nlike WebRTC, WebSocket, and SIP. Natively supports speech-to-speech\nas well as text, image, and audio inputs and outputs.\n\n[Learn more about the Realtime API](https://platform.openai.com/docs/guides/realtime).\n", + "navigationGroup": "realtime" + }, + { + "id": "realtime-sessions", + "title": "Session tokens", + "description": "REST API endpoint to generate ephemeral session tokens for use in client-side\napplications.\n", + "navigationGroup": "realtime", + "sections": [ + { + "type": "endpoint", + "key": "create-realtime-client-secret", + "path": "create-realtime-client-secret" + }, + { + "type": "object", + "key": "RealtimeCreateClientSecretResponse", + "path": "create-secret-response" + } + ] + }, + { + "id": "realtime-client-events", + "title": "Client events", + "description": "These are events that the OpenAI Realtime WebSocket server will accept from the client.\n", + "navigationGroup": "realtime", + "sections": [ + { + "type": "object", + "key": "RealtimeClientEventSessionUpdate", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventInputAudioBufferAppend", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventInputAudioBufferCommit", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventInputAudioBufferClear", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventConversationItemCreate", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventConversationItemRetrieve", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventConversationItemTruncate", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventConversationItemDelete", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventResponseCreate", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventResponseCancel", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventTranscriptionSessionUpdate", + "path": "" + }, + { + "type": "object", + "key": "RealtimeClientEventOutputAudioBufferClear", + "path": "" + } + ] + }, + { + "id": "realtime-server-events", + "title": "Server events", + "description": "These are events emitted from the OpenAI Realtime WebSocket server to the client.\n", + "navigationGroup": "realtime", + "sections": [ + { + "type": "object", + "key": "RealtimeServerEventError", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventSessionCreated", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventSessionUpdated", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventTranscriptionSessionCreated", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventConversationItemCreated", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventConversationItemAdded", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventConversationItemDone", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventConversationItemRetrieved", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventConversationItemInputAudioTranscriptionCompleted", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventConversationItemInputAudioTranscriptionDelta", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventConversationItemInputAudioTranscriptionSegment", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventConversationItemInputAudioTranscriptionFailed", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventConversationItemTruncated", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventConversationItemDeleted", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventInputAudioBufferCommitted", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventInputAudioBufferCleared", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventInputAudioBufferSpeechStarted", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventInputAudioBufferSpeechStopped", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventInputAudioBufferTimeoutTriggered", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseCreated", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseDone", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseOutputItemAdded", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseOutputItemDone", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseContentPartAdded", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseContentPartDone", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseTextDelta", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseTextDone", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseAudioTranscriptDelta", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseAudioTranscriptDone", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseAudioDelta", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseAudioDone", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseFunctionCallArgumentsDelta", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseFunctionCallArgumentsDone", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseMCPCallArgumentsDelta", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseMCPCallArgumentsDone", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventMCPListToolsInProgress", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventMCPListToolsCompleted", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventMCPListToolsFailed", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseMCPCallInProgress", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseMCPCallCompleted", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventResponseMCPCallFailed", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventTranscriptionSessionUpdated", + "path": "" + }, + { + "type": "object", + "key": "RealtimeServerEventRateLimitsUpdated", + "path": "" + } + ] + }, + { + "id": "chat", + "title": "Chat Completions", + "description": "The Chat Completions API endpoint will generate a model response from a\nlist of messages comprising a conversation.\n\nRelated guides:\n- [Quickstart](https://platform.openai.com/docs/quickstart?api-mode=chat)\n- [Text inputs and outputs](https://platform.openai.com/docs/guides/text?api-mode=chat)\n- [Image inputs](https://platform.openai.com/docs/guides/images?api-mode=chat)\n- [Audio inputs and outputs](https://platform.openai.com/docs/guides/audio?api-mode=chat)\n- [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs?api-mode=chat)\n- [Function calling](https://platform.openai.com/docs/guides/function-calling?api-mode=chat)\n- [Conversation state](https://platform.openai.com/docs/guides/conversation-state?api-mode=chat)\n\n**Starting a new project?** We recommend trying [Responses](https://platform.openai.com/docs/api-reference/responses)\nto take advantage of the latest OpenAI platform features. Compare\n[Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses).\n", + "navigationGroup": "chat", + "sections": [ + { + "type": "endpoint", + "key": "createChatCompletion", + "path": "create" + }, + { + "type": "endpoint", + "key": "getChatCompletion", + "path": "get" + }, + { + "type": "endpoint", + "key": "getChatCompletionMessages", + "path": "getMessages" + }, + { + "type": "endpoint", + "key": "listChatCompletions", + "path": "list" + }, + { + "type": "endpoint", + "key": "updateChatCompletion", + "path": "update" + }, + { + "type": "endpoint", + "key": "deleteChatCompletion", + "path": "delete" + }, + { + "type": "object", + "key": "CreateChatCompletionResponse", + "path": "object" + }, + { + "type": "object", + "key": "ChatCompletionList", + "path": "list-object" + }, + { + "type": "object", + "key": "ChatCompletionMessageList", + "path": "message-list" + } + ] + }, + { + "id": "chat-streaming", + "title": "Streaming", + "description": "Stream Chat Completions in real time. Receive chunks of completions\nreturned from the model using server-sent events.\n[Learn more](https://platform.openai.com/docs/guides/streaming-responses?api-mode=chat).\n", + "navigationGroup": "chat", + "sections": [ + { + "type": "object", + "key": "CreateChatCompletionStreamResponse", + "path": "streaming" + } + ] + }, + { + "id": "assistants", + "title": "Assistants", + "beta": true, + "description": "Build assistants that can call models and use tools to perform tasks.\n\n[Get started with the Assistants API](https://platform.openai.com/docs/assistants)\n", + "navigationGroup": "assistants", + "sections": [ + { + "type": "endpoint", + "key": "createAssistant", + "path": "createAssistant" + }, + { + "type": "endpoint", + "key": "listAssistants", + "path": "listAssistants" + }, + { + "type": "endpoint", + "key": "getAssistant", + "path": "getAssistant" + }, + { + "type": "endpoint", + "key": "modifyAssistant", + "path": "modifyAssistant" + }, + { + "type": "endpoint", + "key": "deleteAssistant", + "path": "deleteAssistant" + }, + { + "type": "object", + "key": "AssistantObject", + "path": "object" + } + ] + }, + { + "id": "threads", + "title": "Threads", + "beta": true, + "description": "Create threads that assistants can interact with.\n\nRelated guide: [Assistants](https://platform.openai.com/docs/assistants/overview)\n", + "navigationGroup": "assistants", + "sections": [ + { + "type": "endpoint", + "key": "createThread", + "path": "createThread" + }, + { + "type": "endpoint", + "key": "getThread", + "path": "getThread" + }, + { + "type": "endpoint", + "key": "modifyThread", + "path": "modifyThread" + }, + { + "type": "endpoint", + "key": "deleteThread", + "path": "deleteThread" + }, + { + "type": "object", + "key": "ThreadObject", + "path": "object" + } + ] + }, + { + "id": "messages", + "title": "Messages", + "beta": true, + "description": "Create messages within threads\n\nRelated guide: [Assistants](https://platform.openai.com/docs/assistants/overview)\n", + "navigationGroup": "assistants", + "sections": [ + { + "type": "endpoint", + "key": "createMessage", + "path": "createMessage" + }, + { + "type": "endpoint", + "key": "listMessages", + "path": "listMessages" + }, + { + "type": "endpoint", + "key": "getMessage", + "path": "getMessage" + }, + { + "type": "endpoint", + "key": "modifyMessage", + "path": "modifyMessage" + }, + { + "type": "endpoint", + "key": "deleteMessage", + "path": "deleteMessage" + }, + { + "type": "object", + "key": "MessageObject", + "path": "object" + } + ] + }, + { + "id": "runs", + "title": "Runs", + "beta": true, + "description": "Represents an execution run on a thread.\n\nRelated guide: [Assistants](https://platform.openai.com/docs/assistants/overview)\n", + "navigationGroup": "assistants", + "sections": [ + { + "type": "endpoint", + "key": "createRun", + "path": "createRun" + }, + { + "type": "endpoint", + "key": "createThreadAndRun", + "path": "createThreadAndRun" + }, + { + "type": "endpoint", + "key": "listRuns", + "path": "listRuns" + }, + { + "type": "endpoint", + "key": "getRun", + "path": "getRun" + }, + { + "type": "endpoint", + "key": "modifyRun", + "path": "modifyRun" + }, + { + "type": "endpoint", + "key": "submitToolOuputsToRun", + "path": "submitToolOutputs" + }, + { + "type": "endpoint", + "key": "cancelRun", + "path": "cancelRun" + }, + { + "type": "object", + "key": "RunObject", + "path": "object" + } + ] + }, + { + "id": "run-steps", + "title": "Run steps", + "beta": true, + "description": "Represents the steps (model and tool calls) taken during the run.\n\nRelated guide: [Assistants](https://platform.openai.com/docs/assistants/overview)\n", + "navigationGroup": "assistants", + "sections": [ + { + "type": "endpoint", + "key": "listRunSteps", + "path": "listRunSteps" + }, + { + "type": "endpoint", + "key": "getRunStep", + "path": "getRunStep" + }, + { + "type": "object", + "key": "RunStepObject", + "path": "step-object" + } + ] + }, + { + "id": "assistants-streaming", + "title": "Streaming", + "beta": true, + "description": "Stream the result of executing a Run or resuming a Run after submitting tool outputs.\nYou can stream events from the [Create Thread and Run](https://platform.openai.com/docs/api-reference/runs/createThreadAndRun),\n[Create Run](https://platform.openai.com/docs/api-reference/runs/createRun), and [Submit Tool Outputs](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs)\nendpoints by passing `\"stream\": true`. The response will be a [Server-Sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) stream.\nOur Node and Python SDKs provide helpful utilities to make streaming easy. Reference the\n[Assistants API quickstart](https://platform.openai.com/docs/assistants/overview) to learn more.\n", + "navigationGroup": "assistants", + "sections": [ + { + "type": "object", + "key": "MessageDeltaObject", + "path": "message-delta-object" + }, + { + "type": "object", + "key": "RunStepDeltaObject", + "path": "run-step-delta-object" + }, + { + "type": "object", + "key": "AssistantStreamEvent", + "path": "events" + } + ] + }, + { + "id": "administration", + "title": "Administration", + "description": "Programmatically manage your organization.\nThe Audit Logs endpoint provides a log of all actions taken in the organization for security and monitoring purposes.\nTo access these endpoints please generate an Admin API Key through the [API Platform Organization overview](/organization/admin-keys). Admin API keys cannot be used for non-administration endpoints.\nFor best practices on setting up your organization, please refer to this [guide](https://platform.openai.com/docs/guides/production-best-practices#setting-up-your-organization)\n", + "navigationGroup": "administration" + }, + { + "id": "admin-api-keys", + "title": "Admin API Keys", + "description": "Admin API keys enable Organization Owners to programmatically manage various aspects of their organization, including users, projects, and API keys. These keys provide administrative capabilities, such as creating, updating, and deleting users; managing projects; and overseeing API key lifecycles.\n\nKey Features of Admin API Keys:\n\n- User Management: Invite new users, update roles, and remove users from the organization.\n\n- Project Management: Create, update, archive projects, and manage user assignments within projects.\n\n- API Key Oversight: List, retrieve, and delete API keys associated with projects.\n\nOnly Organization Owners have the authority to create and utilize Admin API keys. To manage these keys, Organization Owners can navigate to the Admin Keys section of their API Platform dashboard.\n\nFor direct access to the Admin Keys management page, Organization Owners can use the following link:\n\n[https://platform.openai.com/settings/organization/admin-keys](https://platform.openai.com/settings/organization/admin-keys)\n\nIt's crucial to handle Admin API keys with care due to their elevated permissions. Adhering to best practices, such as regular key rotation and assigning appropriate permissions, enhances security and ensures proper governance within the organization.\n", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "admin-api-keys-list", + "path": "list" + }, + { + "type": "endpoint", + "key": "admin-api-keys-create", + "path": "create" + }, + { + "type": "endpoint", + "key": "admin-api-keys-get", + "path": "listget" + }, + { + "type": "endpoint", + "key": "admin-api-keys-delete", + "path": "delete" + }, + { + "type": "object", + "key": "AdminApiKey", + "path": "object" + } + ] + }, + { + "id": "invite", + "title": "Invites", + "description": "Invite and manage invitations for an organization.", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "list-invites", + "path": "list" + }, + { + "type": "endpoint", + "key": "inviteUser", + "path": "create" + }, + { + "type": "endpoint", + "key": "retrieve-invite", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "delete-invite", + "path": "delete" + }, + { + "type": "object", + "key": "Invite", + "path": "object" + } + ] + }, + { + "id": "users", + "title": "Users", + "description": "Manage users and their role in an organization.\n", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "list-users", + "path": "list" + }, + { + "type": "endpoint", + "key": "modify-user", + "path": "modify" + }, + { + "type": "endpoint", + "key": "retrieve-user", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "delete-user", + "path": "delete" + }, + { + "type": "object", + "key": "User", + "path": "object" + } + ] + }, + { + "id": "projects", + "title": "Projects", + "description": "Manage the projects within an orgnanization includes creation, updating, and archiving or projects.\nThe Default project cannot be archived.\n", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "list-projects", + "path": "list" + }, + { + "type": "endpoint", + "key": "create-project", + "path": "create" + }, + { + "type": "endpoint", + "key": "retrieve-project", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "modify-project", + "path": "modify" + }, + { + "type": "endpoint", + "key": "archive-project", + "path": "archive" + }, + { + "type": "object", + "key": "Project", + "path": "object" + } + ] + }, + { + "id": "project-users", + "title": "Project users", + "description": "Manage users within a project, including adding, updating roles, and removing users.\n", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "list-project-users", + "path": "list" + }, + { + "type": "endpoint", + "key": "create-project-user", + "path": "create" + }, + { + "type": "endpoint", + "key": "retrieve-project-user", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "modify-project-user", + "path": "modify" + }, + { + "type": "endpoint", + "key": "delete-project-user", + "path": "delete" + }, + { + "type": "object", + "key": "ProjectUser", + "path": "object" + } + ] + }, + { + "id": "project-service-accounts", + "title": "Project service accounts", + "description": "Manage service accounts within a project. A service account is a bot user that is not associated with a user.\nIf a user leaves an organization, their keys and membership in projects will no longer work. Service accounts\ndo not have this limitation. However, service accounts can also be deleted from a project.\n", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "list-project-service-accounts", + "path": "list" + }, + { + "type": "endpoint", + "key": "create-project-service-account", + "path": "create" + }, + { + "type": "endpoint", + "key": "retrieve-project-service-account", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "delete-project-service-account", + "path": "delete" + }, + { + "type": "object", + "key": "ProjectServiceAccount", + "path": "object" + } + ] + }, + { + "id": "project-api-keys", + "title": "Project API keys", + "description": "Manage API keys for a given project. Supports listing and deleting keys for users.\nThis API does not allow issuing keys for users, as users need to authorize themselves to generate keys.\n", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "list-project-api-keys", + "path": "list" + }, + { + "type": "endpoint", + "key": "retrieve-project-api-key", + "path": "retrieve" + }, + { + "type": "endpoint", + "key": "delete-project-api-key", + "path": "delete" + }, + { + "type": "object", + "key": "ProjectApiKey", + "path": "object" + } + ] + }, + { + "id": "project-rate-limits", + "title": "Project rate limits", + "description": "Manage rate limits per model for projects. Rate limits may be configured to be equal to or lower than the organization's rate limits.\n", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "list-project-rate-limits", + "path": "list" + }, + { + "type": "endpoint", + "key": "update-project-rate-limits", + "path": "update" + }, + { + "type": "object", + "key": "ProjectRateLimit", + "path": "object" + } + ] + }, + { + "id": "audit-logs", + "title": "Audit logs", + "description": "Logs of user actions and configuration changes within this organization.\nTo log events, an Organization Owner must activate logging in the [Data Controls Settings](/settings/organization/data-controls/data-retention).\nOnce activated, for security reasons, logging cannot be deactivated.\n", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "list-audit-logs", + "path": "list" + }, + { + "type": "object", + "key": "AuditLog", + "path": "object" + } + ] + }, + { + "id": "usage", + "title": "Usage", + "description": "The **Usage API** provides detailed insights into your activity across the OpenAI API. It also includes a separate [Costs endpoint](https://platform.openai.com/docs/api-reference/usage/costs), which offers visibility into your spend, breaking down consumption by invoice line items and project IDs.\n\nWhile the Usage API delivers granular usage data, it may not always reconcile perfectly with the Costs due to minor differences in how usage and spend are recorded. For financial purposes, we recommend using the [Costs endpoint](https://platform.openai.com/docs/api-reference/usage/costs) or the [Costs tab](/settings/organization/usage) in the Usage Dashboard, which will reconcile back to your billing invoice.\n", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "usage-completions", + "path": "completions" + }, + { + "type": "object", + "key": "UsageCompletionsResult", + "path": "completions_object" + }, + { + "type": "endpoint", + "key": "usage-embeddings", + "path": "embeddings" + }, + { + "type": "object", + "key": "UsageEmbeddingsResult", + "path": "embeddings_object" + }, + { + "type": "endpoint", + "key": "usage-moderations", + "path": "moderations" + }, + { + "type": "object", + "key": "UsageModerationsResult", + "path": "moderations_object" + }, + { + "type": "endpoint", + "key": "usage-images", + "path": "images" + }, + { + "type": "object", + "key": "UsageImagesResult", + "path": "images_object" + }, + { + "type": "endpoint", + "key": "usage-audio-speeches", + "path": "audio_speeches" + }, + { + "type": "object", + "key": "UsageAudioSpeechesResult", + "path": "audio_speeches_object" + }, + { + "type": "endpoint", + "key": "usage-audio-transcriptions", + "path": "audio_transcriptions" + }, + { + "type": "object", + "key": "UsageAudioTranscriptionsResult", + "path": "audio_transcriptions_object" + }, + { + "type": "endpoint", + "key": "usage-vector-stores", + "path": "vector_stores" + }, + { + "type": "object", + "key": "UsageVectorStoresResult", + "path": "vector_stores_object" + }, + { + "type": "endpoint", + "key": "usage-code-interpreter-sessions", + "path": "code_interpreter_sessions" + }, + { + "type": "object", + "key": "UsageCodeInterpreterSessionsResult", + "path": "code_interpreter_sessions_object" + }, + { + "type": "endpoint", + "key": "usage-costs", + "path": "costs" + }, + { + "type": "object", + "key": "CostsResult", + "path": "costs_object" + } + ] + }, + { + "id": "certificates", + "beta": true, + "title": "Certificates", + "description": "Manage Mutual TLS certificates across your organization and projects.\n\n[Learn more about Mutual TLS.](https://help.openai.com/en/articles/10876024-openai-mutual-tls-beta-program)\n", + "navigationGroup": "administration", + "sections": [ + { + "type": "endpoint", + "key": "uploadCertificate", + "path": "uploadCertificate" + }, + { + "type": "endpoint", + "key": "getCertificate", + "path": "getCertificate" + }, + { + "type": "endpoint", + "key": "modifyCertificate", + "path": "modifyCertificate" + }, + { + "type": "endpoint", + "key": "deleteCertificate", + "path": "deleteCertificate" + }, + { + "type": "endpoint", + "key": "listOrganizationCertificates", + "path": "listOrganizationCertificates" + }, + { + "type": "endpoint", + "key": "listProjectCertificates", + "path": "listProjectCertificates" + }, + { + "type": "endpoint", + "key": "activateOrganizationCertificates", + "path": "activateOrganizationCertificates" + }, + { + "type": "endpoint", + "key": "deactivateOrganizationCertificates", + "path": "deactivateOrganizationCertificates" + }, + { + "type": "endpoint", + "key": "activateProjectCertificates", + "path": "activateProjectCertificates" + }, + { + "type": "endpoint", + "key": "deactivateProjectCertificates", + "path": "deactivateProjectCertificates" + }, + { + "type": "object", + "key": "Certificate", + "path": "object" + } + ] + }, + { + "id": "completions", + "title": "Completions", + "legacy": true, + "navigationGroup": "legacy", + "description": "Given a prompt, the model will return one or more predicted completions along with the probabilities of alternative tokens at each position. Most developer should use our [Chat Completions API](https://platform.openai.com/docs/guides/text-generation#text-generation-models) to leverage our best and newest models.\n", + "sections": [ + { + "type": "endpoint", + "key": "createCompletion", + "path": "create" + }, + { + "type": "object", + "key": "CreateCompletionResponse", + "path": "object" + } + ] + } + ] + } +} \ No newline at end of file diff --git a/website/public/openapi/openapi.json b/website/public/openapi/openapi.json index 75a60d208..976199abf 100644 --- a/website/public/openapi/openapi.json +++ b/website/public/openapi/openapi.json @@ -1,21 +1,112 @@ { "openapi": "3.1.0", - "info": { "title": "👋Jan API", "version": "0.3.14" }, + "info": { + "title": "👋Jan API", + "description": "OpenAI-compatible API for local inference with Jan. Run AI models locally with complete privacy using llama.cpp's high-performance inference engine. Supports GGUF models with CPU and GPU acceleration. No authentication required for local usage.", + "version": "0.3.14", + "contact": { + "name": "Jan Support", + "url": "https://jan.ai/support", + "email": "support@jan.ai" + }, + "license": { + "name": "Apache 2.0", + "url": "https://github.com/janhq/jan/blob/main/LICENSE" + } + }, + "servers": [ + { + "url": "http://127.0.0.1:1337", + "description": "Local Jan Server (Default IP)" + }, + { + "url": "http://localhost:1337", + "description": "Local Jan Server (localhost)" + }, + { + "url": "http://localhost:8080", + "description": "Local Jan Server (Alternative Port)" + } + ], + "tags": [ + { + "name": "Models", + "description": "List and describe available models" + }, + { + "name": "Chat", + "description": "Chat completion endpoints for conversational AI" + }, + { + "name": "Completions", + "description": "Text completion endpoints for generating text" + }, + { + "name": "Extras", + "description": "Additional utility endpoints for tokenization and text processing" + } + ], "paths": { "/v1/completions": { "post": { - "tags": ["OpenAI V1"], - "summary": "Completion", - "operationId": "create_completion_v1_completions_post", + "tags": ["Completions"], + "summary": "Create completion", + "description": "Creates a completion for the provided prompt and parameters. This endpoint is compatible with OpenAI's completions API.", + "operationId": "create_completion", "requestBody": { + "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateCompletionRequest" + }, + "examples": { + "basic": { + "summary": "Basic Completion", + "description": "Simple text completion example", + "value": { + "model": "gemma-2-2b-it-Q8_0", + "prompt": "Once upon a time", + "max_tokens": 50, + "temperature": 0.7 + } + }, + "creative": { + "summary": "Creative Writing", + "description": "Generate creative content with higher temperature", + "value": { + "model": "gemma-2-2b-it-Q8_0", + "prompt": "Write a short poem about coding:", + "max_tokens": 150, + "temperature": 1, + "top_p": 0.95 + } + }, + "code": { + "summary": "Code Generation", + "description": "Generate code with lower temperature for accuracy", + "value": { + "model": "gemma-2-2b-it-Q8_0", + "prompt": "# Python function to calculate fibonacci\ndef fibonacci(n):", + "max_tokens": 200, + "temperature": 0.3, + "stop": ["\n\n", "def ", "class "] + } + }, + "streaming": { + "summary": "Streaming Response", + "description": "Stream tokens as they are generated", + "value": { + "model": "gemma-2-2b-it-Q8_0", + "prompt": "Explain quantum computing in simple terms:", + "max_tokens": 300, + "temperature": 0.7, + "stream": true + } + } } } - }, - "required": true + } }, "responses": { "200": { @@ -23,19 +114,24 @@ "content": { "application/json": { "schema": { - "anyOf": [ - { "$ref": "#/components/schemas/CreateCompletionResponse" }, - { "type": "string" }, - { "$ref": "#/components/schemas/CreateCompletionResponse" } - ], - "title": "Completion response, when stream=False" + "$ref": "#/components/schemas/CreateCompletionResponse" + } + } + } + }, + "202": { + "description": "Accepted - Request is being processed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateCompletionResponse" } }, "text/event-stream": { "schema": { "type": "string", - "title": "Server Side Streaming response, when stream=True. See SSE format: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format", - "example": "data: {... see CreateCompletionResponse ...} \\n\\n data: ... \\n\\n ... data: [DONE]" + "format": "binary", + "description": "Server-sent events stream for streaming responses" } } } @@ -44,150 +140,126 @@ "description": "Validation Error", "content": { "application/json": { - "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + "schema": { + "$ref": "#/components/schemas/ValidationError" + } } } } - }, - "security": [{ "HTTPBearer": [] }] - } - }, - "/v1/embeddings": { - "post": { - "tags": ["OpenAI V1"], - "summary": "Embedding", - "operationId": "create_embedding_v1_embeddings_post", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateEmbeddingRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successful Response", - "content": { "application/json": { "schema": {} } } - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/HTTPValidationError" } - } - } - } - }, - "security": [{ "HTTPBearer": [] }] + } } }, "/v1/chat/completions": { "post": { - "tags": ["OpenAI V1"], - "summary": "Chat", - "operationId": "create_chat_completion_v1_chat_completions_post", + "tags": ["Chat"], + "summary": "Create chat completion", + "description": "Creates a model response for the given chat conversation. This endpoint is compatible with OpenAI's chat completions API.", + "operationId": "create_chat_completion", "requestBody": { + "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateChatCompletionRequest" }, "examples": { - "normal": { - "summary": "Chat Completion", + "simple": { + "summary": "Simple Chat", + "description": "Basic question and answer", "value": { - "model": "gpt-3.5-turbo", + "model": "gemma-2-2b-it-Q8_0", "messages": [ - { - "role": "system", - "content": "You are a helpful assistant." - }, { "role": "user", "content": "What is the capital of France?" } - ] + ], + "max_tokens": 100, + "temperature": 0.7 + } + }, + "system": { + "summary": "With System Message", + "description": "Chat with system instructions", + "value": { + "model": "gemma-2-2b-it-Q8_0", + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant that speaks like a pirate." + }, + { + "role": "user", + "content": "Tell me about the weather today." + } + ], + "max_tokens": 150, + "temperature": 0.8 + } + }, + "conversation": { + "summary": "Multi-turn Conversation", + "description": "Extended conversation with context", + "value": { + "model": "gemma-2-2b-it-Q8_0", + "messages": [ + { + "role": "system", + "content": "You are a knowledgeable AI assistant." + }, + { + "role": "user", + "content": "What is machine learning?" + }, + { + "role": "assistant", + "content": "Machine learning is a subset of artificial intelligence that enables systems to learn and improve from experience without being explicitly programmed." + }, + { + "role": "user", + "content": "Can you give me a simple example?" + } + ], + "max_tokens": 200, + "temperature": 0.7 + } + }, + "streaming": { + "summary": "Streaming Chat", + "description": "Stream the response token by token", + "value": { + "model": "gemma-2-2b-it-Q8_0", + "messages": [ + { + "role": "user", + "content": "Write a haiku about programming" + } + ], + "stream": true, + "temperature": 0.9 } }, "json_mode": { - "summary": "JSON Mode", + "summary": "JSON Response", + "description": "Request structured JSON output", "value": { - "model": "gpt-3.5-turbo", + "model": "gemma-2-2b-it-Q8_0", "messages": [ - { - "role": "system", - "content": "You are a helpful assistant." - }, { "role": "user", - "content": "Who won the world series in 2020" + "content": "List 3 programming languages with their main use cases in JSON format" } ], - "response_format": { "type": "json_object" } - } - }, - "tool_calling": { - "summary": "Tool Calling", - "value": { - "model": "gpt-3.5-turbo", - "messages": [ - { - "role": "system", - "content": "You are a helpful assistant." - }, - { - "role": "user", - "content": "Extract Jason is 30 years old." - } - ], - "tools": [ - { - "type": "function", - "function": { - "name": "User", - "description": "User record", - "parameters": { - "type": "object", - "properties": { - "name": { "type": "string" }, - "age": { "type": "number" } - }, - "required": ["name", "age"] - } - } - } - ], - "tool_choice": { - "type": "function", - "function": { "name": "User" } + "max_tokens": 200, + "temperature": 0.5, + "response_format": { + "type": "json_object" } } - }, - "logprobs": { - "summary": "Logprobs", - "value": { - "model": "gpt-3.5-turbo", - "messages": [ - { - "role": "system", - "content": "You are a helpful assistant." - }, - { - "role": "user", - "content": "What is the capital of France?" - } - ], - "logprobs": true, - "top_logprobs": 10 - } } } } - }, - "required": true + } }, "responses": { "200": { @@ -195,23 +267,31 @@ "content": { "application/json": { "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/CreateChatCompletionResponse" - }, - { "type": "string" }, - { - "$ref": "#/components/schemas/CreateChatCompletionResponse" - } - ], - "title": "Completion response, when stream=False" + "$ref": "#/components/schemas/CreateChatCompletionResponse" } }, "text/event-stream": { "schema": { "type": "string", - "title": "Server Side Streaming response, when stream=TrueSee SSE format: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format", - "example": "data: {... see CreateChatCompletionResponse ...} \\n\\n data: ... \\n\\n ... data: [DONE]" + "format": "binary", + "description": "Server-sent events stream for streaming responses" + } + } + } + }, + "202": { + "description": "Accepted - Request is being processed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateChatCompletionResponse" + } + }, + "text/event-stream": { + "schema": { + "type": "string", + "format": "binary", + "description": "Server-sent events stream for streaming responses" } } } @@ -220,44 +300,83 @@ "description": "Validation Error", "content": { "application/json": { - "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + "schema": { + "$ref": "#/components/schemas/ValidationError" + } } } } - }, - "security": [{ "HTTPBearer": [] }] + } } }, "/v1/models": { "get": { - "tags": ["OpenAI V1"], - "summary": "Models", - "operationId": "get_models_v1_models_get", + "tags": ["Models"], + "summary": "List available models", + "description": "Lists the currently available models and provides basic information about each one such as the owner and availability.", + "operationId": "list_models", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { - "schema": { "$ref": "#/components/schemas/ModelList" } + "schema": { + "$ref": "#/components/schemas/ModelList" + }, + "example": { + "object": "list", + "data": [ + { + "id": "gemma-2-2b-it-Q8_0", + "object": "model", + "created": 1686935002, + "owned_by": "jan" + }, + { + "id": "llama-3.1-8b-instruct-Q4_K_M", + "object": "model", + "created": 1686935002, + "owned_by": "jan" + }, + { + "id": "mistral-7b-instruct-v0.3-Q4_K_M", + "object": "model", + "created": 1686935002, + "owned_by": "jan" + }, + { + "id": "phi-3-mini-4k-instruct-Q4_K_M", + "object": "model", + "created": 1686935002, + "owned_by": "jan" + } + ] + } } } } - }, - "security": [{ "HTTPBearer": [] }] + } } }, "/extras/tokenize": { "post": { "tags": ["Extras"], - "summary": "Tokenize", - "operationId": "tokenize_extras_tokenize_post", + "summary": "Tokenize text", + "description": "Convert text input into tokens using the model's tokenizer.", + "operationId": "tokenize", "requestBody": { + "required": true, "content": { "application/json": { - "schema": { "$ref": "#/components/schemas/TokenizeInputRequest" } + "schema": { + "$ref": "#/components/schemas/TokenizeRequest" + }, + "example": { + "input": "Hello, world!", + "model": "gemma-2-2b-it-Q8_0" + } } - }, - "required": true + } }, "responses": { "200": { @@ -265,73 +384,36 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TokenizeInputResponse" + "$ref": "#/components/schemas/TokenizeResponse" + }, + "example": { + "tokens": [15339, 11, 1917, 0] } } } - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/HTTPValidationError" } - } - } } - }, - "security": [{ "HTTPBearer": [] }] + } } }, "/extras/tokenize/count": { "post": { "tags": ["Extras"], - "summary": "Tokenize Count", - "operationId": "count_query_tokens_extras_tokenize_count_post", - "requestBody": { - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/TokenizeInputRequest" } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/TokenizeInputCountResponse" - } - } - } - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/HTTPValidationError" } - } - } - } - }, - "security": [{ "HTTPBearer": [] }] - } - }, - "/extras/detokenize": { - "post": { - "tags": ["Extras"], - "summary": "Detokenize", - "operationId": "detokenize_extras_detokenize_post", + "summary": "Count tokens", + "description": "Count the number of tokens in the provided text.", + "operationId": "count_tokens", "requestBody": { + "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DetokenizeInputRequest" + "$ref": "#/components/schemas/TokenizeRequest" + }, + "example": { + "input": "How many tokens does this text have?", + "model": "gemma-2-2b-it-Q8_0" } } - }, - "required": true + } }, "responses": { "200": { @@ -339,1121 +421,95 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DetokenizeInputResponse" + "$ref": "#/components/schemas/TokenCountResponse" + }, + "example": { + "count": 8 } } } - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/HTTPValidationError" } - } - } } - }, - "security": [{ "HTTPBearer": [] }] + } } } }, "components": { "schemas": { - "ChatCompletionFunction": { + "TokenizeRequest": { + "type": "object", "properties": { - "name": { "type": "string", "title": "Name" }, - "description": { "type": "string", "title": "Description" }, - "parameters": { - "additionalProperties": { - "anyOf": [ - { "type": "integer" }, - { "type": "string" }, - { "type": "boolean" }, - { "items": {}, "type": "array" }, - { "additionalProperties": true, "type": "object" }, - { "type": "null" } - ] - }, - "type": "object", - "title": "Parameters" - } - }, - "type": "object", - "required": ["name", "parameters"], - "title": "ChatCompletionFunction" - }, - "ChatCompletionLogprobToken": { - "properties": { - "token": { "type": "string", "title": "Token" }, - "logprob": { "type": "number", "title": "Logprob" }, - "bytes": { - "anyOf": [ - { "items": { "type": "integer" }, "type": "array" }, - { "type": "null" } - ], - "title": "Bytes" - }, - "top_logprobs": { - "items": { - "$ref": "#/components/schemas/ChatCompletionTopLogprobToken" - }, - "type": "array", - "title": "Top Logprobs" - } - }, - "type": "object", - "required": ["token", "logprob", "bytes", "top_logprobs"], - "title": "ChatCompletionLogprobToken" - }, - "ChatCompletionLogprobs": { - "properties": { - "content": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/ChatCompletionLogprobToken" - }, - "type": "array" - }, - { "type": "null" } - ], - "title": "Content" - }, - "refusal": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/ChatCompletionLogprobToken" - }, - "type": "array" - }, - { "type": "null" } - ], - "title": "Refusal" - } - }, - "type": "object", - "required": ["content", "refusal"], - "title": "ChatCompletionLogprobs" - }, - "ChatCompletionMessageToolCall": { - "properties": { - "id": { "type": "string", "title": "Id" }, - "type": { "type": "string", "const": "function", "title": "Type" }, - "function": { - "$ref": "#/components/schemas/ChatCompletionMessageToolCallFunction" - } - }, - "type": "object", - "required": ["id", "type", "function"], - "title": "ChatCompletionMessageToolCall" - }, - "ChatCompletionMessageToolCallFunction": { - "properties": { - "name": { "type": "string", "title": "Name" }, - "arguments": { "type": "string", "title": "Arguments" } - }, - "type": "object", - "required": ["name", "arguments"], - "title": "ChatCompletionMessageToolCallFunction" - }, - "ChatCompletionNamedToolChoice": { - "properties": { - "type": { "type": "string", "const": "function", "title": "Type" }, - "function": { - "$ref": "#/components/schemas/ChatCompletionNamedToolChoiceFunction" - } - }, - "type": "object", - "required": ["type", "function"], - "title": "ChatCompletionNamedToolChoice" - }, - "ChatCompletionNamedToolChoiceFunction": { - "properties": { "name": { "type": "string", "title": "Name" } }, - "type": "object", - "required": ["name"], - "title": "ChatCompletionNamedToolChoiceFunction" - }, - "ChatCompletionRequestAssistantMessage": { - "properties": { - "role": { "type": "string", "const": "assistant", "title": "Role" }, - "content": { "type": "string", "title": "Content" }, - "tool_calls": { - "items": { - "$ref": "#/components/schemas/ChatCompletionMessageToolCall" - }, - "type": "array", - "title": "Tool Calls" - }, - "function_call": { - "$ref": "#/components/schemas/ChatCompletionRequestAssistantMessageFunctionCall" - } - }, - "type": "object", - "required": ["role"], - "title": "ChatCompletionRequestAssistantMessage" - }, - "ChatCompletionRequestAssistantMessageFunctionCall": { - "properties": { - "name": { "type": "string", "title": "Name" }, - "arguments": { "type": "string", "title": "Arguments" } - }, - "type": "object", - "required": ["name", "arguments"], - "title": "ChatCompletionRequestAssistantMessageFunctionCall" - }, - "ChatCompletionRequestFunctionCallOption": { - "properties": { "name": { "type": "string", "title": "Name" } }, - "type": "object", - "required": ["name"], - "title": "ChatCompletionRequestFunctionCallOption" - }, - "ChatCompletionRequestFunctionMessage": { - "properties": { - "role": { "type": "string", "const": "function", "title": "Role" }, - "content": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Content" - }, - "name": { "type": "string", "title": "Name" } - }, - "type": "object", - "required": ["role", "content", "name"], - "title": "ChatCompletionRequestFunctionMessage" - }, - "ChatCompletionRequestMessageContentPartImage": { - "properties": { - "type": { "type": "string", "const": "image_url", "title": "Type" }, - "image_url": { - "anyOf": [ - { "type": "string" }, - { - "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartImageImageUrl" - } - ], - "title": "Image Url" - } - }, - "type": "object", - "required": ["type", "image_url"], - "title": "ChatCompletionRequestMessageContentPartImage" - }, - "ChatCompletionRequestMessageContentPartImageImageUrl": { - "properties": { - "url": { "type": "string", "title": "Url" }, - "detail": { - "type": "string", - "enum": ["auto", "low", "high"], - "title": "Detail" - } - }, - "type": "object", - "required": ["url"], - "title": "ChatCompletionRequestMessageContentPartImageImageUrl" - }, - "ChatCompletionRequestMessageContentPartText": { - "properties": { - "type": { "type": "string", "const": "text", "title": "Type" }, - "text": { "type": "string", "title": "Text" } - }, - "type": "object", - "required": ["type", "text"], - "title": "ChatCompletionRequestMessageContentPartText" - }, - "ChatCompletionRequestResponseFormat": { - "properties": { - "type": { - "type": "string", - "enum": ["text", "json_object"], - "title": "Type" - }, - "schema": { - "anyOf": [ - { "type": "integer" }, - { "type": "string" }, - { "type": "boolean" }, - { "items": {}, "type": "array" }, - { "additionalProperties": true, "type": "object" }, - { "type": "null" } - ], - "title": "Schema" - } - }, - "type": "object", - "required": ["type"], - "title": "ChatCompletionRequestResponseFormat" - }, - "ChatCompletionRequestSystemMessage": { - "properties": { - "role": { "type": "string", "const": "system", "title": "Role" }, - "content": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Content" - } - }, - "type": "object", - "required": ["role", "content"], - "title": "ChatCompletionRequestSystemMessage" - }, - "ChatCompletionRequestToolMessage": { - "properties": { - "role": { "type": "string", "const": "tool", "title": "Role" }, - "content": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Content" - }, - "tool_call_id": { "type": "string", "title": "Tool Call Id" } - }, - "type": "object", - "required": ["role", "content", "tool_call_id"], - "title": "ChatCompletionRequestToolMessage" - }, - "ChatCompletionRequestUserMessage": { - "properties": { - "role": { "type": "string", "const": "user", "title": "Role" }, - "content": { - "anyOf": [ - { "type": "string" }, - { - "items": { - "anyOf": [ - { - "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartText" - }, - { - "$ref": "#/components/schemas/ChatCompletionRequestMessageContentPartImage" - } - ] - }, - "type": "array" - }, - { "type": "null" } - ], - "title": "Content" - } - }, - "type": "object", - "required": ["role", "content"], - "title": "ChatCompletionRequestUserMessage" - }, - "ChatCompletionResponseChoice": { - "properties": { - "index": { "type": "integer", "title": "Index" }, - "message": { - "$ref": "#/components/schemas/ChatCompletionResponseMessage" - }, - "logprobs": { - "anyOf": [ - { "$ref": "#/components/schemas/ChatCompletionLogprobs" }, - { "type": "null" } - ] - }, - "finish_reason": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Finish Reason" - } - }, - "type": "object", - "required": ["index", "message", "logprobs", "finish_reason"], - "title": "ChatCompletionResponseChoice" - }, - "ChatCompletionResponseFunctionCall": { - "properties": { - "name": { "type": "string", "title": "Name" }, - "arguments": { "type": "string", "title": "Arguments" } - }, - "type": "object", - "required": ["name", "arguments"], - "title": "ChatCompletionResponseFunctionCall" - }, - "ChatCompletionResponseMessage": { - "properties": { - "content": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Content" - }, - "tool_calls": { - "items": { - "$ref": "#/components/schemas/ChatCompletionMessageToolCall" - }, - "type": "array", - "title": "Tool Calls" - }, - "role": { - "type": "string", - "enum": ["assistant", "function"], - "title": "Role" - }, - "function_call": { - "$ref": "#/components/schemas/ChatCompletionResponseFunctionCall" - } - }, - "type": "object", - "required": ["content", "role"], - "title": "ChatCompletionResponseMessage" - }, - "ChatCompletionTool": { - "properties": { - "type": { "type": "string", "const": "function", "title": "Type" }, - "function": { - "$ref": "#/components/schemas/ChatCompletionToolFunction" - } - }, - "type": "object", - "required": ["type", "function"], - "title": "ChatCompletionTool" - }, - "ChatCompletionToolFunction": { - "properties": { - "name": { "type": "string", "title": "Name" }, - "description": { "type": "string", "title": "Description" }, - "parameters": { - "additionalProperties": { - "anyOf": [ - { "type": "integer" }, - { "type": "string" }, - { "type": "boolean" }, - { "items": {}, "type": "array" }, - { "additionalProperties": true, "type": "object" }, - { "type": "null" } - ] - }, - "type": "object", - "title": "Parameters" - } - }, - "type": "object", - "required": ["name", "parameters"], - "title": "ChatCompletionToolFunction" - }, - "ChatCompletionTopLogprobToken": { - "properties": { - "token": { "type": "string", "title": "Token" }, - "logprob": { "type": "number", "title": "Logprob" }, - "bytes": { - "anyOf": [ - { "items": { "type": "integer" }, "type": "array" }, - { "type": "null" } - ], - "title": "Bytes" - } - }, - "type": "object", - "required": ["token", "logprob", "bytes"], - "title": "ChatCompletionTopLogprobToken" - }, - "CompletionChoice": { - "properties": { - "text": { "type": "string", "title": "Text" }, - "index": { "type": "integer", "title": "Index" }, - "logprobs": { - "anyOf": [ - { "$ref": "#/components/schemas/CompletionLogprobs" }, - { "type": "null" } - ] - }, - "finish_reason": { - "anyOf": [ - { "type": "string", "enum": ["stop", "length"] }, - { "type": "null" } - ], - "title": "Finish Reason" - } - }, - "type": "object", - "required": ["text", "index", "logprobs", "finish_reason"], - "title": "CompletionChoice" - }, - "CompletionLogprobs": { - "properties": { - "text_offset": { - "items": { "type": "integer" }, - "type": "array", - "title": "Text Offset" - }, - "token_logprobs": { - "items": { "anyOf": [{ "type": "number" }, { "type": "null" }] }, - "type": "array", - "title": "Token Logprobs" - }, - "tokens": { - "items": { "type": "string" }, - "type": "array", - "title": "Tokens" - }, - "top_logprobs": { - "items": { - "anyOf": [ - { - "additionalProperties": { "type": "number" }, - "type": "object" - }, - { "type": "null" } - ] - }, - "type": "array", - "title": "Top Logprobs" - } - }, - "type": "object", - "required": ["text_offset", "token_logprobs", "tokens", "top_logprobs"], - "title": "CompletionLogprobs" - }, - "CompletionUsage": { - "properties": { - "prompt_tokens": { "type": "integer", "title": "Prompt Tokens" }, - "completion_tokens": { - "type": "integer", - "title": "Completion Tokens" - }, - "total_tokens": { "type": "integer", "title": "Total Tokens" } - }, - "type": "object", - "required": ["prompt_tokens", "completion_tokens", "total_tokens"], - "title": "CompletionUsage" - }, - "CreateChatCompletionRequest": { - "properties": { - "messages": { - "items": { - "anyOf": [ - { - "$ref": "#/components/schemas/ChatCompletionRequestSystemMessage" - }, - { - "$ref": "#/components/schemas/ChatCompletionRequestUserMessage" - }, - { - "$ref": "#/components/schemas/ChatCompletionRequestAssistantMessage" - }, - { - "$ref": "#/components/schemas/ChatCompletionRequestToolMessage" - }, - { - "$ref": "#/components/schemas/ChatCompletionRequestFunctionMessage" - } - ] - }, - "type": "array", - "title": "Messages", - "description": "A list of messages to generate completions for.", - "default": [] - }, - "functions": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/ChatCompletionFunction" - }, - "type": "array" - }, - { "type": "null" } - ], - "title": "Functions", - "description": "A list of functions to apply to the generated completions." - }, - "function_call": { - "anyOf": [ - { "type": "string", "enum": ["none", "auto"] }, - { - "$ref": "#/components/schemas/ChatCompletionRequestFunctionCallOption" - }, - { "type": "null" } - ], - "title": "Function Call", - "description": "A function to apply to the generated completions." - }, - "tools": { - "anyOf": [ - { - "items": { "$ref": "#/components/schemas/ChatCompletionTool" }, - "type": "array" - }, - { "type": "null" } - ], - "title": "Tools", - "description": "A list of tools to apply to the generated completions." - }, - "tool_choice": { - "anyOf": [ - { "type": "string", "enum": ["none", "auto", "required"] }, - { "$ref": "#/components/schemas/ChatCompletionNamedToolChoice" }, - { "type": "null" } - ], - "title": "Tool Choice", - "description": "A tool to apply to the generated completions." - }, - "max_tokens": { - "anyOf": [{ "type": "integer" }, { "type": "null" }], - "title": "Max Tokens", - "description": "The maximum number of tokens to generate. Defaults to inf" - }, - "min_tokens": { - "type": "integer", - "minimum": 0.0, - "title": "Min Tokens", - "description": "The minimum number of tokens to generate. It may return fewer tokens if another condition is met (e.g. max_tokens, stop).", - "default": 0 - }, - "logprobs": { - "anyOf": [{ "type": "boolean" }, { "type": "null" }], - "title": "Logprobs", - "description": "Whether to output the logprobs or not. Default is True", - "default": false - }, - "top_logprobs": { - "anyOf": [ - { "type": "integer", "minimum": 0.0 }, - { "type": "null" } - ], - "title": "Top Logprobs", - "description": "The number of logprobs to generate. If None, no logprobs are generated. logprobs need to set to True." - }, - "temperature": { - "type": "number", - "title": "Temperature", - "description": "Adjust the randomness of the generated text.\n\nTemperature is a hyperparameter that controls the randomness of the generated text. It affects the probability distribution of the model's output tokens. A higher temperature (e.g., 1.5) makes the output more random and creative, while a lower temperature (e.g., 0.5) makes the output more focused, deterministic, and conservative. The default value is 0.8, which provides a balance between randomness and determinism. At the extreme, a temperature of 0 will always pick the most likely next token, leading to identical outputs in each run.", - "default": 0.8 - }, - "top_p": { - "type": "number", - "maximum": 1.0, - "minimum": 0.0, - "title": "Top P", - "description": "Limit the next token selection to a subset of tokens with a cumulative probability above a threshold P.\n\nTop-p sampling, also known as nucleus sampling, is another text generation method that selects the next token from a subset of tokens that together have a cumulative probability of at least p. This method provides a balance between diversity and quality by considering both the probabilities of tokens and the number of tokens to sample from. A higher value for top_p (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text.", - "default": 0.95 - }, - "min_p": { - "type": "number", - "maximum": 1.0, - "minimum": 0.0, - "title": "Min P", - "description": "Sets a minimum base probability threshold for token selection.\n\nThe Min-P sampling method was designed as an alternative to Top-P, and aims to ensure a balance of quality and variety. The parameter min_p represents the minimum probability for a token to be considered, relative to the probability of the most likely token. For example, with min_p=0.05 and the most likely token having a probability of 0.9, logits with a value less than 0.045 are filtered out.", - "default": 0.05 - }, - "stop": { - "anyOf": [ - { "type": "string" }, - { "items": { "type": "string" }, "type": "array" }, - { "type": "null" } - ], - "title": "Stop", - "description": "A list of tokens at which to stop generation. If None, no stop tokens are used." - }, - "stream": { - "type": "boolean", - "title": "Stream", - "description": "Whether to stream the results as they are generated. Useful for chatbots.", - "default": false - }, - "presence_penalty": { - "anyOf": [ - { "type": "number", "maximum": 2.0, "minimum": -2.0 }, - { "type": "null" } - ], - "title": "Presence Penalty", - "description": "Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.", - "default": 0.0 - }, - "frequency_penalty": { - "anyOf": [ - { "type": "number", "maximum": 2.0, "minimum": -2.0 }, - { "type": "null" } - ], - "title": "Frequency Penalty", - "description": "Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.", - "default": 0.0 - }, - "logit_bias": { - "anyOf": [ - { - "additionalProperties": { "type": "number" }, - "type": "object" - }, - { "type": "null" } - ], - "title": "Logit Bias" - }, - "seed": { - "anyOf": [{ "type": "integer" }, { "type": "null" }], - "title": "Seed" - }, - "response_format": { - "anyOf": [ - { - "$ref": "#/components/schemas/ChatCompletionRequestResponseFormat" - }, - { "type": "null" } - ] - }, - "model": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Model", - "description": "The model to use for generating completions." - }, - "n": { - "anyOf": [{ "type": "integer" }, { "type": "null" }], - "title": "N", - "default": 1 - }, - "user": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "User" - }, - "top_k": { - "type": "integer", - "minimum": 0.0, - "title": "Top K", - "description": "Limit the next token selection to the K most probable tokens.\n\nTop-k sampling is a text generation method that selects the next token only from the top k most likely tokens predicted by the model. It helps reduce the risk of generating low-probability or nonsensical tokens, but it may also limit the diversity of the output. A higher value for top_k (e.g., 100) will consider more tokens and lead to more diverse text, while a lower value (e.g., 10) will focus on the most probable tokens and generate more conservative text.", - "default": 40 - }, - "repeat_penalty": { - "type": "number", - "minimum": 0.0, - "title": "Repeat Penalty", - "description": "A penalty applied to each token that is already generated. This helps prevent the model from repeating itself.\n\nRepeat penalty is a hyperparameter used to penalize the repetition of token sequences during text generation. It helps prevent the model from generating repetitive or monotonous text. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient.", - "default": 1.1 - }, - "logit_bias_type": { - "anyOf": [ - { "type": "string", "enum": ["input_ids", "tokens"] }, - { "type": "null" } - ], - "title": "Logit Bias Type" - }, - "mirostat_mode": { - "type": "integer", - "maximum": 2.0, - "minimum": 0.0, - "title": "Mirostat Mode", - "description": "Enable Mirostat constant-perplexity algorithm of the specified version (1 or 2; 0 = disabled)", - "default": 0 - }, - "mirostat_tau": { - "type": "number", - "maximum": 10.0, - "minimum": 0.0, - "title": "Mirostat Tau", - "description": "Mirostat target entropy, i.e. the target perplexity - lower values produce focused and coherent text, larger values produce more diverse and less coherent text", - "default": 5.0 - }, - "mirostat_eta": { - "type": "number", - "maximum": 1.0, - "minimum": 0.001, - "title": "Mirostat Eta", - "description": "Mirostat learning rate", - "default": 0.1 - }, - "grammar": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Grammar" - } - }, - "type": "object", - "title": "CreateChatCompletionRequest", - "examples": [ - { - "messages": [ - { "content": "You are a helpful assistant.", "role": "system" }, - { "content": "What is the capital of France?", "role": "user" } - ] - } - ] - }, - "CreateChatCompletionResponse": { - "properties": { - "id": { "type": "string", "title": "Id" }, - "object": { - "type": "string", - "const": "chat.completion", - "title": "Object" - }, - "created": { "type": "integer", "title": "Created" }, - "model": { "type": "string", "title": "Model" }, - "choices": { - "items": { - "$ref": "#/components/schemas/ChatCompletionResponseChoice" - }, - "type": "array", - "title": "Choices" - }, - "usage": { "$ref": "#/components/schemas/CompletionUsage" } - }, - "type": "object", - "required": ["id", "object", "created", "model", "choices", "usage"], - "title": "CreateChatCompletionResponse" - }, - "CreateCompletionRequest": { - "properties": { - "prompt": { - "anyOf": [ - { "type": "string" }, - { "items": { "type": "string" }, "type": "array" } - ], - "title": "Prompt", - "description": "The prompt to generate completions for.", - "default": "" - }, - "suffix": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Suffix", - "description": "A suffix to append to the generated text. If None, no suffix is appended. Useful for chatbots." - }, - "max_tokens": { - "anyOf": [ - { "type": "integer", "minimum": 0.0 }, - { "type": "null" } - ], - "title": "Max Tokens", - "description": "The maximum number of tokens to generate.", - "default": 16 - }, - "min_tokens": { - "type": "integer", - "minimum": 0.0, - "title": "Min Tokens", - "description": "The minimum number of tokens to generate. It may return fewer tokens if another condition is met (e.g. max_tokens, stop).", - "default": 0 - }, - "temperature": { - "type": "number", - "title": "Temperature", - "description": "Adjust the randomness of the generated text.\n\nTemperature is a hyperparameter that controls the randomness of the generated text. It affects the probability distribution of the model's output tokens. A higher temperature (e.g., 1.5) makes the output more random and creative, while a lower temperature (e.g., 0.5) makes the output more focused, deterministic, and conservative. The default value is 0.8, which provides a balance between randomness and determinism. At the extreme, a temperature of 0 will always pick the most likely next token, leading to identical outputs in each run.", - "default": 0.8 - }, - "top_p": { - "type": "number", - "maximum": 1.0, - "minimum": 0.0, - "title": "Top P", - "description": "Limit the next token selection to a subset of tokens with a cumulative probability above a threshold P.\n\nTop-p sampling, also known as nucleus sampling, is another text generation method that selects the next token from a subset of tokens that together have a cumulative probability of at least p. This method provides a balance between diversity and quality by considering both the probabilities of tokens and the number of tokens to sample from. A higher value for top_p (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text.", - "default": 0.95 - }, - "min_p": { - "type": "number", - "maximum": 1.0, - "minimum": 0.0, - "title": "Min P", - "description": "Sets a minimum base probability threshold for token selection.\n\nThe Min-P sampling method was designed as an alternative to Top-P, and aims to ensure a balance of quality and variety. The parameter min_p represents the minimum probability for a token to be considered, relative to the probability of the most likely token. For example, with min_p=0.05 and the most likely token having a probability of 0.9, logits with a value less than 0.045 are filtered out.", - "default": 0.05 - }, - "echo": { - "type": "boolean", - "title": "Echo", - "description": "Whether to echo the prompt in the generated text. Useful for chatbots.", - "default": false - }, - "stop": { - "anyOf": [ - { "type": "string" }, - { "items": { "type": "string" }, "type": "array" }, - { "type": "null" } - ], - "title": "Stop", - "description": "A list of tokens at which to stop generation. If None, no stop tokens are used." - }, - "stream": { - "type": "boolean", - "title": "Stream", - "description": "Whether to stream the results as they are generated. Useful for chatbots.", - "default": false - }, - "logprobs": { - "anyOf": [ - { "type": "integer", "minimum": 0.0 }, - { "type": "null" } - ], - "title": "Logprobs", - "description": "The number of logprobs to generate. If None, no logprobs are generated." - }, - "presence_penalty": { - "anyOf": [ - { "type": "number", "maximum": 2.0, "minimum": -2.0 }, - { "type": "null" } - ], - "title": "Presence Penalty", - "description": "Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.", - "default": 0.0 - }, - "frequency_penalty": { - "anyOf": [ - { "type": "number", "maximum": 2.0, "minimum": -2.0 }, - { "type": "null" } - ], - "title": "Frequency Penalty", - "description": "Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.", - "default": 0.0 - }, - "logit_bias": { - "anyOf": [ - { - "additionalProperties": { "type": "number" }, - "type": "object" - }, - { "type": "null" } - ], - "title": "Logit Bias" - }, - "seed": { - "anyOf": [{ "type": "integer" }, { "type": "null" }], - "title": "Seed" - }, - "model": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Model", - "description": "The model to use for generating completions." - }, - "n": { - "anyOf": [{ "type": "integer" }, { "type": "null" }], - "title": "N", - "default": 1 - }, - "best_of": { - "anyOf": [{ "type": "integer" }, { "type": "null" }], - "title": "Best Of", - "default": 1 - }, - "user": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "User" - }, - "top_k": { - "type": "integer", - "minimum": 0.0, - "title": "Top K", - "description": "Limit the next token selection to the K most probable tokens.\n\nTop-k sampling is a text generation method that selects the next token only from the top k most likely tokens predicted by the model. It helps reduce the risk of generating low-probability or nonsensical tokens, but it may also limit the diversity of the output. A higher value for top_k (e.g., 100) will consider more tokens and lead to more diverse text, while a lower value (e.g., 10) will focus on the most probable tokens and generate more conservative text.", - "default": 40 - }, - "repeat_penalty": { - "type": "number", - "minimum": 0.0, - "title": "Repeat Penalty", - "description": "A penalty applied to each token that is already generated. This helps prevent the model from repeating itself.\n\nRepeat penalty is a hyperparameter used to penalize the repetition of token sequences during text generation. It helps prevent the model from generating repetitive or monotonous text. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient.", - "default": 1.1 - }, - "logit_bias_type": { - "anyOf": [ - { "type": "string", "enum": ["input_ids", "tokens"] }, - { "type": "null" } - ], - "title": "Logit Bias Type" - }, - "mirostat_mode": { - "type": "integer", - "maximum": 2.0, - "minimum": 0.0, - "title": "Mirostat Mode", - "description": "Enable Mirostat constant-perplexity algorithm of the specified version (1 or 2; 0 = disabled)", - "default": 0 - }, - "mirostat_tau": { - "type": "number", - "maximum": 10.0, - "minimum": 0.0, - "title": "Mirostat Tau", - "description": "Mirostat target entropy, i.e. the target perplexity - lower values produce focused and coherent text, larger values produce more diverse and less coherent text", - "default": 5.0 - }, - "mirostat_eta": { - "type": "number", - "maximum": 1.0, - "minimum": 0.001, - "title": "Mirostat Eta", - "description": "Mirostat learning rate", - "default": 0.1 - }, - "grammar": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Grammar" - } - }, - "type": "object", - "title": "CreateCompletionRequest", - "examples": [ - { - "prompt": "\n\n### Instructions:\nWhat is the capital of France?\n\n### Response:\n", - "stop": ["\n", "###"] - } - ] - }, - "CreateCompletionResponse": { - "properties": { - "id": { "type": "string", "title": "Id" }, - "object": { - "type": "string", - "const": "text_completion", - "title": "Object" - }, - "created": { "type": "integer", "title": "Created" }, - "model": { "type": "string", "title": "Model" }, - "choices": { - "items": { "$ref": "#/components/schemas/CompletionChoice" }, - "type": "array", - "title": "Choices" - }, - "usage": { "$ref": "#/components/schemas/CompletionUsage" } - }, - "type": "object", - "required": ["id", "object", "created", "model", "choices"], - "title": "CreateCompletionResponse" - }, - "CreateEmbeddingRequest": { - "properties": { - "model": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Model", - "description": "The model to use for generating completions." - }, "input": { - "anyOf": [ - { "type": "string" }, - { "items": { "type": "string" }, "type": "array" } - ], - "title": "Input", - "description": "The input to embed." - }, - "user": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "User" - } - }, - "type": "object", - "required": ["input"], - "title": "CreateEmbeddingRequest", - "examples": [{ "input": "The food was delicious and the waiter..." }] - }, - "DetokenizeInputRequest": { - "properties": { - "model": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Model", - "description": "The model to use for generating completions." - }, - "tokens": { - "items": { "type": "integer" }, - "type": "array", - "title": "Tokens", - "description": "A list of toekns to detokenize." - } - }, - "type": "object", - "required": ["tokens"], - "title": "DetokenizeInputRequest", - "example": [{ "tokens": [123, 321, 222] }] - }, - "DetokenizeInputResponse": { - "properties": { - "text": { "type": "string", - "title": "Text", - "description": "The detokenized text." + "description": "The text to tokenize" + }, + "model": { + "type": "string", + "description": "The model to use for tokenization", + "enum": [ + "gemma-2-2b-it-Q8_0", + "llama-3.1-8b-instruct-Q4_K_M", + "mistral-7b-instruct-v0.3-Q4_K_M", + "phi-3-mini-4k-instruct-Q4_K_M" + ] } }, - "type": "object", - "required": ["text"], - "title": "DetokenizeInputResponse", - "example": { "text": "How many tokens in this query?" } + "required": ["input"] }, - "HTTPValidationError": { + "TokenizeResponse": { + "type": "object", "properties": { - "detail": { - "items": { "$ref": "#/components/schemas/ValidationError" }, + "tokens": { "type": "array", - "title": "Detail" + "items": { + "type": "integer" + }, + "description": "Array of token IDs" } }, - "type": "object", - "title": "HTTPValidationError" + "required": ["tokens"] }, - "ModelData": { - "properties": { - "id": { "type": "string", "title": "Id" }, - "object": { "type": "string", "const": "model", "title": "Object" }, - "owned_by": { "type": "string", "title": "Owned By" }, - "permissions": { - "items": { "type": "string" }, - "type": "array", - "title": "Permissions" - } - }, + "TokenCountResponse": { "type": "object", - "required": ["id", "object", "owned_by", "permissions"], - "title": "ModelData" - }, - "ModelList": { - "properties": { - "object": { "type": "string", "const": "list", "title": "Object" }, - "data": { - "items": { "$ref": "#/components/schemas/ModelData" }, - "type": "array", - "title": "Data" - } - }, - "type": "object", - "required": ["object", "data"], - "title": "ModelList" - }, - "TokenizeInputCountResponse": { "properties": { "count": { "type": "integer", - "title": "Count", - "description": "The number of tokens in the input." + "description": "Number of tokens" } }, - "type": "object", - "required": ["count"], - "title": "TokenizeInputCountResponse", - "example": { "count": 5 } - }, - "TokenizeInputRequest": { - "properties": { - "model": { - "anyOf": [{ "type": "string" }, { "type": "null" }], - "title": "Model", - "description": "The model to use for generating completions." - }, - "input": { - "type": "string", - "title": "Input", - "description": "The input to tokenize." - } - }, - "type": "object", - "required": ["input"], - "title": "TokenizeInputRequest", - "examples": [{ "input": "How many tokens in this query?" }] - }, - "TokenizeInputResponse": { - "properties": { - "tokens": { - "items": { "type": "integer" }, - "type": "array", - "title": "Tokens", - "description": "A list of tokens." - } - }, - "type": "object", - "required": ["tokens"], - "title": "TokenizeInputResponse", - "example": { "tokens": [123, 321, 222] } - }, - "ValidationError": { - "properties": { - "loc": { - "items": { "anyOf": [{ "type": "string" }, { "type": "integer" }] }, - "type": "array", - "title": "Location" - }, - "msg": { "type": "string", "title": "Message" }, - "type": { "type": "string", "title": "Error Type" } - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError" + "required": ["count"] } }, - "securitySchemes": { "HTTPBearer": { "type": "http", "scheme": "bearer" } } + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT", + "description": "Optional: Enter your API key if authentication is enabled. The Bearer prefix will be added automatically." + } + } + }, + "x-jan-local-features": { + "engine": "llama.cpp", + "features": [ + "GGUF model support", + "CPU and GPU acceleration", + "Quantized model support (Q4, Q5, Q8)", + "Metal acceleration on macOS", + "CUDA support on NVIDIA GPUs", + "ROCm support on AMD GPUs", + "AVX/AVX2/AVX512 optimizations", + "Memory-mapped model loading" + ], + "privacy": { + "local_processing": true, + "no_telemetry": true, + "offline_capable": true + }, + "model_formats": ["GGUF", "GGML"], + "default_settings": { + "context_length": 4096, + "batch_size": 512, + "threads": "auto" + } } } diff --git a/website/public/scripts/inject-navigation.js b/website/public/scripts/inject-navigation.js new file mode 100644 index 000000000..823d82773 --- /dev/null +++ b/website/public/scripts/inject-navigation.js @@ -0,0 +1,119 @@ +// Navigation injection script for Jan documentation +// This script adds navigation links to regular docs pages (not API reference pages) + +;(function () { + // Navigation configuration for Jan docs + const JAN_NAV_CONFIG = { + // Product navigation links - easy to extend for multiple products + links: [ + { + href: '/', + text: 'Docs', + isActive: (path) => + path === '/' || (path.startsWith('/') && !path.startsWith('/api')), + }, + { + href: '/api', + text: 'API Reference', + isActive: (path) => path.startsWith('/api'), + }, + ], + + // Pages that have their own navigation (don't inject nav) + excludePaths: ['/api-reference/', '/api/'], + } + + // Add navigation to docs pages with retry logic + function addNavigation(retries = 0) { + const currentPath = window.location.pathname + + // Skip if page has its own navigation + const shouldSkipNav = JAN_NAV_CONFIG.excludePaths.some((path) => + currentPath.startsWith(path) + ) + if (shouldSkipNav) return + + const header = document.querySelector('.header') + const siteTitle = document.querySelector('.site-title') + const existingNav = document.querySelector('.custom-nav-links') + + if (header && siteTitle && !existingNav) { + // Find the right container for nav links + const searchElement = header.querySelector('[class*="search"]') + const flexContainer = header.querySelector('.sl-flex') + const targetContainer = flexContainer || header + + if (targetContainer) { + // Create navigation container + const nav = document.createElement('nav') + nav.className = 'custom-nav-links' + nav.setAttribute('aria-label', 'Product Navigation') + + // Create links from configuration + JAN_NAV_CONFIG.links.forEach((link) => { + const a = document.createElement('a') + a.href = link.href + a.textContent = link.text + a.className = 'nav-link' + + // Set active state + if (link.isActive(currentPath)) { + a.setAttribute('aria-current', 'page') + } + + nav.appendChild(a) + }) + + // Insert navigation safely + if (searchElement && targetContainer.contains(searchElement)) { + targetContainer.insertBefore(nav, searchElement) + } else { + // Find site title and insert after it + if (siteTitle && targetContainer.contains(siteTitle)) { + siteTitle.insertAdjacentElement('afterend', nav) + } else { + targetContainer.appendChild(nav) + } + } + } else if (retries < 5) { + setTimeout(() => addNavigation(retries + 1), 500) + } + } else if (retries < 5) { + setTimeout(() => addNavigation(retries + 1), 500) + } + } + + // Initialize navigation injection + function initNavigation() { + // Update logo link to jan.ai + const logoLink = document.querySelector('a[href="/"]') + if (logoLink && logoLink.getAttribute('href') === '/') { + logoLink.href = 'https://jan.ai' + } + + // Start navigation injection + if (document.readyState === 'loading') { + setTimeout(() => addNavigation(), 1000) + } else { + addNavigation() + } + } + + // Run when DOM is ready + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', initNavigation) + } else { + initNavigation() + } + + // Handle page navigation in SPA-like environments + let lastUrl = location.href + new MutationObserver(() => { + const url = location.href + if (url !== lastUrl) { + lastUrl = url + // Re-run navigation injection after navigation + setTimeout(() => addNavigation(), 100) + } + }).observe(document, { subtree: true, childList: true }) +})() diff --git a/website/public/styles/navigation.css b/website/public/styles/navigation.css new file mode 100644 index 000000000..00ff6694e --- /dev/null +++ b/website/public/styles/navigation.css @@ -0,0 +1,48 @@ +/* Navigation links for regular docs pages */ +.custom-nav-links { + display: inline-flex; + align-items: center; + gap: 0.5rem; + margin: 0 1rem; +} + +.custom-nav-links .nav-link { + display: inline-flex; + align-items: center; + padding: 0.5rem 0.875rem; + border-radius: 0.375rem; + color: var(--sl-color-gray-2); + text-decoration: none; + font-weight: 500; + font-size: 0.875rem; + transition: all 0.2s ease; + white-space: nowrap; +} + +.custom-nav-links .nav-link:hover { + color: var(--sl-color-text); + background: var(--sl-color-gray-6); +} + +.custom-nav-links .nav-link[aria-current="page"] { + color: var(--sl-color-text); + background: var(--sl-color-gray-6); +} + +/* Responsive design */ +@media (max-width: 768px) { + .custom-nav-links { + display: none; + } +} + +@media (min-width: 768px) and (max-width: 1024px) { + .custom-nav-links { + margin: 0 0.5rem; + } + + .custom-nav-links .nav-link { + padding: 0.375rem 0.625rem; + font-size: 0.8125rem; + } +} diff --git a/website/scripts/conditional-cloud-spec.js b/website/scripts/conditional-cloud-spec.js new file mode 100644 index 000000000..febba969d --- /dev/null +++ b/website/scripts/conditional-cloud-spec.js @@ -0,0 +1,187 @@ +#!/usr/bin/env node + +/** + * Conditional Cloud Spec Generator + * + * This script conditionally runs the cloud spec generation based on environment variables. + * It's designed to be used in CI/CD pipelines to control when the spec should be updated. + * + * Environment variables: + * - SKIP_CLOUD_SPEC_UPDATE: Skip cloud spec generation entirely + * - FORCE_UPDATE: Force update even if skip is set + * - CI: Detect if running in CI environment + */ + +import { spawn } from 'child_process' +import fs from 'fs' +import path from 'path' +import { fileURLToPath } from 'url' + +const __filename = fileURLToPath(import.meta.url) +const __dirname = path.dirname(__filename) + +// Configuration +const CONFIG = { + CLOUD_SPEC_PATH: path.join(__dirname, '../public/openapi/cloud-openapi.json'), + GENERATOR_SCRIPT: path.join(__dirname, 'generate-cloud-spec.js'), + FALLBACK_SPEC_PATH: path.join(__dirname, '../public/openapi/openapi.json'), +} + +// Color codes for console output +const colors = { + reset: '\x1b[0m', + green: '\x1b[32m', + yellow: '\x1b[33m', + cyan: '\x1b[36m', + gray: '\x1b[90m', +} + +function log(message, type = 'info') { + const prefix = { + info: `${colors.cyan}ℹ️ `, + skip: `${colors.gray}⏭️ `, + run: `${colors.green}▶️ `, + warning: `${colors.yellow}⚠️ `, + }[type] || '' + console.log(`${prefix}${message}${colors.reset}`) +} + +async function shouldRunGenerator() { + // Check environment variables + const skipUpdate = process.env.SKIP_CLOUD_SPEC_UPDATE === 'true' + const forceUpdate = process.env.FORCE_UPDATE === 'true' + const isCI = process.env.CI === 'true' + const isPR = process.env.GITHUB_EVENT_NAME === 'pull_request' + + // Force update overrides all + if (forceUpdate) { + log('Force update requested', 'info') + return true + } + + // Skip if explicitly requested + if (skipUpdate) { + log('Cloud spec update skipped (SKIP_CLOUD_SPEC_UPDATE=true)', 'skip') + return false + } + + // Skip in PR builds to avoid unnecessary API calls + if (isPR) { + log('Cloud spec update skipped (Pull Request build)', 'skip') + return false + } + + // Check if cloud spec already exists + const specExists = fs.existsSync(CONFIG.CLOUD_SPEC_PATH) + + // In CI, only update if spec doesn't exist or if scheduled/manual trigger + if (isCI) { + const isScheduled = process.env.GITHUB_EVENT_NAME === 'schedule' + const isManualWithUpdate = + process.env.GITHUB_EVENT_NAME === 'workflow_dispatch' && + process.env.UPDATE_CLOUD_SPEC === 'true' + + if (isScheduled || isManualWithUpdate) { + log('Cloud spec update triggered (scheduled/manual)', 'info') + return true + } + + if (!specExists) { + log('Cloud spec missing, will attempt to generate', 'warning') + return true + } + + log('Cloud spec update skipped (CI build, spec exists)', 'skip') + return false + } + + // For local development, update if spec is missing or older than 24 hours + if (!specExists) { + log('Cloud spec missing, generating...', 'info') + return true + } + + // Check if spec is older than 24 hours + const stats = fs.statSync(CONFIG.CLOUD_SPEC_PATH) + const ageInHours = (Date.now() - stats.mtime.getTime()) / (1000 * 60 * 60) + + if (ageInHours > 24) { + log(`Cloud spec is ${Math.round(ageInHours)} hours old, updating...`, 'info') + return true + } + + log(`Cloud spec is recent (${Math.round(ageInHours)} hours old), skipping update`, 'skip') + return false +} + +async function runGenerator() { + return new Promise((resolve, reject) => { + log('Running cloud spec generator...', 'run') + + const child = spawn('bun', [CONFIG.GENERATOR_SCRIPT], { + stdio: 'inherit', + env: { ...process.env } + }) + + child.on('close', (code) => { + if (code === 0) { + resolve() + } else { + reject(new Error(`Generator exited with code ${code}`)) + } + }) + + child.on('error', (err) => { + reject(err) + }) + }) +} + +async function ensureFallback() { + // If cloud spec doesn't exist but fallback does, copy it + if (!fs.existsSync(CONFIG.CLOUD_SPEC_PATH) && fs.existsSync(CONFIG.FALLBACK_SPEC_PATH)) { + log('Using fallback spec as cloud spec', 'warning') + fs.copyFileSync(CONFIG.FALLBACK_SPEC_PATH, CONFIG.CLOUD_SPEC_PATH) + return true + } + return false +} + +async function main() { + try { + // Determine if we should run the generator + const shouldRun = await shouldRunGenerator() + + if (shouldRun) { + try { + await runGenerator() + log('Cloud spec generation completed', 'info') + } catch (error) { + log(`Cloud spec generation failed: ${error.message}`, 'warning') + + // Try to use fallback + if (ensureFallback()) { + log('Fallback spec used successfully', 'info') + } else { + log('No fallback available, build may fail', 'warning') + // Don't exit with error - let the build continue + } + } + } else { + // Ensure we have at least a fallback spec + if (!fs.existsSync(CONFIG.CLOUD_SPEC_PATH)) { + ensureFallback() + } + } + + // Always exit successfully to not break the build + process.exit(0) + } catch (error) { + console.error('Unexpected error:', error) + // Even on error, try to continue the build + process.exit(0) + } +} + +// Run the script +main() diff --git a/website/scripts/fix-local-spec-complete.js b/website/scripts/fix-local-spec-complete.js new file mode 100644 index 000000000..ed315098a --- /dev/null +++ b/website/scripts/fix-local-spec-complete.js @@ -0,0 +1,746 @@ +#!/usr/bin/env node + +import fs from 'fs' +import path from 'path' +import { fileURLToPath } from 'url' + +const __filename = fileURLToPath(import.meta.url) +const __dirname = path.dirname(__filename) + +const cloudSpecPath = path.join( + __dirname, + '../public/openapi/cloud-openapi.json' +) +const outputPath = path.join(__dirname, '../public/openapi/openapi.json') + +console.log( + '🔧 Fixing Local OpenAPI Spec with Complete Examples and Schemas...' +) + +// Read cloud spec as a reference +const cloudSpec = JSON.parse(fs.readFileSync(cloudSpecPath, 'utf8')) + +// Convert Swagger 2.0 to OpenAPI 3.0 format for paths +function convertSwaggerPathToOpenAPI3(swaggerPath) { + const openApiPath = {} + + Object.keys(swaggerPath || {}).forEach((method) => { + if (typeof swaggerPath[method] === 'object') { + openApiPath[method] = { + ...swaggerPath[method], + // Convert parameters + parameters: swaggerPath[method].parameters?.filter( + (p) => p.in !== 'body' + ), + // Convert body parameter to requestBody + requestBody: swaggerPath[method].parameters?.find( + (p) => p.in === 'body' + ) + ? { + required: true, + content: { + 'application/json': { + schema: swaggerPath[method].parameters.find( + (p) => p.in === 'body' + ).schema, + }, + }, + } + : undefined, + // Convert responses + responses: {}, + } + + // Convert responses + Object.keys(swaggerPath[method].responses || {}).forEach((statusCode) => { + const response = swaggerPath[method].responses[statusCode] + openApiPath[method].responses[statusCode] = { + description: response.description, + content: response.schema + ? { + 'application/json': { + schema: response.schema, + }, + } + : undefined, + } + }) + } + }) + + return openApiPath +} + +// Create comprehensive local spec +const localSpec = { + openapi: '3.1.0', + info: { + title: 'Jan API', + description: + "OpenAI-compatible API for local inference with Jan. Run AI models locally with complete privacy using llama.cpp's high-performance inference engine. Supports GGUF models with CPU and GPU acceleration. No authentication required for local usage.", + version: '0.3.14', + contact: { + name: 'Jan Support', + url: 'https://jan.ai/support', + email: 'support@jan.ai', + }, + license: { + name: 'Apache 2.0', + url: 'https://github.com/janhq/jan/blob/main/LICENSE', + }, + }, + servers: [ + { + url: 'http://127.0.0.1:1337', + description: 'Local Jan Server (Default IP)', + }, + { + url: 'http://localhost:1337', + description: 'Local Jan Server (localhost)', + }, + { + url: 'http://localhost:8080', + description: 'Local Jan Server (Alternative Port)', + }, + ], + tags: [ + { + name: 'Models', + description: 'List and describe available models', + }, + { + name: 'Chat', + description: 'Chat completion endpoints for conversational AI', + }, + { + name: 'Completions', + description: 'Text completion endpoints for generating text', + }, + { + name: 'Extras', + description: + 'Additional utility endpoints for tokenization and text processing', + }, + ], + paths: {}, + components: { + schemas: {}, + securitySchemes: { + bearerAuth: { + type: 'http', + scheme: 'bearer', + bearerFormat: 'JWT', + description: + 'Optional: Enter your API key if authentication is enabled. The Bearer prefix will be added automatically.', + }, + }, + }, +} + +// Local model examples +const LOCAL_MODELS = [ + 'gemma-2-2b-it-Q8_0', + 'llama-3.1-8b-instruct-Q4_K_M', + 'mistral-7b-instruct-v0.3-Q4_K_M', + 'phi-3-mini-4k-instruct-Q4_K_M', +] + +// Add completions endpoint with rich examples +localSpec.paths['/v1/completions'] = { + post: { + tags: ['Completions'], + summary: 'Create completion', + description: + "Creates a completion for the provided prompt and parameters. This endpoint is compatible with OpenAI's completions API.", + operationId: 'create_completion', + requestBody: { + required: true, + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/CreateCompletionRequest', + }, + examples: { + basic: { + summary: 'Basic Completion', + description: 'Simple text completion example', + value: { + model: LOCAL_MODELS[0], + prompt: 'Once upon a time', + max_tokens: 50, + temperature: 0.7, + }, + }, + creative: { + summary: 'Creative Writing', + description: 'Generate creative content with higher temperature', + value: { + model: LOCAL_MODELS[0], + prompt: 'Write a short poem about coding:', + max_tokens: 150, + temperature: 1.0, + top_p: 0.95, + }, + }, + code: { + summary: 'Code Generation', + description: 'Generate code with lower temperature for accuracy', + value: { + model: LOCAL_MODELS[0], + prompt: + '# Python function to calculate fibonacci\ndef fibonacci(n):', + max_tokens: 200, + temperature: 0.3, + stop: ['\n\n', 'def ', 'class '], + }, + }, + streaming: { + summary: 'Streaming Response', + description: 'Stream tokens as they are generated', + value: { + model: LOCAL_MODELS[0], + prompt: 'Explain quantum computing in simple terms:', + max_tokens: 300, + temperature: 0.7, + stream: true, + }, + }, + }, + }, + }, + }, + responses: { + 200: { + description: 'Successful Response', + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/CreateCompletionResponse', + }, + }, + }, + }, + 202: { + description: 'Accepted - Request is being processed', + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/CreateCompletionResponse', + }, + }, + 'text/event-stream': { + schema: { + type: 'string', + format: 'binary', + description: 'Server-sent events stream for streaming responses', + }, + }, + }, + }, + 422: { + description: 'Validation Error', + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/ValidationError', + }, + }, + }, + }, + }, + }, +} + +// Add chat completions endpoint with rich examples +localSpec.paths['/v1/chat/completions'] = { + post: { + tags: ['Chat'], + summary: 'Create chat completion', + description: + "Creates a model response for the given chat conversation. This endpoint is compatible with OpenAI's chat completions API.", + operationId: 'create_chat_completion', + requestBody: { + required: true, + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/CreateChatCompletionRequest', + }, + examples: { + simple: { + summary: 'Simple Chat', + description: 'Basic question and answer', + value: { + model: LOCAL_MODELS[0], + messages: [ + { + role: 'user', + content: 'What is the capital of France?', + }, + ], + max_tokens: 100, + temperature: 0.7, + }, + }, + system: { + summary: 'With System Message', + description: 'Chat with system instructions', + value: { + model: LOCAL_MODELS[0], + messages: [ + { + role: 'system', + content: + 'You are a helpful assistant that speaks like a pirate.', + }, + { + role: 'user', + content: 'Tell me about the weather today.', + }, + ], + max_tokens: 150, + temperature: 0.8, + }, + }, + conversation: { + summary: 'Multi-turn Conversation', + description: 'Extended conversation with context', + value: { + model: LOCAL_MODELS[0], + messages: [ + { + role: 'system', + content: 'You are a knowledgeable AI assistant.', + }, + { + role: 'user', + content: 'What is machine learning?', + }, + { + role: 'assistant', + content: + 'Machine learning is a subset of artificial intelligence that enables systems to learn and improve from experience without being explicitly programmed.', + }, + { + role: 'user', + content: 'Can you give me a simple example?', + }, + ], + max_tokens: 200, + temperature: 0.7, + }, + }, + streaming: { + summary: 'Streaming Chat', + description: 'Stream the response token by token', + value: { + model: LOCAL_MODELS[0], + messages: [ + { + role: 'user', + content: 'Write a haiku about programming', + }, + ], + stream: true, + temperature: 0.9, + }, + }, + json_mode: { + summary: 'JSON Response', + description: 'Request structured JSON output', + value: { + model: LOCAL_MODELS[0], + messages: [ + { + role: 'user', + content: + 'List 3 programming languages with their main use cases in JSON format', + }, + ], + max_tokens: 200, + temperature: 0.5, + response_format: { + type: 'json_object', + }, + }, + }, + }, + }, + }, + }, + responses: { + 200: { + description: 'Successful Response', + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/CreateChatCompletionResponse', + }, + }, + 'text/event-stream': { + schema: { + type: 'string', + format: 'binary', + description: 'Server-sent events stream for streaming responses', + }, + }, + }, + }, + 202: { + description: 'Accepted - Request is being processed', + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/CreateChatCompletionResponse', + }, + }, + 'text/event-stream': { + schema: { + type: 'string', + format: 'binary', + description: 'Server-sent events stream for streaming responses', + }, + }, + }, + }, + 422: { + description: 'Validation Error', + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/ValidationError', + }, + }, + }, + }, + }, + }, +} + +// Add models endpoint +localSpec.paths['/v1/models'] = { + get: { + tags: ['Models'], + summary: 'List available models', + description: + 'Lists the currently available models and provides basic information about each one such as the owner and availability.', + operationId: 'list_models', + responses: { + 200: { + description: 'Successful Response', + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/ModelList', + }, + example: { + object: 'list', + data: LOCAL_MODELS.map((id) => ({ + id: id, + object: 'model', + created: 1686935002, + owned_by: 'jan', + })), + }, + }, + }, + }, + }, + }, +} + +// Add tokenization endpoints +localSpec.paths['/extras/tokenize'] = { + post: { + tags: ['Extras'], + summary: 'Tokenize text', + description: "Convert text input into tokens using the model's tokenizer.", + operationId: 'tokenize', + requestBody: { + required: true, + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/TokenizeRequest', + }, + example: { + input: 'Hello, world!', + model: LOCAL_MODELS[0], + }, + }, + }, + }, + responses: { + 200: { + description: 'Successful Response', + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/TokenizeResponse', + }, + example: { + tokens: [15339, 11, 1917, 0], + }, + }, + }, + }, + }, + }, +} + +localSpec.paths['/extras/tokenize/count'] = { + post: { + tags: ['Extras'], + summary: 'Count tokens', + description: 'Count the number of tokens in the provided text.', + operationId: 'count_tokens', + requestBody: { + required: true, + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/TokenizeRequest', + }, + example: { + input: 'How many tokens does this text have?', + model: LOCAL_MODELS[0], + }, + }, + }, + }, + responses: { + 200: { + description: 'Successful Response', + content: { + 'application/json': { + schema: { + $ref: '#/components/schemas/TokenCountResponse', + }, + example: { + count: 8, + }, + }, + }, + }, + }, + }, +} + +// Copy ALL necessary schemas from cloud spec +const schemasToInclude = [ + // Request/Response schemas + 'CreateChatCompletionRequest', + 'CreateChatCompletionResponse', + 'CreateCompletionRequest', + 'CreateCompletionResponse', + 'ChatCompletionRequestMessage', + 'ChatCompletionRequestSystemMessage', + 'ChatCompletionRequestUserMessage', + 'ChatCompletionRequestAssistantMessage', + 'ChatCompletionResponseMessage', + 'ChatCompletionResponseChoice', + 'CompletionChoice', + 'CompletionUsage', + 'ModelList', + 'ModelData', + 'ValidationError', + + // Additional message types + 'ChatCompletionRequestFunctionMessage', + 'ChatCompletionRequestToolMessage', + 'ChatCompletionRequestMessageContentPart', + 'ChatCompletionRequestMessageContentPartText', + 'ChatCompletionRequestMessageContentPartImage', + + // Function calling + 'ChatCompletionFunction', + 'ChatCompletionFunctionCall', + 'ChatCompletionTool', + 'ChatCompletionToolCall', + 'ChatCompletionNamedToolChoice', + + // Response format + 'ChatCompletionRequestResponseFormat', + + // Logprobs + 'ChatCompletionLogprobs', + 'ChatCompletionLogprobToken', + 'ChatCompletionTopLogprobToken', +] + +// Copy schemas from cloud spec (handle both definitions and schemas) +if (cloudSpec.definitions || cloudSpec.components?.schemas) { + const sourceSchemas = + cloudSpec.definitions || cloudSpec.components?.schemas || {} + + schemasToInclude.forEach((schemaName) => { + if (sourceSchemas[schemaName]) { + localSpec.components.schemas[schemaName] = JSON.parse( + JSON.stringify(sourceSchemas[schemaName]) + ) + } + }) + + // Also copy any schemas that are referenced by the included schemas + const processedSchemas = new Set(schemasToInclude) + const schemasToProcess = [...schemasToInclude] + + while (schemasToProcess.length > 0) { + const currentSchema = schemasToProcess.pop() + const schema = localSpec.components.schemas[currentSchema] + if (!schema) continue + + // Find all $ref references + const schemaString = JSON.stringify(schema) + const refPattern = /#\/(?:definitions|components\/schemas)\/([^"]+)/g + let match + + while ((match = refPattern.exec(schemaString)) !== null) { + const referencedSchema = match[1] + if ( + !processedSchemas.has(referencedSchema) && + sourceSchemas[referencedSchema] + ) { + localSpec.components.schemas[referencedSchema] = JSON.parse( + JSON.stringify(sourceSchemas[referencedSchema]) + ) + processedSchemas.add(referencedSchema) + schemasToProcess.push(referencedSchema) + } + } + } +} + +// Add tokenization schemas manually +localSpec.components.schemas.TokenizeRequest = { + type: 'object', + properties: { + input: { + type: 'string', + description: 'The text to tokenize', + }, + model: { + type: 'string', + description: 'The model to use for tokenization', + enum: LOCAL_MODELS, + }, + }, + required: ['input'], +} + +localSpec.components.schemas.TokenizeResponse = { + type: 'object', + properties: { + tokens: { + type: 'array', + items: { + type: 'integer', + }, + description: 'Array of token IDs', + }, + }, + required: ['tokens'], +} + +localSpec.components.schemas.TokenCountResponse = { + type: 'object', + properties: { + count: { + type: 'integer', + description: 'Number of tokens', + }, + }, + required: ['count'], +} + +// Update model references in schemas to use local models +if ( + localSpec.components.schemas.CreateChatCompletionRequest?.properties?.model +) { + localSpec.components.schemas.CreateChatCompletionRequest.properties.model = { + ...localSpec.components.schemas.CreateChatCompletionRequest.properties + .model, + enum: LOCAL_MODELS, + example: LOCAL_MODELS[0], + description: `ID of the model to use. Available models: ${LOCAL_MODELS.join(', ')}`, + } +} + +if (localSpec.components.schemas.CreateCompletionRequest?.properties?.model) { + localSpec.components.schemas.CreateCompletionRequest.properties.model = { + ...localSpec.components.schemas.CreateCompletionRequest.properties.model, + enum: LOCAL_MODELS, + example: LOCAL_MODELS[0], + description: `ID of the model to use. Available models: ${LOCAL_MODELS.join(', ')}`, + } +} + +// Fix all $ref references to use components/schemas instead of definitions +function fixReferences(obj) { + if (typeof obj === 'string') { + return obj.replace(/#\/definitions\//g, '#/components/schemas/') + } + if (Array.isArray(obj)) { + return obj.map(fixReferences) + } + if (obj && typeof obj === 'object') { + const fixed = {} + for (const key in obj) { + fixed[key] = fixReferences(obj[key]) + } + return fixed + } + return obj +} + +// Apply reference fixes +localSpec.paths = fixReferences(localSpec.paths) +localSpec.components.schemas = fixReferences(localSpec.components.schemas) + +// Add x-jan-local-features +localSpec['x-jan-local-features'] = { + engine: 'llama.cpp', + features: [ + 'GGUF model support', + 'CPU and GPU acceleration', + 'Quantized model support (Q4, Q5, Q8)', + 'Metal acceleration on macOS', + 'CUDA support on NVIDIA GPUs', + 'ROCm support on AMD GPUs', + 'AVX/AVX2/AVX512 optimizations', + 'Memory-mapped model loading', + ], + privacy: { + local_processing: true, + no_telemetry: true, + offline_capable: true, + }, + model_formats: ['GGUF', 'GGML'], + default_settings: { + context_length: 4096, + batch_size: 512, + threads: 'auto', + }, +} + +// Write the fixed spec +fs.writeFileSync(outputPath, JSON.stringify(localSpec, null, 2), 'utf8') + +console.log('✅ Local OpenAPI spec fixed successfully!') +console.log(`📁 Output: ${outputPath}`) +console.log(`📊 Endpoints: ${Object.keys(localSpec.paths).length}`) +console.log(`📊 Schemas: ${Object.keys(localSpec.components.schemas).length}`) +console.log( + `🎯 Examples: ${Object.keys(localSpec.paths).reduce((count, path) => { + return ( + count + + Object.keys(localSpec.paths[path]).reduce((c, method) => { + const examples = + localSpec.paths[path][method]?.requestBody?.content?.[ + 'application/json' + ]?.examples + return c + (examples ? Object.keys(examples).length : 0) + }, 0) + ) + }, 0)}` +) diff --git a/website/scripts/generate-cloud-spec.js b/website/scripts/generate-cloud-spec.js new file mode 100644 index 000000000..4ccfb339b --- /dev/null +++ b/website/scripts/generate-cloud-spec.js @@ -0,0 +1,421 @@ +#!/usr/bin/env node + +import fs from 'fs' +import path from 'path' +import { fileURLToPath } from 'url' + +// Get current directory in ES modules +const __filename = fileURLToPath(import.meta.url) +const __dirname = path.dirname(__filename) + +const CONFIG = { + // Jan Server API spec URL - change this for different environments + JAN_SERVER_SPEC_URL: + process.env.JAN_SERVER_SPEC_URL || + 'https://api.jan.ai/api/swagger/doc.json', + + // Server URLs for different environments + SERVERS: { + production: { + url: process.env.JAN_SERVER_PROD_URL || 'https://api.jan.ai/v1', + description: 'Jan Server API (Production)', + }, + staging: { + url: + process.env.JAN_SERVER_STAGING_URL || 'https://staging-api.jan.ai/v1', + description: 'Jan Server API (Staging)', + }, + local: { + url: process.env.JAN_SERVER_LOCAL_URL || 'http://localhost:8000/v1', + description: 'Jan Server (Local Development)', + }, + minikube: { + url: + process.env.JAN_SERVER_MINIKUBE_URL || + 'http://jan-server.local:8000/v1', + description: 'Jan Server (Minikube)', + }, + }, + + // Output file path + OUTPUT_PATH: path.join(__dirname, '../public/openapi/cloud-openapi.json'), + + // Fallback to local spec if fetch fails + FALLBACK_SPEC_PATH: path.join(__dirname, '../public/openapi/openapi.json'), + + // Request timeout in milliseconds + FETCH_TIMEOUT: 10000, +} + +// Model examples for Jan Server (vLLM deployment) +const MODEL_EXAMPLES = [ + 'llama-3.1-8b-instruct', + 'mistral-7b-instruct-v0.3', + 'gemma-2-9b-it', + 'qwen2.5-7b-instruct', +] + +// ============================================================================= +// UTILITY FUNCTIONS +// ============================================================================= + +const colors = { + reset: '\x1b[0m', + green: '\x1b[32m', + yellow: '\x1b[33m', + red: '\x1b[31m', + cyan: '\x1b[36m', + bright: '\x1b[1m', +} + +function log(message, type = 'info') { + const prefix = + { + success: `${colors.green}✅`, + warning: `${colors.yellow}⚠️ `, + error: `${colors.red}❌`, + info: `${colors.cyan}ℹ️ `, + }[type] || '' + console.log(`${prefix} ${message}${colors.reset}`) +} + +async function fetchWithTimeout(url, options = {}) { + const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), CONFIG.FETCH_TIMEOUT) + + try { + const response = await fetch(url, { + ...options, + signal: controller.signal, + }) + clearTimeout(timeoutId) + return response + } catch (error) { + clearTimeout(timeoutId) + throw error + } +} + +// ============================================================================= +// SPEC ENHANCEMENT FUNCTIONS +// ============================================================================= + +function enhanceSpecWithBranding(spec) { + // Update info section with Jan Server branding + spec.info = { + ...spec.info, + 'title': '👋Jan Server API', + 'description': + 'OpenAI-compatible API for Jan Server powered by vLLM. High-performance, scalable inference service with automatic batching and optimized memory management.', + 'version': spec.info?.version || '1.0.0', + 'x-logo': { + url: 'https://jan.ai/logo.png', + altText: '👋Jan Server API', + }, + 'contact': { + name: 'Jan Server Support', + url: 'https://jan.ai/support', + email: 'support@jan.ai', + }, + 'license': { + name: 'Apache 2.0', + url: 'https://github.com/menloresearch/jan/blob/main/LICENSE', + }, + } + + // Update servers with our configured endpoints + spec.servers = Object.values(CONFIG.SERVERS) + + // Add global security requirement + spec.security = [{ bearerAuth: [] }] + + // Add tags for better organization + spec.tags = [ + { name: 'Models', description: 'List and describe available models' }, + { + name: 'Chat', + description: 'Chat completion endpoints for conversational AI', + }, + { name: 'Completions', description: 'Text completion endpoints' }, + { name: 'Embeddings', description: 'Generate embeddings for text' }, + { name: 'Usage', description: 'Monitor API usage and quotas' }, + ] + + return spec +} + +function enhanceSecuritySchemes(spec) { + if (!spec.components) spec.components = {} + if (!spec.components.securitySchemes) spec.components.securitySchemes = {} + + spec.components.securitySchemes.bearerAuth = { + type: 'http', + scheme: 'bearer', + bearerFormat: 'JWT', + description: + 'Enter your Jan Server API key. Configure authentication in your server settings.', + } + + return spec +} + +function addModelExamples(spec) { + const primaryModel = MODEL_EXAMPLES[0] + + // Helper function to update model fields in schemas + function updateModelField(modelField) { + if (!modelField) return + + modelField.example = primaryModel + modelField.description = `ID of the model to use. Available models: ${MODEL_EXAMPLES.join(', ')}` + + if (modelField.anyOf && modelField.anyOf[0]?.type === 'string') { + modelField.anyOf[0].example = primaryModel + modelField.anyOf[0].enum = MODEL_EXAMPLES + } else if (modelField.type === 'string') { + modelField.enum = MODEL_EXAMPLES + } + } + + // Update model fields in common request schemas + const schemas = spec.components?.schemas || {} + + if (schemas.CreateCompletionRequest?.properties?.model) { + updateModelField(schemas.CreateCompletionRequest.properties.model) + } + + if (schemas.CreateChatCompletionRequest?.properties?.model) { + updateModelField(schemas.CreateChatCompletionRequest.properties.model) + } + + if (schemas.CreateEmbeddingRequest?.properties?.model) { + updateModelField(schemas.CreateEmbeddingRequest.properties.model) + } + + return spec +} + +function addRequestExamples(spec) { + const primaryModel = MODEL_EXAMPLES[0] + + // Example request bodies + const examples = { + completion: { + 'text-completion': { + summary: 'Text Completion Example', + description: `Complete text using ${primaryModel}`, + value: { + model: primaryModel, + prompt: 'Once upon a time,', + max_tokens: 50, + temperature: 0.7, + top_p: 0.9, + stream: false, + }, + }, + }, + chatCompletion: { + 'simple-chat': { + summary: 'Simple Chat Example', + description: `Chat completion using ${primaryModel}`, + value: { + model: primaryModel, + messages: [ + { role: 'user', content: 'What is the capital of France?' }, + ], + max_tokens: 100, + temperature: 0.7, + stream: false, + }, + }, + }, + embedding: { + 'text-embedding': { + summary: 'Text Embedding Example', + description: `Generate embeddings using ${primaryModel}`, + value: { + model: primaryModel, + input: 'The quick brown fox jumps over the lazy dog', + }, + }, + }, + } + + // Add examples to path operations + Object.keys(spec.paths || {}).forEach((path) => { + Object.keys(spec.paths[path] || {}).forEach((method) => { + const operation = spec.paths[path][method] + + if (!operation.requestBody?.content?.['application/json']) return + + if (path.includes('/completions') && !path.includes('/chat')) { + operation.requestBody.content['application/json'].examples = + examples.completion + } else if (path.includes('/chat/completions')) { + operation.requestBody.content['application/json'].examples = + examples.chatCompletion + } else if (path.includes('/embeddings')) { + operation.requestBody.content['application/json'].examples = + examples.embedding + } + }) + }) + + return spec +} + +function addCloudFeatures(spec) { + // Add cloud-specific extension + spec['x-jan-server-features'] = { + vllm: { + version: '0.5.0', + features: [ + 'PagedAttention for efficient memory management', + 'Continuous batching for high throughput', + 'Tensor parallelism for multi-GPU serving', + 'Quantization support (AWQ, GPTQ, SqueezeLLM)', + 'Speculative decoding', + 'LoRA adapter support', + ], + }, + scaling: { + auto_scaling: true, + min_replicas: 1, + max_replicas: 100, + target_qps: 100, + }, + limits: { + max_tokens_per_request: 32768, + max_batch_size: 256, + timeout_seconds: 300, + }, + } + + return spec +} + +// ============================================================================= +// MAIN FUNCTIONS +// ============================================================================= + +async function fetchJanServerSpec() { + log(`Fetching Jan Server spec from: ${CONFIG.JAN_SERVER_SPEC_URL}`) + + try { + const response = await fetchWithTimeout(CONFIG.JAN_SERVER_SPEC_URL) + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`) + } + + const spec = await response.json() + log('Successfully fetched Jan Server specification', 'success') + return spec + } catch (error) { + log(`Failed to fetch Jan Server spec: ${error.message}`, 'warning') + + // If FORCE_UPDATE is set, don't use fallback - fail instead + if (process.env.FORCE_UPDATE === 'true') { + log('Force update requested - not using fallback', 'error') + throw error + } + + log(`Falling back to local spec: ${CONFIG.FALLBACK_SPEC_PATH}`, 'warning') + + if (fs.existsSync(CONFIG.FALLBACK_SPEC_PATH)) { + const fallbackSpec = JSON.parse( + fs.readFileSync(CONFIG.FALLBACK_SPEC_PATH, 'utf8') + ) + log('Using local fallback specification', 'warning') + return fallbackSpec + } else { + throw new Error('No fallback spec available') + } + } +} + +async function generateCloudSpec() { + console.log( + `${colors.bright}${colors.cyan}🚀 Jan Server API Spec Generator${colors.reset}` + ) + console.log( + `${colors.cyan}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${colors.reset}` + ) + console.log(`📡 Source: ${CONFIG.JAN_SERVER_SPEC_URL}`) + console.log(`📁 Output: ${CONFIG.OUTPUT_PATH}`) + console.log(`🏗️ Servers: ${Object.keys(CONFIG.SERVERS).join(', ')}`) + console.log('') + + try { + // Fetch the real Jan Server specification + let spec = await fetchJanServerSpec() + + // Apply all enhancements + spec = enhanceSpecWithBranding(spec) + spec = enhanceSecuritySchemes(spec) + spec = addModelExamples(spec) + spec = addRequestExamples(spec) + spec = addCloudFeatures(spec) + + // Ensure all paths have security requirements + Object.keys(spec.paths || {}).forEach((path) => { + Object.keys(spec.paths[path] || {}).forEach((method) => { + const operation = spec.paths[path][method] + if (!operation.security) { + operation.security = [{ bearerAuth: [] }] + } + }) + }) + + // Write the enhanced specification + fs.writeFileSync(CONFIG.OUTPUT_PATH, JSON.stringify(spec, null, 2), 'utf8') + + log('Jan Server specification generated successfully!', 'success') + console.log(`📁 Output: ${CONFIG.OUTPUT_PATH}`) + console.log('\n📊 Summary:') + console.log(` - Endpoints: ${Object.keys(spec.paths || {}).length}`) + console.log(` - Servers: ${spec.servers?.length || 0}`) + console.log(` - Models: ${MODEL_EXAMPLES.length}`) + console.log(` - Security: Bearer token authentication`) + console.log( + ` - Engine: vLLM (${spec['x-jan-server-features']?.vllm?.version || 'unknown'})` + ) + + return true + } catch (error) { + log( + `Failed to generate Jan Server specification: ${error.message}`, + 'error' + ) + console.log('\n🔧 Troubleshooting:') + console.log(' 1. Check your internet connection') + console.log( + ` 2. Verify Jan Server is accessible at: ${CONFIG.JAN_SERVER_SPEC_URL}` + ) + console.log(' 3. Check if you need to set environment variables:') + console.log(' - JAN_SERVER_SPEC_URL') + console.log(' - JAN_SERVER_PROD_URL') + console.log(' - JAN_SERVER_LOCAL_URL') + return false + } +} + +// ============================================================================= +// EXECUTION +// ============================================================================= + +// Show configuration on startup +if (process.env.NODE_ENV !== 'test') { + console.log(`${colors.cyan}🔧 Configuration:${colors.reset}`) + console.log(` Spec URL: ${CONFIG.JAN_SERVER_SPEC_URL}`) + console.log(` Timeout: ${CONFIG.FETCH_TIMEOUT}ms`) + console.log(` Servers: ${Object.keys(CONFIG.SERVERS).length} configured`) + if (process.env.FORCE_UPDATE === 'true') { + console.log(` ${colors.yellow}Force Update: ENABLED${colors.reset}`) + } + console.log('') +} + +// Run the generator +const success = await generateCloudSpec() +process.exit(success ? 0 : 1) diff --git a/website/src/assets/anthropic.png b/website/src/assets/anthropic.png deleted file mode 100644 index d82ba291d..000000000 Binary files a/website/src/assets/anthropic.png and /dev/null differ diff --git a/website/src/assets/chat_jan_v1.png b/website/src/assets/chat_jan_v1.png index fd438d143..ae5edcd38 100644 Binary files a/website/src/assets/chat_jan_v1.png and b/website/src/assets/chat_jan_v1.png differ diff --git a/website/src/assets/customprovider.png b/website/src/assets/customprovider.png new file mode 100644 index 000000000..2c28ba54e Binary files /dev/null and b/website/src/assets/customprovider.png differ diff --git a/website/src/assets/customprovider10.png b/website/src/assets/customprovider10.png new file mode 100644 index 000000000..9f852e707 Binary files /dev/null and b/website/src/assets/customprovider10.png differ diff --git a/website/src/assets/customprovider2.png b/website/src/assets/customprovider2.png new file mode 100644 index 000000000..9a620cc7a Binary files /dev/null and b/website/src/assets/customprovider2.png differ diff --git a/website/src/assets/customprovider3.png b/website/src/assets/customprovider3.png new file mode 100644 index 000000000..eacfaa6d7 Binary files /dev/null and b/website/src/assets/customprovider3.png differ diff --git a/website/src/assets/customprovider4.png b/website/src/assets/customprovider4.png new file mode 100644 index 000000000..35a09cc00 Binary files /dev/null and b/website/src/assets/customprovider4.png differ diff --git a/website/src/assets/customprovider5.png b/website/src/assets/customprovider5.png new file mode 100644 index 000000000..008bb3a4f Binary files /dev/null and b/website/src/assets/customprovider5.png differ diff --git a/website/src/assets/customprovider6.png b/website/src/assets/customprovider6.png new file mode 100644 index 000000000..a2a508926 Binary files /dev/null and b/website/src/assets/customprovider6.png differ diff --git a/website/src/assets/customprovider7.png b/website/src/assets/customprovider7.png new file mode 100644 index 000000000..bf0e45d2f Binary files /dev/null and b/website/src/assets/customprovider7.png differ diff --git a/website/src/assets/customprovider8.png b/website/src/assets/customprovider8.png new file mode 100644 index 000000000..a45153bb5 Binary files /dev/null and b/website/src/assets/customprovider8.png differ diff --git a/website/src/assets/customprovider9.png b/website/src/assets/customprovider9.png new file mode 100644 index 000000000..2a881506b Binary files /dev/null and b/website/src/assets/customprovider9.png differ diff --git a/website/src/assets/deepseek.png b/website/src/assets/deepseek.png deleted file mode 100644 index 9e1084aee..000000000 Binary files a/website/src/assets/deepseek.png and /dev/null differ diff --git a/website/src/assets/extensions-01.png b/website/src/assets/extensions-01.png deleted file mode 100644 index 98fe85480..000000000 Binary files a/website/src/assets/extensions-01.png and /dev/null differ diff --git a/website/src/assets/extensions-02.png b/website/src/assets/extensions-02.png deleted file mode 100644 index 5761b6b7f..000000000 Binary files a/website/src/assets/extensions-02.png and /dev/null differ diff --git a/website/src/assets/extensions-03.png b/website/src/assets/extensions-03.png deleted file mode 100644 index a74230a0a..000000000 Binary files a/website/src/assets/extensions-03.png and /dev/null differ diff --git a/website/src/assets/extensions-04.png b/website/src/assets/extensions-04.png deleted file mode 100644 index 20b48bcf5..000000000 Binary files a/website/src/assets/extensions-04.png and /dev/null differ diff --git a/website/src/assets/extensions-05.png b/website/src/assets/extensions-05.png deleted file mode 100644 index 3967d90a8..000000000 Binary files a/website/src/assets/extensions-05.png and /dev/null differ diff --git a/website/src/assets/extensions-06.png b/website/src/assets/extensions-06.png deleted file mode 100644 index b169e3926..000000000 Binary files a/website/src/assets/extensions-06.png and /dev/null differ diff --git a/website/src/assets/extensions-07.png b/website/src/assets/extensions-07.png deleted file mode 100644 index 3d39f56d9..000000000 Binary files a/website/src/assets/extensions-07.png and /dev/null differ diff --git a/website/src/assets/extensions-08.png b/website/src/assets/extensions-08.png deleted file mode 100644 index 3d124e367..000000000 Binary files a/website/src/assets/extensions-08.png and /dev/null differ diff --git a/website/src/assets/extensions-09.png b/website/src/assets/extensions-09.png deleted file mode 100644 index 7d7cd6193..000000000 Binary files a/website/src/assets/extensions-09.png and /dev/null differ diff --git a/website/src/assets/extensions-10.png b/website/src/assets/extensions-10.png deleted file mode 100644 index ecadd8475..000000000 Binary files a/website/src/assets/extensions-10.png and /dev/null differ diff --git a/website/src/assets/gpt5-add.png b/website/src/assets/gpt5-add.png new file mode 100644 index 000000000..9e34e8e69 Binary files /dev/null and b/website/src/assets/gpt5-add.png differ diff --git a/website/src/assets/gpt5-chat.png b/website/src/assets/gpt5-chat.png new file mode 100644 index 000000000..69933eba8 Binary files /dev/null and b/website/src/assets/gpt5-chat.png differ diff --git a/website/src/assets/gpt5-msg.png b/website/src/assets/gpt5-msg.png new file mode 100644 index 000000000..4ea346ae3 Binary files /dev/null and b/website/src/assets/gpt5-msg.png differ diff --git a/website/src/assets/gpt5-msg2.png b/website/src/assets/gpt5-msg2.png new file mode 100644 index 000000000..736e9cd6f Binary files /dev/null and b/website/src/assets/gpt5-msg2.png differ diff --git a/website/src/assets/gpt5-msg3.png b/website/src/assets/gpt5-msg3.png new file mode 100644 index 000000000..509f23c79 Binary files /dev/null and b/website/src/assets/gpt5-msg3.png differ diff --git a/website/src/assets/gpt5-tools.png b/website/src/assets/gpt5-tools.png new file mode 100644 index 000000000..f4b8eaaa9 Binary files /dev/null and b/website/src/assets/gpt5-tools.png differ diff --git a/website/src/assets/hf_hub.png b/website/src/assets/hf_hub.png new file mode 100644 index 000000000..ad059c49a Binary files /dev/null and b/website/src/assets/hf_hub.png differ diff --git a/website/src/assets/hf_jan_nano.png b/website/src/assets/hf_jan_nano.png new file mode 100644 index 000000000..147a5c70e Binary files /dev/null and b/website/src/assets/hf_jan_nano.png differ diff --git a/website/src/assets/hf_jan_nano_2.png b/website/src/assets/hf_jan_nano_2.png new file mode 100644 index 000000000..10c410240 Binary files /dev/null and b/website/src/assets/hf_jan_nano_2.png differ diff --git a/website/src/assets/hf_jan_nano_3.png b/website/src/assets/hf_jan_nano_3.png new file mode 100644 index 000000000..dac240d29 Binary files /dev/null and b/website/src/assets/hf_jan_nano_3.png differ diff --git a/website/src/assets/hf_jan_nano_4.png b/website/src/assets/hf_jan_nano_4.png new file mode 100644 index 000000000..552f07b06 Binary files /dev/null and b/website/src/assets/hf_jan_nano_4.png differ diff --git a/website/src/assets/hf_jan_nano_5.png b/website/src/assets/hf_jan_nano_5.png new file mode 100644 index 000000000..b322f0f93 Binary files /dev/null and b/website/src/assets/hf_jan_nano_5.png differ diff --git a/website/src/assets/hf_jan_nano_6.png b/website/src/assets/hf_jan_nano_6.png new file mode 100644 index 000000000..c8be2b707 Binary files /dev/null and b/website/src/assets/hf_jan_nano_6.png differ diff --git a/website/src/assets/hf_jan_nano_7.png b/website/src/assets/hf_jan_nano_7.png new file mode 100644 index 000000000..2a8ba8438 Binary files /dev/null and b/website/src/assets/hf_jan_nano_7.png differ diff --git a/website/src/assets/hf_jan_nano_8.png b/website/src/assets/hf_jan_nano_8.png new file mode 100644 index 000000000..4e1885a8e Binary files /dev/null and b/website/src/assets/hf_jan_nano_8.png differ diff --git a/website/src/assets/hf_jan_nano_9.png b/website/src/assets/hf_jan_nano_9.png new file mode 100644 index 000000000..09575c541 Binary files /dev/null and b/website/src/assets/hf_jan_nano_9.png differ diff --git a/website/src/assets/hf_jan_setup.png b/website/src/assets/hf_jan_setup.png new file mode 100644 index 000000000..2d917539b Binary files /dev/null and b/website/src/assets/hf_jan_setup.png differ diff --git a/website/src/assets/hf_providers.png b/website/src/assets/hf_providers.png new file mode 100644 index 000000000..1f8e4daf7 Binary files /dev/null and b/website/src/assets/hf_providers.png differ diff --git a/website/src/assets/houston.webp b/website/src/assets/houston.webp deleted file mode 100644 index 930c16497..000000000 Binary files a/website/src/assets/houston.webp and /dev/null differ diff --git a/website/src/assets/install-engines-01.png b/website/src/assets/install-engines-01.png deleted file mode 100644 index 95e824a7f..000000000 Binary files a/website/src/assets/install-engines-01.png and /dev/null differ diff --git a/website/src/assets/install-engines-02.png b/website/src/assets/install-engines-02.png deleted file mode 100644 index b6b6a6a58..000000000 Binary files a/website/src/assets/install-engines-02.png and /dev/null differ diff --git a/website/src/assets/install-engines-03.png b/website/src/assets/install-engines-03.png deleted file mode 100644 index a65145a4c..000000000 Binary files a/website/src/assets/install-engines-03.png and /dev/null differ diff --git a/website/src/assets/jan-nano0.png b/website/src/assets/jan-nano0.png deleted file mode 100644 index f2da8b5f7..000000000 Binary files a/website/src/assets/jan-nano0.png and /dev/null differ diff --git a/website/src/assets/jan-server.png b/website/src/assets/jan-server.png deleted file mode 100644 index e49499f01..000000000 Binary files a/website/src/assets/jan-server.png and /dev/null differ diff --git a/website/src/assets/jan-vision.png b/website/src/assets/jan-vision.png deleted file mode 100644 index 5ba34cb13..000000000 Binary files a/website/src/assets/jan-vision.png and /dev/null differ diff --git a/website/src/assets/jan_desktop.png b/website/src/assets/jan_desktop.png deleted file mode 100644 index 4d200df0a..000000000 Binary files a/website/src/assets/jan_desktop.png and /dev/null differ diff --git a/website/src/assets/jan_everywhere.png b/website/src/assets/jan_everywhere.png deleted file mode 100644 index ee47a84db..000000000 Binary files a/website/src/assets/jan_everywhere.png and /dev/null differ diff --git a/website/src/assets/jan_loaded.png b/website/src/assets/jan_loaded.png new file mode 100644 index 000000000..cfd3b1a13 Binary files /dev/null and b/website/src/assets/jan_loaded.png differ diff --git a/website/src/assets/jan_mobile.png b/website/src/assets/jan_mobile.png deleted file mode 100644 index 5257bc98d..000000000 Binary files a/website/src/assets/jan_mobile.png and /dev/null differ diff --git a/website/src/assets/jan_mobile2.png b/website/src/assets/jan_mobile2.png deleted file mode 100644 index eb5275431..000000000 Binary files a/website/src/assets/jan_mobile2.png and /dev/null differ diff --git a/website/src/assets/jan_mobile3.png b/website/src/assets/jan_mobile3.png deleted file mode 100644 index b81c86919..000000000 Binary files a/website/src/assets/jan_mobile3.png and /dev/null differ diff --git a/website/src/assets/jan_mobile4.png b/website/src/assets/jan_mobile4.png deleted file mode 100644 index b54c04e7b..000000000 Binary files a/website/src/assets/jan_mobile4.png and /dev/null differ diff --git a/website/src/assets/jan_mobile5.png b/website/src/assets/jan_mobile5.png deleted file mode 100644 index 7332186e1..000000000 Binary files a/website/src/assets/jan_mobile5.png and /dev/null differ diff --git a/website/src/assets/jan_mobile6.png b/website/src/assets/jan_mobile6.png deleted file mode 100644 index abe80cf0f..000000000 Binary files a/website/src/assets/jan_mobile6.png and /dev/null differ diff --git a/website/src/assets/jan_mobile7.png b/website/src/assets/jan_mobile7.png deleted file mode 100644 index f010fe08b..000000000 Binary files a/website/src/assets/jan_mobile7.png and /dev/null differ diff --git a/website/src/assets/jan_sync.png b/website/src/assets/jan_sync.png deleted file mode 100644 index 95fddb9ca..000000000 Binary files a/website/src/assets/jan_sync.png and /dev/null differ diff --git a/website/src/assets/jan_web.png b/website/src/assets/jan_web.png deleted file mode 100644 index dc17ad08f..000000000 Binary files a/website/src/assets/jan_web.png and /dev/null differ diff --git a/website/src/assets/jupyter.png b/website/src/assets/jupyter.png new file mode 100644 index 000000000..d261566d3 Binary files /dev/null and b/website/src/assets/jupyter.png differ diff --git a/website/src/assets/jupyter1.png b/website/src/assets/jupyter1.png new file mode 100644 index 000000000..f12e66eea Binary files /dev/null and b/website/src/assets/jupyter1.png differ diff --git a/website/src/assets/jupyter2.png b/website/src/assets/jupyter2.png new file mode 100644 index 000000000..b4650d651 Binary files /dev/null and b/website/src/assets/jupyter2.png differ diff --git a/website/src/assets/jupyter3.png b/website/src/assets/jupyter3.png new file mode 100644 index 000000000..de64bafa6 Binary files /dev/null and b/website/src/assets/jupyter3.png differ diff --git a/website/src/assets/jupyter4.png b/website/src/assets/jupyter4.png new file mode 100644 index 000000000..b920d49cb Binary files /dev/null and b/website/src/assets/jupyter4.png differ diff --git a/website/src/assets/jupyter5.png b/website/src/assets/jupyter5.png new file mode 100644 index 000000000..cb6b1b119 Binary files /dev/null and b/website/src/assets/jupyter5.png differ diff --git a/website/src/assets/linear1.png b/website/src/assets/linear1.png new file mode 100644 index 000000000..f260b55ff Binary files /dev/null and b/website/src/assets/linear1.png differ diff --git a/website/src/assets/linear2.png b/website/src/assets/linear2.png new file mode 100644 index 000000000..fc059195b Binary files /dev/null and b/website/src/assets/linear2.png differ diff --git a/website/src/assets/linear3.png b/website/src/assets/linear3.png new file mode 100644 index 000000000..f3fbe9b78 Binary files /dev/null and b/website/src/assets/linear3.png differ diff --git a/website/src/assets/linear4.png b/website/src/assets/linear4.png new file mode 100644 index 000000000..3482649d8 Binary files /dev/null and b/website/src/assets/linear4.png differ diff --git a/website/src/assets/linear5.png b/website/src/assets/linear5.png new file mode 100644 index 000000000..82d1db180 Binary files /dev/null and b/website/src/assets/linear5.png differ diff --git a/website/src/assets/linear6.png b/website/src/assets/linear6.png new file mode 100644 index 000000000..717e928d1 Binary files /dev/null and b/website/src/assets/linear6.png differ diff --git a/website/src/assets/linear7.png b/website/src/assets/linear7.png new file mode 100644 index 000000000..30f992abc Binary files /dev/null and b/website/src/assets/linear7.png differ diff --git a/website/src/assets/linear8.png b/website/src/assets/linear8.png new file mode 100644 index 000000000..4d0ea415a Binary files /dev/null and b/website/src/assets/linear8.png differ diff --git a/website/src/assets/lucy.jpeg b/website/src/assets/lucy.jpeg deleted file mode 100644 index 6085967e1..000000000 Binary files a/website/src/assets/lucy.jpeg and /dev/null differ diff --git a/website/src/assets/martian.png b/website/src/assets/martian.png deleted file mode 100644 index 840fd083d..000000000 Binary files a/website/src/assets/martian.png and /dev/null differ diff --git a/website/src/assets/meme.png b/website/src/assets/meme.png new file mode 100644 index 000000000..498a33e06 Binary files /dev/null and b/website/src/assets/meme.png differ diff --git a/website/src/assets/model-management-07.png b/website/src/assets/model-management-07.png deleted file mode 100644 index ca9880ac0..000000000 Binary files a/website/src/assets/model-management-07.png and /dev/null differ diff --git a/website/src/assets/model-management-08.png b/website/src/assets/model-management-08.png deleted file mode 100644 index 98c02a19d..000000000 Binary files a/website/src/assets/model-management-08.png and /dev/null differ diff --git a/website/src/assets/model-management-09.png b/website/src/assets/model-management-09.png deleted file mode 100644 index 990b53710..000000000 Binary files a/website/src/assets/model-management-09.png and /dev/null differ diff --git a/website/src/assets/nvidia-nim.png b/website/src/assets/nvidia-nim.png deleted file mode 100644 index e748756f7..000000000 Binary files a/website/src/assets/nvidia-nim.png and /dev/null differ diff --git a/website/src/assets/openai-settings.png b/website/src/assets/openai-settings.png new file mode 100644 index 000000000..e8beeba28 Binary files /dev/null and b/website/src/assets/openai-settings.png differ diff --git a/website/src/assets/quick-start-01.png b/website/src/assets/quick-start-01.png deleted file mode 100644 index 03b101aa2..000000000 Binary files a/website/src/assets/quick-start-01.png and /dev/null differ diff --git a/website/src/assets/quick-start-02.png b/website/src/assets/quick-start-02.png deleted file mode 100644 index 977d8ebdb..000000000 Binary files a/website/src/assets/quick-start-02.png and /dev/null differ diff --git a/website/src/assets/retrieval-01.png b/website/src/assets/retrieval-01.png deleted file mode 100644 index 1d120e745..000000000 Binary files a/website/src/assets/retrieval-01.png and /dev/null differ diff --git a/website/src/assets/retrieval-02.png b/website/src/assets/retrieval-02.png deleted file mode 100644 index 2ec4ba029..000000000 Binary files a/website/src/assets/retrieval-02.png and /dev/null differ diff --git a/website/src/assets/settings-01.png b/website/src/assets/settings-01.png deleted file mode 100644 index e2e5aead5..000000000 Binary files a/website/src/assets/settings-01.png and /dev/null differ diff --git a/website/src/assets/settings-02.png b/website/src/assets/settings-02.png deleted file mode 100644 index 6c1699a1c..000000000 Binary files a/website/src/assets/settings-02.png and /dev/null differ diff --git a/website/src/assets/settings-03.png b/website/src/assets/settings-03.png deleted file mode 100644 index 4e32c390b..000000000 Binary files a/website/src/assets/settings-03.png and /dev/null differ diff --git a/website/src/assets/settings-05.png b/website/src/assets/settings-05.png deleted file mode 100644 index 489d6cd50..000000000 Binary files a/website/src/assets/settings-05.png and /dev/null differ diff --git a/website/src/assets/settings-10.png b/website/src/assets/settings-10.png deleted file mode 100644 index 30c4dd4d4..000000000 Binary files a/website/src/assets/settings-10.png and /dev/null differ diff --git a/website/src/assets/settings-16.png b/website/src/assets/settings-16.png deleted file mode 100644 index 72a61ca31..000000000 Binary files a/website/src/assets/settings-16.png and /dev/null differ diff --git a/website/src/assets/settings-19.png b/website/src/assets/settings-19.png deleted file mode 100644 index 634c6f1da..000000000 Binary files a/website/src/assets/settings-19.png and /dev/null differ diff --git a/website/src/assets/tensorrt-llm-01.png b/website/src/assets/tensorrt-llm-01.png deleted file mode 100644 index 2f839f7a5..000000000 Binary files a/website/src/assets/tensorrt-llm-01.png and /dev/null differ diff --git a/website/src/assets/tensorrt-llm-02.png b/website/src/assets/tensorrt-llm-02.png deleted file mode 100644 index de9841874..000000000 Binary files a/website/src/assets/tensorrt-llm-02.png and /dev/null differ diff --git a/website/src/assets/todoist1.png b/website/src/assets/todoist1.png new file mode 100644 index 000000000..a1b98578d Binary files /dev/null and b/website/src/assets/todoist1.png differ diff --git a/website/src/assets/todoist2.png b/website/src/assets/todoist2.png new file mode 100644 index 000000000..9e4164b89 Binary files /dev/null and b/website/src/assets/todoist2.png differ diff --git a/website/src/assets/todoist3.png b/website/src/assets/todoist3.png new file mode 100644 index 000000000..ede276499 Binary files /dev/null and b/website/src/assets/todoist3.png differ diff --git a/website/src/assets/todoist4.png b/website/src/assets/todoist4.png new file mode 100644 index 000000000..2c8e9c816 Binary files /dev/null and b/website/src/assets/todoist4.png differ diff --git a/website/src/assets/todoist5.png b/website/src/assets/todoist5.png new file mode 100644 index 000000000..5e761df7c Binary files /dev/null and b/website/src/assets/todoist5.png differ diff --git a/website/src/assets/toggle_tools b/website/src/assets/toggle_tools deleted file mode 100644 index 53c7e3b05..000000000 Binary files a/website/src/assets/toggle_tools and /dev/null differ diff --git a/website/src/assets/tom_gauld.png b/website/src/assets/tom_gauld.png deleted file mode 100644 index 1f929f645..000000000 Binary files a/website/src/assets/tom_gauld.png and /dev/null differ diff --git a/website/src/assets/trouble-shooting-03.png b/website/src/assets/trouble-shooting-03.png deleted file mode 100644 index d07ed56d7..000000000 Binary files a/website/src/assets/trouble-shooting-03.png and /dev/null differ diff --git a/website/src/assets/vision.png b/website/src/assets/vision.png new file mode 100644 index 000000000..b5fcac9a4 Binary files /dev/null and b/website/src/assets/vision.png differ diff --git a/website/src/assets/vision2.png b/website/src/assets/vision2.png new file mode 100644 index 000000000..faf59b73c Binary files /dev/null and b/website/src/assets/vision2.png differ diff --git a/website/src/assets/vision3.png b/website/src/assets/vision3.png new file mode 100644 index 000000000..f85c0a7aa Binary files /dev/null and b/website/src/assets/vision3.png differ diff --git a/website/src/assets/vision4.png b/website/src/assets/vision4.png new file mode 100644 index 000000000..5003c4b8a Binary files /dev/null and b/website/src/assets/vision4.png differ diff --git a/website/src/assets/vision5.png b/website/src/assets/vision5.png new file mode 100644 index 000000000..9ba7289cb Binary files /dev/null and b/website/src/assets/vision5.png differ diff --git a/website/src/components/ApiReferenceLayout.astro b/website/src/components/ApiReferenceLayout.astro new file mode 100644 index 000000000..7906d24f3 --- /dev/null +++ b/website/src/components/ApiReferenceLayout.astro @@ -0,0 +1,396 @@ +--- +interface Props { + title: string; + description: string; +} + +const { title, description } = Astro.props; +--- + + + + + + + {title} | 👋 Jan + + + + + + + + + + + + + +
+
+ + 👋 Jan + + + + +
+ + + + + +
+
+ +
+ +
+
+ + + + diff --git a/website/src/components/react/ScalarApiReferenceMulti.jsx b/website/src/components/react/ScalarApiReferenceMulti.jsx new file mode 100644 index 000000000..4558deda1 --- /dev/null +++ b/website/src/components/react/ScalarApiReferenceMulti.jsx @@ -0,0 +1,214 @@ +import { ApiReferenceReact } from '@scalar/api-reference-react' +import '@scalar/api-reference-react/style.css' +import { useEffect, useState } from 'react' + +const ScalarApiReferenceMulti = ({ + specUrl, + title, + description, + deployment = 'local', +}) => { + const [isDarkMode, setIsDarkMode] = useState(true) + const [serverUrl, setServerUrl] = useState('') + + useEffect(() => { + // Theme detection for Starlight + const getCurrentTheme = () => { + const htmlElement = document.documentElement + const theme = htmlElement.getAttribute('data-theme') + const isDark = + theme === 'dark' || + (theme !== 'light' && + window.matchMedia('(prefers-color-scheme: dark)').matches) + + setIsDarkMode(isDark) + } + + // Set initial theme + getCurrentTheme() + + // Watch for theme changes + const observer = new MutationObserver(() => { + getCurrentTheme() + }) + + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['data-theme', 'class'], + }) + + // Watch for system theme changes + const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)') + const handleSystemThemeChange = () => { + getCurrentTheme() + } + + mediaQuery.addEventListener('change', handleSystemThemeChange) + + // Check for custom server URL in localStorage or URL params + const params = new URLSearchParams(window.location.search) + const customServer = + params.get('server') || localStorage.getItem('jan-api-server') + if (customServer) { + setServerUrl(customServer) + } + + return () => { + observer.disconnect() + mediaQuery.removeEventListener('change', handleSystemThemeChange) + } + }, []) + + // Get deployment-specific servers + const getServers = () => { + const customServers = serverUrl + ? [{ url: serverUrl, description: 'Custom Server' }] + : [] + + if (deployment === 'cloud') { + return [ + ...customServers, + { + url: 'https://api.jan.ai/v1', + description: 'Jan Server (Production)', + }, + { + url: 'http://localhost:8000/v1', + description: 'Jan Server (Local Development)', + }, + ] + } + + // Local deployment + return [ + ...customServers, + { + url: 'http://127.0.0.1:1337', + description: 'Local Jan Server (Default)', + }, + { + url: 'http://localhost:1337', + description: 'Local Jan Server (localhost)', + }, + { + url: 'http://localhost:8080', + description: 'Local Jan Server (Alternative Port)', + }, + ] + } + + return ( +
+ {/* Optional server URL input */} +
+ + { + setServerUrl(e.target.value) + localStorage.setItem('jan-api-server', e.target.value) + }} + style={{ + padding: '0.25rem 0.5rem', + background: 'var(--sl-color-bg)', + border: '1px solid var(--sl-color-hairline)', + borderRadius: '4px', + color: 'var(--sl-color-text)', + fontFamily: 'monospace', + fontSize: '0.875rem', + flex: '1', + maxWidth: '300px', + }} + /> + +
+ + +
+ ) +} + +export default ScalarApiReferenceMulti diff --git a/website/src/config/README.md b/website/src/config/README.md new file mode 100644 index 000000000..255de0f59 --- /dev/null +++ b/website/src/config/README.md @@ -0,0 +1,101 @@ +# Navigation Configuration + +This directory contains configuration files for managing navigation across Jan's documentation sites. + +## Overview + +As Jan grows to include multiple products (Jan Desktop, Jan Server, Jan Mobile, etc.), we need a scalable way to manage navigation across different documentation sections. This configuration approach allows us to: + +1. **Maintain consistency** across different products +2. **Avoid duplication** in navigation code +3. **Scale easily** as new products are added +4. **Separate concerns** between regular docs and API reference pages + +## Structure + +### `navigation.js` +Central navigation configuration file containing: +- Product-specific navigation links +- API deployment configurations +- Helper functions for navigation management +- Feature flags for navigation behavior + +## Navigation Strategy + +### Regular Documentation Pages +- Navigation is injected via `astro.config.mjs` +- Shows "Docs" and "API Reference" links +- Appears in the main header next to search + +### API Reference Pages +- Have their own navigation via `ApiReferenceLayout.astro` +- Navigation is built into the layout (not injected) +- Prevents duplicate navigation elements + +## Adding New Products + +To add navigation for a new product: + +1. Update `navigation.js`: +```javascript +products: { + janServer: { + name: 'Jan Server', + links: [ + { href: '/server', text: 'Server Docs', isActive: (path) => path.startsWith('/server') }, + { href: '/server/api', text: 'Server API', isActive: (path) => path.startsWith('/server/api') } + ] + } +} +``` + +2. Update `astro.config.mjs` if needed to handle product-specific logic + +3. Create corresponding layout components if the product needs custom API reference pages + +## Configuration in astro.config.mjs + +The navigation injection in `astro.config.mjs` is kept minimal and clean: + +```javascript +const JAN_NAV_CONFIG = { + links: [/* navigation links */], + excludePaths: [/* paths that have their own navigation */] +}; +``` + +This configuration: +- Is easy to read and modify +- Doesn't interfere with API reference pages +- Can be extended for multiple products +- Maintains clean separation of concerns + +## Best Practices + +1. **Keep it simple**: Navigation configuration should be declarative, not complex logic +2. **Avoid duplication**: Use the configuration to generate navigation, don't hardcode it multiple places +3. **Test changes**: Always verify navigation works on both regular docs and API reference pages +4. **Document changes**: Update this README when adding new products or changing navigation strategy + +## Testing Navigation + +After making changes, verify: +1. Navigation appears correctly on regular docs pages +2. Navigation doesn't duplicate on API reference pages +3. Active states work correctly +4. Mobile responsiveness is maintained +5. Theme switching doesn't break navigation + +## Future Considerations + +- **Product switcher**: Add a dropdown to switch between different product docs +- **Version selector**: Add version switching for API documentation +- **Search integration**: Integrate product-specific search scopes +- **Analytics**: Track navigation usage to improve UX + +## Related Files + +- `/astro.config.mjs` - Navigation injection for regular docs +- `/src/components/ApiReferenceLayout.astro` - API reference navigation +- `/src/pages/api.astro` - API documentation landing page +- `/src/pages/api-reference/*.astro` - API reference pages \ No newline at end of file diff --git a/website/src/config/navigation.js b/website/src/config/navigation.js new file mode 100644 index 000000000..f72c77890 --- /dev/null +++ b/website/src/config/navigation.js @@ -0,0 +1,138 @@ +/** + * Navigation Configuration + * + * Centralized navigation configuration for Jan documentation. + * This makes it easy to manage navigation across multiple products + * and maintain consistency across different documentation sections. + */ + +export const NAVIGATION_CONFIG = { + // Main product navigation links + products: { + jan: { + name: 'Jan', + links: [ + { + href: '/', + text: 'Docs', + isActive: (path) => path === '/' || (path.startsWith('/') && !path.startsWith('/api')), + description: 'Jan documentation and guides' + }, + { + href: '/api', + text: 'API Reference', + isActive: (path) => path.startsWith('/api'), + description: 'OpenAI-compatible API documentation' + } + ] + }, + // Future products can be added here + // Example: + // janServer: { + // name: 'Jan Server', + // links: [ + // { href: '/server', text: 'Server Docs', isActive: (path) => path.startsWith('/server') }, + // { href: '/server/api', text: 'Server API', isActive: (path) => path.startsWith('/server/api') } + // ] + // } + }, + + // API deployment configurations + apiDeployments: { + local: { + name: 'Local API', + defaultServers: [ + { url: 'http://127.0.0.1:1337', description: 'Local Jan Server (Default)' }, + { url: 'http://localhost:1337', description: 'Local Jan Server (localhost)' }, + { url: 'http://localhost:8080', description: 'Local Jan Server (Alternative Port)' } + ], + requiresAuth: false, + engine: 'llama.cpp' + }, + cloud: { + name: 'Jan Server', + defaultServers: [ + { url: 'https://api.jan.ai/v1', description: 'Jan Server (Production)' }, + { url: 'http://localhost:8000/v1', description: 'Jan Server (Local Development)' } + ], + requiresAuth: true, + engine: 'vLLM' + } + }, + + // Navigation styles configuration + styles: { + navLink: { + base: 'nav-link', + active: 'nav-link-active' + }, + container: { + base: 'custom-nav-links', + mobile: 'custom-nav-links-mobile' + } + }, + + // Feature flags for navigation behavior + features: { + persistCustomServer: true, + allowUrlParams: true, + showProductSwitcher: false, // For future multi-product support + mobileMenuBreakpoint: 768 + }, + + // Helper functions + helpers: { + /** + * Get navigation links for current product + * @param {string} productKey - The product identifier + * @returns {Array} Navigation links for the product + */ + getProductNav(productKey = 'jan') { + return this.products[productKey]?.links || []; + }, + + /** + * Determine if current path should show API reference navigation + * @param {string} path - Current pathname + * @returns {boolean} Whether to show API reference navigation + */ + isApiReferencePage(path) { + return path.startsWith('/api-reference/') || path.startsWith('/api/'); + }, + + /** + * Get server configuration for deployment type + * @param {string} deployment - 'local' or 'cloud' + * @returns {Object} Server configuration + */ + getServerConfig(deployment) { + return this.apiDeployments[deployment] || this.apiDeployments.local; + }, + + /** + * Build navigation HTML for injection + * @param {string} currentPath - Current page path + * @param {string} productKey - Product identifier + * @returns {string} HTML string for navigation + */ + buildNavigationHTML(currentPath, productKey = 'jan') { + const links = this.getProductNav(productKey); + + return links.map(link => ` + + ${link.text} + + `).join(''); + } + } +}; + +// Export for use in browser context +if (typeof window !== 'undefined') { + window.JanNavigationConfig = NAVIGATION_CONFIG; +} + +export default NAVIGATION_CONFIG; diff --git a/website/src/content.config.ts b/website/src/content.config.ts index 1945fdee8..69d64c7c7 100644 --- a/website/src/content.config.ts +++ b/website/src/content.config.ts @@ -1,11 +1,10 @@ import { defineCollection, z } from 'astro:content' import { docsLoader } from '@astrojs/starlight/loaders' import { docsSchema } from '@astrojs/starlight/schema' -import { videosSchema } from 'starlight-videos/schemas' export const collections = { docs: defineCollection({ loader: docsLoader(), - schema: docsSchema({ extend: videosSchema }), + schema: docsSchema(), }), } diff --git a/website/src/content/docs/browser/index.mdx b/website/src/content/docs/browser/index.mdx new file mode 100644 index 000000000..967ba90f2 --- /dev/null +++ b/website/src/content/docs/browser/index.mdx @@ -0,0 +1,41 @@ +--- +title: Jan Browser Extension +description: Bring your favorite AI models to any website with Jan's browser extension. +keywords: + [ + Jan Browser Extension, + Jan AI, + Browser AI, + Chrome extension, + Firefox addon, + local AI, + ChatGPT alternative + ] +banner: + content: 'Coming in September 2025. Currently testing it with selected users and internally. 🤓' +--- + +import { Aside, Card, CardGrid } from '@astrojs/starlight/components'; + +![Jan Browser Extension](/gifs/extension.gif) + +## Your AI Models, Anywhere on the Web + +The Jan Browser Extension brings AI assistance directly to your browsing experience. +Connect to your local Jan installation or any remote AI provider to get contextual help +on any website without switching tabs. + + + +Access your preferred models without leaving your current page. Whether you're using local +Jan models or remote providers, get instant AI assistance while reading, writing, or researching +online. + +### Core Features Planned: +- **Universal Access**: Use any Jan-compatible model from any website +- **Context Integration**: Highlight text and get AI assistance instantly +- **Privacy Options**: Choose between local processing or remote providers +- **Seamless Experience**: No tab switching or workflow interruption required diff --git a/website/src/content/docs/index.mdx b/website/src/content/docs/index.mdx index 4acbec801..87cf331db 100644 --- a/website/src/content/docs/index.mdx +++ b/website/src/content/docs/index.mdx @@ -1,109 +1,263 @@ --- title: Jan -description: Build, run, and own your AI. From laptop to superintelligence. +description: Working towards open superintelligence through community-driven AI keywords: [ Jan, + Jan AI, open superintelligence, AI ecosystem, - self-hosted AI, local AI, + private AI, + self-hosted AI, llama.cpp, + Model Context Protocol, + MCP, GGUF models, - MCP tools, - Model Context Protocol + large language model, + LLM, ] +banner: + content: | + We just launched something cool! 👋Jan now supports image 🖼️ attachments 🎉 --- -import { Aside } from '@astrojs/starlight/components'; +import { Aside, LinkCard } from '@astrojs/starlight/components'; -![Jan Desktop](../../assets/jan-app-new.png) + +![Jan's Cover Image](../../assets/jan_loaded.png) ## Jan's Goal -> Jan's goal is to build superintelligence that you can self-host and use locally. +> We're working towards open superintelligence to make a viable open-source alternative to platforms like ChatGPT +and Claude that anyone can own and run. -## What is Jan? +## What is Jan Today -Jan is an open-source AI ecosystem that runs on your hardware. We're building towards open superintelligence - a complete AI platform you actually own. +Jan is an open-source AI platform that runs on your hardware. We believe AI should be in the hands of many, not +controlled by a few tech giants. -### The Ecosystem +Today, Jan is: +- **A desktop app** that runs AI models locally or connects to cloud providers +- **A model hub** making the latest open-source models accessible +- **A connector system** that lets AI interact with real-world tools via MCP -**Models**: We build specialized models for real tasks, not general-purpose assistants: -- **Jan-Nano (32k/128k)**: 4B parameters designed for deep research with MCP. The 128k version processes entire papers, codebases, or legal documents in one go -- **Lucy**: 1.7B model that runs agentic web search on your phone. Small enough for CPU, smart enough for complex searches -- **Jan-v1**: 4B model for agentic reasoning and tool use, achieving 91.1% on SimpleQA +Tomorrow, Jan aims to be a complete ecosystem where open models rival or exceed closed alternatives. -We also integrate the best open-source models - from OpenAI's gpt-oss to community GGUF models on Hugging Face. The goal: make powerful AI accessible to everyone, not just those with server farms. - -**Applications**: Jan Desktop runs on your computer today. Web, mobile, and server versions coming in late 2025. Everything syncs, everything works together. - -**Tools**: Connect to the real world through [Model Context Protocol (MCP)](https://modelcontextprotocol.io). Design with Canva, analyze data in Jupyter notebooks, control browsers, execute code in E2B sandboxes. Your AI can actually do things, not just talk about them. - - -**HuggingFace models:** Some require an access token. Add yours in **Settings > Model Providers > Llama.cpp > Hugging Face Access Token**. - -![Add HF Token](../../../assets/hf_token.png) - -### Step 3: Enable GPU Acceleration (Optional) - -For Windows/Linux with compatible graphics cards: - -1. Go to **Settings** > **Hardware** -2. Toggle **GPUs** to ON - -![Turn on GPU acceleration](../../../assets/gpu_accl.png) - - - -### Step 4: Start Chatting +### Step 3: Start Chatting 1. Click the **New Chat** icon 2. Select your model in the input field dropdown 3. Type your message and start chatting -![Create New Thread](../../../assets/threads-new-chat-updated.png) +![Create New Thread](../../../assets/jan_loaded.png) Try asking Jan v1 questions like: - "Explain quantum computing in simple terms" @@ -80,8 +62,6 @@ Try asking Jan v1 questions like: **Want to give Jan v1 access to current web information?** Check out our [Serper MCP tutorial](/docs/mcp-examples/search/serper) to enable real-time web search with 2,500 free searches! - - ## Managing Conversations Jan organizes conversations into threads for easy tracking and revisiting. diff --git a/website/src/content/docs/jan/remote-models/huggingface.mdx b/website/src/content/docs/jan/remote-models/huggingface.mdx new file mode 100644 index 000000000..32100ff41 --- /dev/null +++ b/website/src/content/docs/jan/remote-models/huggingface.mdx @@ -0,0 +1,136 @@ +--- +title: Hugging Face +description: Learn how to integrate Hugging Face models with Jan using the Router or Inference Endpoints. +keywords: + [ + Hugging Face, + Jan, + Jan AI, + Hugging Face Router, + Hugging Face Inference Endpoints, + Hugging Face API, + Hugging Face Integration, + Hugging Face API Integration + ] +--- + +import { Aside } from '@astrojs/starlight/components'; + + +Jan supports Hugging Face models through two methods: the new **HF Router** (recommended) and **Inference Endpoints**. Both methods require a Hugging Face token and **billing to be set up**. + +![HuggingFace Inference Providers](../../../../assets/hf_providers.png) + +## Option 1: HF Router (Recommended) + +The HF Router provides access to models from multiple providers (Replicate, Together AI, SambaNova, Fireworks, Cohere, and more) through a single endpoint. + +### Step 1: Get Your HF Token + +Visit [Hugging Face Settings > Access Tokens](https://huggingface.co/settings/tokens) and create a token. Make sure you have billing set up on your account. + +### Step 2: Configure Jan + +1. Go to **Settings** > **Model Providers** > **HuggingFace** +2. Enter your HF token +3. Use this URL: `https://router.huggingface.co/v1` + +![Jan HF Setup](../../../../assets/hf_jan_setup.png) + +You can find out more about the HF Router [here](https://huggingface.co/docs/inference-providers/index). + +### Step 3: Start Using Models + +Jan comes with three HF Router models pre-configured. Select one and start chatting immediately. + + + +## Option 2: HF Inference Endpoints + +For more control over specific models and deployment configurations, you can use Hugging Face Inference Endpoints. + +### Step 1: Navigate to the HuggingFace Model Hub + +Visit the [Hugging Face Model Hub](https://huggingface.co/models) (make sure you are logged in) and pick the model you want to use. + +![HuggingFace Model Hub](../../../../assets/hf_hub.png) + +### Step 2: Configure HF Inference Endpoint and Deploy + +After you have selected the model you want to use, click on the **Deploy** button and select a deployment method. We will select HF Inference Endpoints for this one. + +![HuggingFace Deployment](../../../../assets/hf_jan_nano.png) + +This will take you to the deployment set up page. For this example, we will leave the default settings as they are under the GPU tab and click on **Create Endpoint**. + +![HuggingFace Deployment](../../../../assets/hf_jan_nano_2.png) + +Once your endpoint is ready, test that it works on the **Test your endpoint** tab. + +![HuggingFace Deployment](../../../../assets/hf_jan_nano_3.png) + +If you get a response, you can click on **Copy** to copy the endpoint URL and API key. + + + +### Step 3: Configure Jan + +If you do not have an API key you can create one under **Settings** > **Access Tokens** [here](https://huggingface.co/settings/tokens). Once you finish, copy the token and add it to Jan alongside your endpoint URL at **Settings** > **Model Providers** > **HuggingFace**. + +**3.1 HF Token** +![Get Token](../../../../assets/hf_jan_nano_5.png) + +**3.2 HF Endpoint URL** +![Endpoint URL](../../../../assets/hf_jan_nano_4.png) + +**3.3 Jan Settings** +![Jan Settings](../../../../assets/hf_jan_nano_6.png) + + + +**3.4 Add Model Details** +![Add Model Details](../../../../assets/hf_jan_nano_7.png) + +### Step 4: Start Using the Model + +Now you can start using the model in any chat. + +![Start Using the Model](../../../../assets/hf_jan_nano_8.png) + +If you want to learn how to use Jan Nano with MCP, check out [the guide here](../jan-models/jan-nano-32). + +## Available Hugging Face Models + +**Option 1 (HF Router):** Access to models from multiple providers as shown in the providers image above. + +**Option 2 (Inference Endpoints):** You can follow the steps above with a large amount of models on Hugging Face and bring them to Jan. Check out other models in the [Hugging Face Model Hub](https://huggingface.co/models). + +## Troubleshooting + +Common issues and solutions: + +**1. Started a chat but the model is not responding** +- Verify your API_KEY/HF_TOKEN is correct and not expired +- Ensure you have billing set up on your HF account +- For Inference Endpoints: Ensure the model you're trying to use is running again since, after a while, they go idle so that you don't get charged when you are not using it + +![Model Running](../../../../assets/hf_jan_nano_9.png) + +**2. Connection Problems** +- Check your internet connection +- Verify Hugging Face's system status +- Look for error messages in [Jan's logs](/docs/troubleshooting#how-to-get-error-logs) + +**3. Model Unavailable** +- Confirm your API key has access to the model +- Check if you're using the correct model ID +- Verify your Hugging Face account has the necessary permissions + +Need more help? Join our [Discord community](https://discord.gg/FTk2MvZwJH) or check the +[Hugging Face's documentation](https://docs.huggingface.co/en/inference-endpoints/index). diff --git a/website/src/content/docs/local-server/data-folder.mdx b/website/src/content/docs/local-server/data-folder.mdx deleted file mode 100644 index 59165137a..000000000 --- a/website/src/content/docs/local-server/data-folder.mdx +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: Jan Data Folder -description: Understand where Jan stores your data and how to monitor server logs. -keywords: - [ - Jan, - local AI, - data folder, - logs, - server logs, - troubleshooting, - privacy, - local storage, - file structure, - ] ---- - -import { Aside, Tabs, TabItem } from '@astrojs/starlight/components'; - -Jan stores all your data locally on your computer. No cloud storage, no external servers - -everything stays on your machine. - -## Quick Access - -**Via Jan Interface:** -1. Go to Settings (⚙️) > Advanced Settings -2. Click the folder icon 📁 - -![Open Jan Data Folder](../../../assets/settings-11.png) - -**Via File Explorer:** - - - -```cmd -%APPDATA%\Jan\data -``` - - -```bash -~/Library/Application Support/Jan/data -``` - - - -```bash -# Default installation -~/.config/Jan/data - -# Custom installation -$XDG_CONFIG_HOME/Jan/data -``` - - - - - -## Monitoring Server Logs - -When Jan's local server is running, you can monitor real-time activity in the logs folder: - -![API Server Logs](../../../assets/api-server-logs.png) - -### Live Log Monitoring - -**Real-time logs show:** -- API requests and responses -- Model loading and inference activity -- Error messages and warnings -- Performance metrics -- Connection attempts from external applications - -**Accessing logs:** -- **In Jan**: System Monitor (footer) > App Log -- **File location**: `/logs/app.log` - -### Log Categories - -| Log Type | What It Shows | When It's Useful | -|----------|---------------|------------------| -| **[APP]** | Core application events | Startup issues, crashes, general errors | -| **[SERVER]** | API server activity | Connection problems, request failures | -| **[SPECS]** | Hardware information | Performance issues, compatibility problems | -| **[MODEL]** | Model operations | Loading failures, inference errors | - -## Data Structure - -``` -jan/ -├── assistants/ # AI personality settings -│ └── jan/ -│ └── assistant.json -├── engines/ # Engine configurations -│ └── llama.cpp/ -├── extensions/ # Add-on modules -│ └── extensions.json -├── logs/ # Server and application logs -│ └── app.log # Main log file -├── models/ # Downloaded AI models -│ └── huggingface.co/ -└── threads/ # Chat conversations - └── thread_id/ - ├── messages.jsonl - └── thread.json -``` - -## Key Folders Explained - -### `/logs/` - Server Activity Hub -Contains all application and server logs. Essential for troubleshooting and monitoring API activity. - -**What you'll find:** -- Real-time server requests -- Model loading status -- Error diagnostics -- Performance data - -### `/models/` - AI Model Storage -Where your downloaded models live. Each model includes: -- `model.gguf` - The actual AI model file -- `model.json` - Configuration and metadata - -### `/threads/` - Chat History -Every conversation gets its own folder with: -- `messages.jsonl` - Complete chat history -- `thread.json` - Thread metadata and settings - -### `/assistants/` - AI Personalities -Configuration files that define how your AI assistants behave, including their instructions and available tools. - -## Privacy & Security - -**Your data stays local:** -- No cloud backups or syncing -- Files stored in standard JSON/JSONL formats -- Complete control over your data -- Easy to backup or migrate - -**File permissions:** -- Only you and Jan can access these files -- Standard user-level permissions -- No elevated access required - - - -## Common Tasks - -### Backup Your Data -Copy the entire Jan data folder to backup: -- All chat history -- Model configurations -- Assistant settings -- Extension data - -### Clear Chat History -Delete individual thread folders in `/threads/` or use Jan's interface to delete conversations. - -### Export Conversations -Thread files are in standard JSON format - readable by any text editor or compatible with other applications. - -### Troubleshooting Data Issues -1. Check `/logs/app.log` for error messages -2. Verify folder permissions -3. Ensure sufficient disk space -4. Restart Jan if files appear corrupted - -## Uninstalling Jan - -If you need to completely remove Jan and all data: - -**Keep data (reinstall later):** Just uninstall the application -**Remove everything:** Delete the Jan data folder after uninstalling - -Detailed uninstall guides: -- [macOS](/docs/desktop/mac#step-2-clean-up-data-optional) -- [Windows](/docs/desktop/windows#step-2-handle-jan-data) -- [Linux](/docs/desktop/linux#uninstall-jan) diff --git a/website/src/content/docs/local-server/index.mdx b/website/src/content/docs/local-server/index.mdx index d81b48b90..76c7de6b7 100644 --- a/website/src/content/docs/local-server/index.mdx +++ b/website/src/content/docs/local-server/index.mdx @@ -1,195 +1,114 @@ --- -title: Jan Local Server -description: Run Jan as a local AI server with OpenAI-compatible API for building AI applications. +title: Local API Server +description: Build AI applications with Jan's OpenAI-compatible API server. --- -import { Aside } from '@astrojs/starlight/components'; +import { Aside, LinkCard } from '@astrojs/starlight/components'; -![Jan's Cover Image](../../../assets/ls.png) +Jan provides an OpenAI-compatible API server that runs entirely on your computer. Use the same API patterns you know from OpenAI, but with complete control over your models and data. -Jan Local Server provides an OpenAI-compatible API that runs entirely on your computer. Build AI applications using familiar API patterns while keeping complete control over your data and models. +## Features -## How It Works +- **OpenAI-compatible** - Drop-in replacement for OpenAI API +- **Local models** - Run GGUF models via llama.cpp +- **Cloud models** - Proxy to OpenAI, Anthropic, and others +- **Privacy-first** - Local models never send data externally +- **No vendor lock-in** - Switch between providers seamlessly -Jan runs a local server powered by [llama.cpp](https://github.com/ggerganov/llama.cpp) that provides an OpenAI-compatible API. By default, it runs at `https://localhost:1337` and works completely offline. +## Quick Start -**What this enables:** -- Connect development tools like [Continue](./continue-dev) and [Cline](https://cline.bot/) to Jan -- Build AI applications without cloud dependencies -- Use both local and cloud models through the same API -- Maintain full privacy for local model interactions +Start the server in **Settings > Local API Server** and make requests to `http://localhost:1337/v1`: -## Key Features +```bash +curl http://localhost:1337/v1/chat/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer YOUR_API_KEY" \ + -d '{ + "model": "MODEL_ID", + "messages": [{"role": "user", "content": "Hello!"}] + }' +``` -**Local AI Models** -- Download popular open-source models (Llama, Gemma, Qwen) from Hugging Face -- Import any GGUF files from your computer -- Run models completely offline +## Documentation -**Cloud Integration** -- Connect to cloud services (OpenAI, Anthropic, Mistral, Groq) -- Use your own API keys -- Switch between local and cloud models seamlessly +- [**API Reference**](/api) - Interactive API documentation with Try It Out +- [**API Configuration**](./api-server) - Server settings, authentication, CORS +- [**Engine Settings**](./llama-cpp) - Configure llama.cpp for your hardware +- [**Server Settings**](./settings) - Advanced configuration options -**Developer-Friendly** -- OpenAI-compatible API for easy integration -- Chat interface for testing and configuration -- Model parameter customization + -**Complete Privacy** -- All data stored locally -- No cloud dependencies for local models -- You control what data leaves your machine +## Integration Examples -## Why Choose Jan? +### Continue (VS Code) +```json +{ + "models": [{ + "title": "Jan", + "provider": "openai", + "baseURL": "http://localhost:1337/v1", + "apiKey": "YOUR_API_KEY", + "model": "MODEL_ID" + }] +} +``` -**Truly Open Source** -- Apache 2.0 license - no restrictions -- Community-driven development -- Full transparency +### Python (OpenAI SDK) +```python +from openai import OpenAI -**Local-First Design** -- Works 100% offline with local models -- Data stays on your machine -- No vendor lock-in +client = OpenAI( + base_url="http://localhost:1337/v1", + api_key="YOUR_API_KEY" +) -**Flexible Model Support** -- Your choice of AI models -- Both local and cloud options -- Easy model switching +response = client.chat.completions.create( + model="MODEL_ID", + messages=[{"role": "user", "content": "Hello!"}] +) +``` -**No Data Collection** -- We don't collect or sell user data -- Local conversations stay local -- [Read our Privacy Policy](./privacy) +### JavaScript/TypeScript +```javascript +const response = await fetch('http://localhost:1337/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer YOUR_API_KEY' + }, + body: JSON.stringify({ + model: 'MODEL_ID', + messages: [{ role: 'user', content: 'Hello!' }] + }) +}); +``` + +## Supported Endpoints + +| Endpoint | Description | +|----------|-------------| +| `/v1/chat/completions` | Chat completions (streaming supported) | +| `/v1/models` | List available models | +| `/v1/models/{id}` | Get model information | -## Philosophy +## Why Use Jan's API? -Jan is built to be **user-owned**. This means: -- **True open source** - Apache 2.0 license with no hidden restrictions -- **Local data storage** - following [local-first principles](https://www.inkandswitch.com/local-first) -- **Internet optional** - works completely offline -- **Free choice** - use any AI models you want -- **No surveillance** - we don't collect or sell your data +**Privacy** - Your data stays on your machine with local models +**Cost** - No API fees for local model usage +**Control** - Choose your models, parameters, and hardware +**Flexibility** - Mix local and cloud models as needed -Read more about our [philosophy](/about#philosophy). +## Related Resources -## Inspiration - -Jan draws inspiration from [Calm Computing](https://en.wikipedia.org/wiki/Calm_technology) and the Disappearing Computer - technology that works quietly in the background without demanding constant attention. - -## Built With - -Jan stands on the shoulders of excellent open-source projects: -- [llama.cpp](https://github.com/ggerganov/llama.cpp) - Local AI model inference -- [Scalar](https://github.com/scalar/scalar) - API documentation - -## Frequently Asked Questions - -## What is Jan? - - Jan is a privacy-focused AI assistant that runs locally on your computer. It's an alternative to ChatGPT, Claude, and other cloud-based AI tools, with optional cloud AI support when you want it. - - -## How do I get started? - - Download Jan, add a model (either download locally or add a cloud API key), and start chatting. Check our [Quick Start guide](/docs/quickstart) for detailed setup instructions. - - -## What systems does Jan support? - - Jan works on all major operating systems: - - [macOS](/docs/desktop/mac#compatibility) - Intel and Apple Silicon - - [Windows](/docs/desktop/windows#compatibility) - x64 systems - - [Linux](/docs/desktop/linux) - Most distributions - - Jan supports various hardware: - - NVIDIA GPUs (CUDA acceleration) - - AMD GPUs (Vulkan support) - - Intel Arc GPUs (Vulkan support) - - Any GPU with Vulkan support - - CPU-only operation - - -## How does Jan protect my privacy? - - Jan prioritizes privacy through: - - **100% offline operation** with local models - - **Local data storage** - everything stays on your device - - **Open-source transparency** - you can verify what Jan does - - **No data collection** - we never see your conversations - - - - All your files and chat history are stored locally in the [Jan Data Folder](./data-folder). See our complete [Privacy Policy](./privacy). - - -## What AI models can I use? - - **Local models:** - - Download optimized models from the [Jan Hub](/docs/manage-models) - - Import GGUF models from Hugging Face - - Use any compatible local model files - - **Cloud models:** - - OpenAI (GPT-4, ChatGPT) - - Anthropic (Claude) - - Mistral, Groq, and others - - Bring your own API keys - - -## Is Jan really free? - - Yes! Jan is completely free and open-source with no subscription fees. - - **What's free:** - - Jan application and all features - - Local model usage (once downloaded) - - Local server and API - - **What costs money:** - - Cloud model usage (you pay providers directly) - - We add no markup to cloud service costs - - -## Can Jan work offline? - - Absolutely! Once you download a local model, Jan works completely offline with no internet connection needed. This is one of Jan's core features. - - -## How can I get help or contribute? - - **Get help:** - - Join our [Discord community](https://discord.gg/qSwXFx6Krr) - - Check the [Troubleshooting guide](./troubleshooting) - - Ask in [#🆘|jan-help](https://discord.com/channels/1107178041848909847/1192090449725358130) - - **Contribute:** - - Contribute on [GitHub](https://github.com/menloresearch/jan) - - No permission needed to submit improvements - - Help other users in Discord - - -## Can I self-host Jan? - - Yes! We fully support self-hosting. You can: - - Download Jan directly for personal use - - Fork the [GitHub repository](https://github.com/menloresearch/jan) - - Build from source - - Deploy on your own infrastructure - - -## What does 'Jan' stand for? - - "Just a Name" - we admit we're not great at marketing! 😄 - - -## Are you hiring? - - Yes! We love hiring from our community. Check our open positions at [Careers](https://menlo.bamboohr.com/careers). +- [Models Overview](/docs/jan/manage-models) - Available models +- [Data Storage](/docs/jan/data-folder) - Where Jan stores data +- [Troubleshooting](/docs/jan/troubleshooting) - Common issues +- [GitHub Repository](https://github.com/janhq/jan) - Source code diff --git a/website/src/content/docs/local-server/llama-cpp.mdx b/website/src/content/docs/local-server/llama-cpp.mdx index ab4522b37..4263c80c3 100644 --- a/website/src/content/docs/local-server/llama-cpp.mdx +++ b/website/src/content/docs/local-server/llama-cpp.mdx @@ -1,6 +1,6 @@ --- title: llama.cpp Engine -description: Configure Jan's local AI engine for optimal performance. +description: Configure Jan's local AI engine for optimal performance on your hardware. keywords: [ Jan, @@ -12,162 +12,377 @@ keywords: GPU acceleration, CPU processing, model optimization, + CUDA, + Metal, + Vulkan, ] --- -import { Aside, Tabs, TabItem } from '@astrojs/starlight/components' +import { Aside, Tabs, TabItem } from '@astrojs/starlight/components'; -`llama.cpp` is the core **inference engine** Jan uses to run AI models locally on your computer. This section -covers the settings for the engine itself, which control *how* a model processes information on your hardware. +## What is llama.cpp? - +llama.cpp is the core inference engine that powers Jan's ability to run AI models locally on your computer. Created by Georgi Gerganov, it's designed to run large language models efficiently on consumer hardware without requiring specialized AI accelerators or cloud connections. + +**Key benefits:** +- Run models entirely offline after download +- Use your existing hardware (CPU, GPU, or Apple Silicon) +- Complete privacy - conversations never leave your device +- No API costs or subscription fees ## Accessing Engine Settings -Find llama.cpp settings at **Settings** > **Local Engine** > **llama.cpp**: +Navigate to **Settings** > **Model Providers** > **Llama.cpp**: -![llama.cpp](../../../assets/llama.cpp-01-updated.png) +![llama.cpp Settings](../../../assets/llama.cpp-01-updated.png) -## When to Adjust Settings - -You might need to modify these settings if: -- Models load slowly or don't work -- You've installed new hardware (like a graphics card) -- You want to optimize performance for your specific setup - ## Engine Management -| Feature | What It Does | When You Need It | -|---------|-------------|------------------| -| **Engine Version** | Shows current llama.cpp version | Check compatibility with newer models | -| **Check Updates** | Downloads engine updates | When new models require updated engine | +| Feature | What It Does | When to Use | +|---------|-------------|-------------| +| **Engine Version** | Shows current llama.cpp version | Check when models require newer engine | +| **Check Updates** | Downloads latest engine | Update for new model support or bug fixes | | **Backend Selection** | Choose hardware-optimized version | After hardware changes or performance issues | -## Hardware Backends +## Selecting the Right Backend -Different backends are optimized for different hardware. Pick the one that matches your computer: - - +Different backends are optimized for specific hardware. Choose the one that matches your system: + -### NVIDIA Graphics Cards (Fastest) -**For CUDA 12.0:** -- `llama.cpp-avx2-cuda-12-0` (most common) -- `llama.cpp-avx512-cuda-12-0` (newer Intel/AMD CPUs) - -**For CUDA 11.7:** -- `llama.cpp-avx2-cuda-11-7` (older drivers) - -### CPU Only -- `llama.cpp-avx2` (modern CPUs) -- `llama.cpp-avx` (older CPUs) -- `llama.cpp-noavx` (very old CPUs) - -### Other Graphics Cards -- `llama.cpp-vulkan` (AMD, Intel Arc) - - - - - ### NVIDIA Graphics Cards -- `llama.cpp-avx2-cuda-12-0` (recommended) -- `llama.cpp-avx2-cuda-11-7` (older drivers) +Check your CUDA version in NVIDIA Control Panel, then select: + +**CUDA 12.0 (Most Common):** +- `llama.cpp-avx2-cuda-12-0` - Modern CPUs with AVX2 +- `llama.cpp-avx512-cuda-12-0` - Newer Intel/AMD CPUs with AVX512 +- `llama.cpp-avx-cuda-12-0` - Older CPUs without AVX2 + +**CUDA 11.7 (Older Drivers):** +- `llama.cpp-avx2-cuda-11-7` - Modern CPUs +- `llama.cpp-avx-cuda-11-7` - Older CPUs ### CPU Only -- `llama.cpp-avx2` (modern CPUs) -- `llama.cpp-arm64` (ARM processors) +- `llama.cpp-avx2` - Most modern CPUs (2013+) +- `llama.cpp-avx512` - High-end Intel/AMD CPUs +- `llama.cpp-avx` - Older CPUs (2011-2013) +- `llama.cpp-noavx` - Very old CPUs (pre-2011) -### Other Graphics Cards -- `llama.cpp-vulkan` (AMD, Intel graphics) +### AMD/Intel Graphics +- `llama.cpp-vulkan` - AMD Radeon, Intel Arc, Intel integrated + + ### Apple Silicon (M1/M2/M3/M4) -- `llama.cpp-mac-arm64` (recommended) +- `llama.cpp-mac-arm64` - Automatically uses GPU acceleration via Metal ### Intel Macs -- `llama.cpp-mac-amd64` +- `llama.cpp-mac-amd64` - CPU-only processing + + +### NVIDIA Graphics Cards +- `llama.cpp-avx2-cuda-12-0` - CUDA 12.0+ with modern CPU +- `llama.cpp-avx2-cuda-11-7` - CUDA 11.7+ with modern CPU + +### CPU Only +- `llama.cpp-avx2` - x86_64 modern CPUs +- `llama.cpp-avx512` - High-end Intel/AMD CPUs +- `llama.cpp-arm64` - ARM processors (Raspberry Pi, etc.) + +### AMD/Intel Graphics +- `llama.cpp-vulkan` - Open-source GPU acceleration + + ## Performance Settings -| Setting | What It Does | Recommended | Impact | -|---------|-------------|-------------|---------| -| **Continuous Batching** | Handle multiple requests simultaneously | Enabled | Faster when using tools or multiple chats | -| **Parallel Operations** | Number of concurrent requests | 4 | Higher = more multitasking, uses more memory | -| **CPU Threads** | Processor cores to use | Auto | More threads can speed up CPU processing | +Configure how the engine processes requests: -## Memory Settings +### Core Performance -| Setting | What It Does | Recommended | When to Change | -|---------|-------------|-------------|----------------| -| **Flash Attention** | Efficient memory usage | Enabled | Leave enabled unless problems occur | -| **Caching** | Remember recent conversations | Enabled | Speeds up follow-up questions | -| **KV Cache Type** | Memory vs quality trade-off | f16 | Change to q8_0 if low on memory | -| **mmap** | Efficient model loading | Enabled | Helps with large models | -| **Context Shift** | Handle very long conversations | Disabled | Enable for very long chats | +| Setting | What It Does | Default | When to Adjust | +|---------|-------------|---------|----------------| +| **Auto-update engine** | Automatically updates llama.cpp to latest version | Enabled | Disable if you need version stability | +| **Auto-Unload Old Models** | Frees memory by unloading unused models | Disabled | Enable if switching between many models | +| **Threads** | CPU cores for text generation (`-1` = all cores) | -1 | Reduce if you need CPU for other tasks | +| **Threads (Batch)** | CPU cores for batch processing | -1 | Usually matches Threads setting | +| **Context Shift** | Removes old text to fit new text in memory | Disabled | Enable for very long conversations | +| **Max Tokens to Predict** | Maximum response length (`-1` = unlimited) | -1 | Set a limit to control response size | -### Memory Options Explained -- **f16**: Best quality, uses more memory -- **q8_0**: Balanced memory and quality -- **q4_0**: Least memory, slight quality reduction +**Simple Analogy:** Think of threads like workers in a factory. More workers (threads) means faster production, but if you need workers elsewhere (other programs), you might want to limit how many the factory uses. -## Quick Troubleshooting +### Batch Processing -**Models won't load:** -- Try a different backend -- Check available RAM/VRAM -- Update engine version +| Setting | What It Does | Default | When to Adjust | +|---------|-------------|---------|----------------| +| **Batch Size** | Logical batch size for prompt processing | 2048 | Lower if you have memory issues | +| **uBatch Size** | Physical batch size for hardware | 512 | Match your GPU's capabilities | +| **Continuous Batching** | Process multiple requests at once | Enabled | Keep enabled for efficiency | -**Slow performance:** -- Verify GPU acceleration is active -- Close memory-intensive applications -- Increase GPU Layers in model settings +**Simple Analogy:** Batch size is like the size of a delivery truck. A bigger truck (batch) can carry more packages (tokens) at once, but needs a bigger garage (memory) and more fuel (processing power). + +### Multi-GPU Settings + +| Setting | What It Does | Default | When to Adjust | +|---------|-------------|---------|----------------| +| **GPU Split Mode** | How to divide model across GPUs | Layer | Change only with multiple GPUs | +| **Main GPU Index** | Primary GPU for processing | 0 | Select different GPU if needed | + +**When to tweak:** Only adjust if you have multiple GPUs and want to optimize how the model is distributed across them. + +## Memory Configuration + +Control how models use system and GPU memory: + +### Memory Management + +| Setting | What It Does | Default | When to Adjust | +|---------|-------------|---------|----------------| +| **Flash Attention** | Optimized memory usage for attention | Enabled | Disable only if having stability issues | +| **Disable mmap** | Turn off memory-mapped file loading | Disabled | Enable if experiencing crashes | +| **MLock** | Lock model in RAM (no swap to disk) | Disabled | Enable if you have plenty of RAM | +| **Disable KV Offload** | Keep conversation memory on CPU | Disabled | Enable if GPU memory is limited | + +**Simple Analogy:** Think of your computer's memory like a desk workspace: +- **mmap** is like keeping reference books open to specific pages (efficient) +- **mlock** is like gluing papers to your desk so they can't fall off (uses more space but faster access) +- **Flash Attention** is like using sticky notes instead of full pages (saves space) + +### KV Cache Configuration + +| Setting | What It Does | Options | When to Adjust | +|---------|-------------|---------|----------------| +| **KV Cache K Type** | Precision for "keys" in memory | f16, q8_0, q4_0 | Lower precision saves memory | +| **KV Cache V Type** | Precision for "values" in memory | f16, q8_0, q4_0 | Lower precision saves memory | +| **KV Cache Defragmentation Threshold** | When to reorganize memory (0.1 = 10% fragmented) | 0.1 | Increase if seeing memory errors | + +**Memory Precision Guide:** +- **f16** (default): Full quality, uses most memory - like HD video +- **q8_0**: Good quality, moderate memory - like standard video +- **q4_0**: Acceptable quality, least memory - like compressed video + +**When to adjust:** Start with f16. If you run out of memory, try q8_0. Only use q4_0 if absolutely necessary. + +## Advanced Settings + +### RoPE (Rotary Position Embeddings) + +| Setting | What It Does | Default | When to Adjust | +|---------|-------------|---------|----------------| +| **RoPE Scaling Method** | How to extend context length | None | For contexts beyond model's training | +| **RoPE Scale Factor** | Context extension multiplier | 1 | Increase for longer contexts | +| **RoPE Frequency Base** | Base frequency (0 = auto) | 0 | Leave at 0 unless specified | +| **RoPE Frequency Scale Factor** | Frequency adjustment | 1 | Advanced users only | + +**Simple Analogy:** RoPE is like the model's sense of position in a conversation. Imagine reading a book: +- **Normal**: You remember where you are on the page +- **RoPE Scaling**: Like using a magnifying glass to fit more words on the same page +- Scaling too much can make the text (context) blurry (less accurate) + +**When to use:** Only adjust if you need conversations longer than the model's default context length and understand the quality tradeoffs. + +### Mirostat Sampling + +| Setting | What It Does | Default | When to Adjust | +|---------|-------------|---------|----------------| +| **Mirostat Mode** | Alternative text generation method | Disabled | Try for more consistent output | +| **Mirostat Learning Rate** | How quickly it adapts (eta) | 0.1 | Lower = more stable | +| **Mirostat Target Entropy** | Target randomness (tau) | 5 | Lower = more focused | + +**Simple Analogy:** Mirostat is like cruise control for text generation: +- **Regular sampling**: You manually control speed (randomness) with temperature +- **Mirostat**: Automatically adjusts to maintain consistent "speed" (perplexity) +- **Target Entropy**: Your desired cruising speed +- **Learning Rate**: How quickly the cruise control adjusts + +**When to use:** Enable Mirostat if you find regular temperature settings produce inconsistent results. Start with defaults and adjust tau (3-7 range) for different styles. + +### Structured Output + +| Setting | What It Does | Default | When to Adjust | +|---------|-------------|---------|----------------| +| **Grammar File** | BNF grammar to constrain output | None | For specific output formats | +| **JSON Schema File** | JSON schema to enforce structure | None | For JSON responses | + +**Simple Analogy:** These are like templates or forms the model must fill out: +- **Grammar**: Like Mad Libs - the model can only put words in specific places +- **JSON Schema**: Like a tax form - specific fields must be filled with specific types of data + +**When to use:** Only when you need guaranteed structured output (like JSON for an API). Most users won't need these. + +## Quick Optimization Guide + +### For Best Performance +1. **Enable**: Flash Attention, Continuous Batching +2. **Set Threads**: -1 (use all CPU cores) +3. **Batch Size**: Keep defaults (2048/512) + +### For Limited Memory +1. **Enable**: Auto-Unload Models, Flash Attention +2. **KV Cache**: Set both to q8_0 or q4_0 +3. **Reduce**: Batch Size to 512/128 + +### For Long Conversations +1. **Enable**: Context Shift +2. **Consider**: RoPE scaling (with quality tradeoffs) +3. **Monitor**: Memory usage in System Monitor + +### For Multiple Models +1. **Enable**: Auto-Unload Old Models +2. **Disable**: MLock (saves RAM) +3. **Use**: Default memory settings + +## Troubleshooting Settings + +**Model crashes or errors:** +- Disable mmap +- Reduce Batch Size +- Switch KV Cache to q8_0 **Out of memory:** -- Change KV Cache Type to q8_0 -- Reduce Context Size in model settings -- Try a smaller model +- Enable Auto-Unload +- Reduce KV Cache precision +- Lower Batch Size -**Crashes or errors:** -- Switch to a more stable backend (avx instead of avx2) -- Update graphics drivers -- Check system temperature +**Slow performance:** +- Check Threads = -1 +- Enable Flash Attention +- Verify GPU backend is active -## Quick Setup Guide +**Inconsistent output:** +- Try Mirostat mode +- Adjust temperature in model settings +- Check if Context Shift is needed -**Most users:** -1. Use default settings -2. Only change if problems occur +## Model-Specific Settings -**NVIDIA GPU users:** -1. Download CUDA backend -2. Ensure GPU Layers is set high -3. Enable Flash Attention +Each model can override engine defaults. Access via the gear icon next to any model: -**Performance optimization:** -1. Enable Continuous Batching -2. Use appropriate backend for hardware -3. Monitor memory usage +![Model Settings](../../../assets/trouble-shooting-04.png) + +| Setting | What It Controls | Impact | +|---------|-----------------|---------| +| **Context Length** | Conversation history size | Higher = more memory usage | +| **GPU Layers** | Model layers on GPU | Higher = faster but more VRAM | +| **Temperature** | Response randomness | 0.1 = focused, 1.0 = creative | +| **Top P** | Token selection pool | Lower = more focused responses | + + + +## Troubleshooting + +### Models Won't Load +1. **Wrong backend:** Try CPU-only backend first (`avx2` or `avx`) +2. **Insufficient memory:** Check RAM/VRAM requirements +3. **Outdated engine:** Update to latest version +4. **Corrupted download:** Re-download the model + +### Slow Performance +1. **No GPU acceleration:** Verify correct CUDA/Vulkan backend +2. **Too few GPU layers:** Increase in model settings +3. **CPU bottleneck:** Check thread count matches cores +4. **Memory swapping:** Reduce context size or use smaller model + +### Out of Memory +1. **Reduce quality:** Switch KV Cache to q8_0 or q4_0 +2. **Lower context:** Decrease context length in model settings +3. **Fewer layers:** Reduce GPU layers +4. **Smaller model:** Use quantized versions (Q4 vs Q8) + +### Crashes or Instability +1. **Backend mismatch:** Use more stable variant (avx vs avx2) +2. **Driver issues:** Update GPU drivers +3. **Overheating:** Monitor temperatures, improve cooling +4. **Power limits:** Check PSU capacity for high-end GPUs + +## Performance Benchmarks + +Typical performance with different configurations: + +| Hardware | Model Size | Backend | Tokens/sec | +|----------|------------|---------|------------| +| RTX 4090 | 7B Q4 | CUDA 12 | 80-120 | +| RTX 3070 | 7B Q4 | CUDA 12 | 40-60 | +| M2 Pro | 7B Q4 | Metal | 30-50 | +| Ryzen 9 | 7B Q4 | AVX2 | 10-20 | + +## Advanced Configuration + +### Custom Compilation + +For maximum performance, compile llama.cpp for your specific hardware: + +```bash +# Clone and build with specific optimizations +git clone https://github.com/ggerganov/llama.cpp +cd llama.cpp + +# Examples for different systems +make LLAMA_CUDA=1 # NVIDIA GPUs +make LLAMA_METAL=1 # Apple Silicon +make LLAMA_VULKAN=1 # AMD/Intel GPUs +``` + +### Environment Variables + +Fine-tune behavior with environment variables: + +```bash +# Force specific GPU +export CUDA_VISIBLE_DEVICES=0 + +# Thread tuning +export OMP_NUM_THREADS=8 + +# Memory limits +export GGML_CUDA_NO_PINNED=1 +``` + +## Best Practices + +**For Beginners:** +1. Use default settings +2. Start with smaller models (3-7B parameters) +3. Enable GPU acceleration if available + +**For Power Users:** +1. Match backend to hardware precisely +2. Tune memory settings for your VRAM +3. Experiment with parallel slots for multi-tasking + +**For Developers:** +1. Enable verbose logging for debugging +2. Use consistent settings across deployments +3. Monitor resource usage during inference + +## Related Resources + +- [Model Parameters Guide](/docs/jan/explanation/model-parameters) - Fine-tune model behavior +- [Troubleshooting Guide](/docs/jan/troubleshooting) - Detailed problem-solving +- [Hardware Requirements](/docs/desktop/mac#compatibility) - System specifications +- [API Server Settings](./api-server) - Configure the local API diff --git a/website/src/content/docs/local-server/settings.mdx b/website/src/content/docs/local-server/settings.mdx index 8f366ef5f..a95691de6 100644 --- a/website/src/content/docs/local-server/settings.mdx +++ b/website/src/content/docs/local-server/settings.mdx @@ -1,221 +1,125 @@ --- -title: Settings -description: Configure Jan to work best for your needs and hardware. +title: Server Settings +description: Configure advanced server settings for Jan's local API. keywords: [ Jan, + local server, settings, configuration, - model management, - privacy, - hardware settings, - local AI, - customization, + API server, + performance, + logging, ] --- -import { Aside, Steps } from '@astrojs/starlight/components' +import { Aside } from '@astrojs/starlight/components' -# Settings +This page covers server-specific settings for Jan's local API. For general Jan settings, see the main [Settings Guide](/docs/jan/settings). -Access Jan's settings by clicking the Settings icon in the bottom left corner. +## Accessing Server Settings -## Managing AI Models +Navigate to **Settings** in Jan to configure server-related options. -Find all model options at **Settings** > **Model Providers**: +## Server Configuration -### Adding Models +### API Server Settings -**From Hugging Face:** -- Enter a model's ID (like `microsoft/DialoGPT-medium`) in the search bar -- **Need authentication?** Some models require a Hugging Face token - add yours at **Settings > Model Providers > Hugging Face Access Token** +Configure the local API server at **Settings > Local API Server**: -**From Your Computer:** -- Click **Import Model** and select GGUF files from your computer -- Works with any compatible model files you've downloaded +- **Host & Port** - Network binding configuration +- **API Key** - Authentication for API requests +- **CORS** - Cross-origin resource sharing +- **Verbose Logging** - Detailed request/response logs -### Managing Existing Models +See our [API Configuration Guide](./api-server) for complete details. -**Start a model:** -1. Open a new chat and select the model you want -2. Or go to **Settings > Model Providers** and click the **Start** button +### Engine Configuration -**Remove a model:** -- Click the trash icon next to the **Start** button -- Confirm deletion when prompted +Configure llama.cpp engine at **Settings > Model Providers > Llama.cpp**: -### Hugging Face Token Setup +- **Backend Selection** - Hardware-optimized versions +- **Performance Settings** - Batching, threading, memory +- **Model Defaults** - Context size, GPU layers -For restricted models (like Meta's Llama models): -1. Get your token from [Hugging Face Tokens](https://huggingface.co/docs/hub/en/security-tokens) -2. Add it at **Settings > Model Providers > Hugging Face** +See our [Engine Settings Guide](./llama-cpp) for optimization tips. -## Model Configuration (Gear Icon) +## Logging & Monitoring -![Model Settings](../../../assets/trouble-shooting-04.png) +### Server Logs -Click the gear icon next to any model to adjust how it behaves: +Monitor API activity in real-time: -**Basic Settings:** -- **Context Size**: How much conversation history the model remembers -- **GPU Layers**: How much of the model runs on your graphics card (higher = faster, but uses more GPU memory) -- **Temperature**: Controls creativity (0.1 = focused, 1.0 = creative) - -**Advanced Controls:** -- **Top K & Top P**: Fine-tune how the model picks words (lower = more focused) -- **Min P**: Minimum probability threshold for word selection -- **Repeat Penalty**: Prevents the model from repeating itself too much -- **Presence Penalty**: Encourages the model to use varied vocabulary - - - -## Hardware Monitoring - -Check your computer's performance at **Settings** > **Hardware**: - -- **CPU, RAM, GPU**: Real-time usage and specifications -- **GPU Acceleration**: Turn GPU acceleration on/off -- **Temperature monitoring**: Keep an eye on system heat - -![Hardware](../../../assets/hardware.png) - - - -## Personalization - -### Visual Appearance - -Customize Jan's look at **Settings** > **Appearance**: -- **Theme**: Choose light or dark mode -- **Colors**: Pick your preferred color scheme -- **Code highlighting**: Adjust syntax colors for programming discussions - -![Appearance](../../../assets/settings-04.png) - -### Writing Assistance - -**Spell Check:** Jan can help catch typing mistakes in your messages. - -![Spell Check](../../../assets/settings-06.png) - -## Privacy & Data Control - -Access privacy settings at **Settings** > **Privacy**: - -### Usage Analytics - -**Default: No data collection.** Everything stays on your computer. - -**Optional: Help improve Jan** -- Toggle **Analytics** to share anonymous usage patterns -- No conversations or personal data ever shared -- Change this setting anytime - - - -![Analytics](../../../assets/settings-07.png) +1. Enable **Verbose Server Logs** in API settings +2. View logs at **System Monitor** > **App Log** +3. Filter by `[SERVER]` tags for API-specific events ### Log Management -**Viewing System Logs:** -- Logs help troubleshoot problems -- Click the folder icon to open App Logs and System Logs -- Logs are automatically deleted after 24 hours - -![View Logs](../../../assets/settings-08.png) - -**Clearing Logs:** -- Click **Clear** to remove all log files immediately -- Useful before sharing your computer or troubleshooting - - - -![Clear Logs](../../../assets/settings-09.png) - -### Data Folder Management - -Jan stores everything locally on your computer in standard file formats. - -**Access Your Data:** -- Click the folder icon to open Jan's data directory -- Find your chat history, models, and settings -- All files are yours to backup, move, or examine - -![Open Jan Data Folder](../../../assets/settings-11.png) - -**Change Storage Location:** -1. Click the pencil icon to edit the data folder location -2. Choose an empty directory -3. Confirm the move (original folder stays intact) -4. Restart Jan to complete the change - -![Edit Jan Data Folder](../../../assets/settings-12.png) +- **Location**: Stored in [Jan Data Folder](/docs/jan/data-folder) +- **Retention**: Automatically cleared after 24 hours +- **Manual Clear**: Settings > Advanced > Clear Logs -## Local API Server +## Performance Tuning -All settings for running Jan as a local, OpenAI-compatible server have been moved to their own dedicated page for clarity. +### Memory Management -This includes configuration for: -- Server Host and Port -- API Keys -- CORS (Cross-Origin Resource Sharing) -- Verbose Logging +For optimal server performance: -[**Go to Local API Server Settings →**](/docs/local-server/api-server) +- **High Traffic**: Increase parallel slots in engine settings +- **Limited RAM**: Reduce KV cache quality (q8_0 or q4_0) +- **Multiple Models**: Enable model unloading after idle timeout -## Emergency Options +### Network Configuration -### Factory Reset +Advanced networking options: -**When to use:** Only as a last resort for serious problems that other solutions can't fix. +- **Local Only**: Use `127.0.0.1` (default, most secure) +- **LAN Access**: Use `0.0.0.0` (allows network connections) +- **Custom Port**: Change from default `1337` if conflicts exist -**What it does:** Returns Jan to its original state - deletes everything. +## Security Considerations -**Steps:** -1. Click **Reset** under "Reset to Factory Settings" -2. Type **RESET** to confirm you understand this deletes everything -3. Optionally keep your current data folder location -4. Click **Reset Now** -5. Restart Jan +### API Authentication -![Factory Reset](../../../assets/settings-17.png) +- Always set a strong API key +- Rotate keys regularly for production use +- Never expose keys in client-side code -![Reset Confirmation](../../../assets/settings-18.png) +### Network Security - +- Keep server on `localhost` unless LAN access is required +- Use firewall rules to restrict access +- Consider VPN for remote access needs -**Try these first:** -- Restart Jan -- Check the [Troubleshooting Guide](./troubleshooting) -- Ask for help on [Discord](https://discord.gg/qSwXFx6Krr) +## Troubleshooting Server Issues -## Quick Tips +### Common Problems -**For new users:** -- Start with default settings -- Try a few different models to find what works best -- Enable GPU acceleration if you have a graphics card +**Server won't start:** +- Check port availability (`netstat -an | grep 1337`) +- Verify no other instances running +- Try different port number -**For performance:** -- Monitor hardware usage in real-time -- Adjust GPU layers based on your graphics card memory -- Use smaller models on older hardware +**Connection refused:** +- Ensure server is started +- Check host/port configuration +- Verify firewall settings -**For privacy:** -- All data stays local by default -- Check the data folder to see exactly what's stored -- Analytics are opt-in only +**Authentication failures:** +- Confirm API key matches configuration +- Check Authorization header format +- Ensure no extra spaces in key + +For more issues, see our [Troubleshooting Guide](/docs/jan/troubleshooting). + +## Related Resources + +- [API Configuration](./api-server) - Detailed API settings +- [Engine Settings](./llama-cpp) - Hardware optimization +- [Data Folder](/docs/jan/data-folder) - Storage locations +- [Models Overview](/docs/jan/manage-models) - Model management \ No newline at end of file diff --git a/website/src/content/docs/local-server/troubleshooting.mdx b/website/src/content/docs/local-server/troubleshooting.mdx deleted file mode 100644 index ad2ce70d8..000000000 --- a/website/src/content/docs/local-server/troubleshooting.mdx +++ /dev/null @@ -1,323 +0,0 @@ ---- -title: Troubleshooting -description: Fix common issues and optimize Jan's performance with this comprehensive guide. -keywords: - [ - Jan, - troubleshooting, - error fixes, - performance issues, - GPU problems, - installation issues, - common errors, - local AI, - technical support, - ] ---- - -import { Aside, Steps, Tabs, TabItem } from '@astrojs/starlight/components' - -## Getting Help: Error Logs - -When Jan isn't working properly, error logs help identify the problem. Here's how to get them: - -### Quick Access to Logs - -**In Jan Interface:** -1. Look for **System Monitor** in the footer -2. Click **App Log** - -![App log](../../../assets/trouble-shooting-02.png) - -**Via Terminal:** -```bash -# macOS/Linux -tail -n 50 ~/Library/Application\ Support/Jan/data/logs/app.log - -# Windows -type %APPDATA%\Jan\data\logs\app.log -``` - - - -## Common Issues & Solutions - -### Jan Won't Start (Broken Installation) - -If Jan gets stuck after installation or won't start properly: - - - - -**Clean Reinstall Steps:** - -1. **Uninstall Jan** from Applications folder - -2. **Delete all Jan data:** -```bash -rm -rf ~/Library/Application\ Support/Jan -``` - -3. **Kill any background processes** (for versions before 0.4.2): -```bash -ps aux | grep nitro -# Find process IDs and kill them: -kill -9 -``` - -4. **Download fresh copy** from [jan.ai](/download) - - - - - -**Clean Reinstall Steps:** - -1. **Uninstall Jan** via Control Panel - -2. **Delete application data:** -```cmd -cd C:\Users\%USERNAME%\AppData\Roaming -rmdir /S Jan -``` - -3. **Kill background processes** (for versions before 0.4.2): -```cmd -# Find nitro processes -tasklist | findstr "nitro" -# Kill them by PID -taskkill /F /PID -``` - -4. **Download fresh copy** from [jan.ai](/download) - - - - - -**Clean Reinstall Steps:** - -1. **Uninstall Jan:** -```bash -# For Debian/Ubuntu -sudo apt-get remove jan - -# For AppImage - just delete the file -``` - -2. **Delete application data:** -```bash -# Default location -rm -rf ~/.config/Jan - -# Or custom location -rm -rf $XDG_CONFIG_HOME/Jan -``` - -3. **Kill background processes** (for versions before 0.4.2): -```bash -ps aux | grep nitro -kill -9 -``` - -4. **Download fresh copy** from [jan.ai](/download) - - - - - - -### NVIDIA GPU Not Working - -If Jan isn't using your NVIDIA graphics card for acceleration: - - -### Step 1: Check Your Hardware Setup - -**Verify GPU Detection:** - -*Windows:* Right-click desktop → NVIDIA Control Panel, or check Device Manager → Display Adapters - -*Linux:* Run `lspci | grep -i nvidia` - -**Install Required Software:** - -**NVIDIA Driver (470.63.01 or newer):** -1. Download from [nvidia.com/drivers](https://www.nvidia.com/drivers/) -2. Test: Run `nvidia-smi` in terminal - -**CUDA Toolkit (11.7 or newer):** -1. Download from [CUDA Downloads](https://developer.nvidia.com/cuda-downloads) -2. Test: Run `nvcc --version` - -**Linux Additional Requirements:** -```bash -# Install required packages -sudo apt update && sudo apt install gcc-11 g++-11 cpp-11 - -# Set CUDA environment -export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64 -``` - -### Step 2: Enable GPU Acceleration in Jan - -1. Open **Settings** > **Hardware** -2. Turn on **GPU Acceleration** -3. Check **System Monitor** (footer) to verify GPU is detected - -![Hardware](../../../assets/trouble-shooting-01.png) - -### Step 3: Verify Configuration - -1. Go to **Settings** > **Advanced Settings** > **Data Folder** -2. Open `settings.json` file -3. Check these settings: - -```json -{ - "run_mode": "gpu", // Should be "gpu" - "nvidia_driver": { - "exist": true, // Should be true - "version": "531.18" - }, - "cuda": { - "exist": true, // Should be true - "version": "12" - }, - "gpus": [ - { - "id": "0", - "vram": "12282" // Your GPU memory in MB - } - ] -} -``` - -### Step 4: Restart Jan - -Close and restart Jan to apply changes. - -#### Tested Working Configurations - -**Desktop Systems:** -- Windows 11 + RTX 4070Ti + CUDA 12.2 + Driver 531.18 -- Ubuntu 22.04 + RTX 4070Ti + CUDA 12.2 + Driver 545 - -**Virtual Machines:** -- Ubuntu on Proxmox + GTX 1660Ti + CUDA 12.1 + Driver 535 - - - -### "Failed to Fetch" or "Something's Amiss" Errors - -When models won't respond or show these errors: - -**1. Check System Requirements** -- **RAM:** Use models under 80% of available memory - - 8GB system: Use models under 6GB - - 16GB system: Use models under 13GB -- **Hardware:** Verify your system meets [minimum requirements](/docs/troubleshooting#step-1-verify-hardware-and-system-requirements) - -**2. Adjust Model Settings** -- Open model settings in the chat sidebar -- Lower the **GPU Layers (ngl)** setting -- Start low and increase gradually - -**3. Check Port Conflicts** -If logs show "Bind address failed": - -```bash -# Check if ports are in use -# macOS/Linux -netstat -an | grep 1337 - -# Windows -netstat -ano | find "1337" -``` - -**Default Jan ports:** -- API Server: `1337` -- Documentation: `3001` - -**4. Try Factory Reset** -1. **Settings** > **Advanced Settings** -2. Click **Reset** under "Reset To Factory Settings" - - - -**5. Clean Reinstall** -If problems persist, do a complete clean installation (see "Jan Won't Start" section above). - -### Permission Denied Errors - -If you see permission errors during installation: - -```bash -# Fix npm permissions (macOS/Linux) -sudo chown -R $(whoami) ~/.npm - -# Windows - run as administrator -``` - -### OpenAI API Issues ("Unexpected Token") - -For OpenAI connection problems: - -**1. Verify API Key** -- Get valid key from [OpenAI Platform](https://platform.openai.com/) -- Ensure sufficient credits and permissions - -**2. Check Regional Access** -- Some regions have API restrictions -- Try using a VPN from a supported region -- Test network connectivity to OpenAI endpoints - -### Performance Issues - -**Models Running Slowly:** -- Enable GPU acceleration (see NVIDIA section) -- Use appropriate model size for your hardware -- Close other memory-intensive applications -- Check Task Manager/Activity Monitor for resource usage - -**High Memory Usage:** -- Switch to smaller model variants -- Reduce context length in model settings -- Enable model offloading in engine settings - -**Frequent Crashes:** -- Update graphics drivers -- Check system temperature -- Reduce GPU layers if using GPU acceleration -- Verify adequate power supply (desktop systems) - -## Need More Help? - -If these solutions don't work: - -**1. Gather Information:** -- Copy your error logs (see top of this page) -- Note your system specifications -- Describe what you were trying to do when the problem occurred - -**2. Get Community Support:** -- Join our [Discord](https://discord.com/invite/FTk2MvZwJH) -- Post in the **#🆘|jan-help** channel -- Include your logs and system info - -**3. Check Resources:** -- [System requirements](/docs/troubleshooting#step-1-verify-hardware-and-system-requirements) -- [Model compatibility guides](/docs/manage-models) -- [Hardware setup guides](/docs/desktop/) - - diff --git a/website/src/pages/api-reference.astro b/website/src/pages/api-reference.astro new file mode 100644 index 000000000..81e7c3f87 --- /dev/null +++ b/website/src/pages/api-reference.astro @@ -0,0 +1,22 @@ + + + + + + Redirecting to API Documentation | Jan + + + + +
+
+

Redirecting...

+

If you are not redirected automatically, click here to go to the API Documentation.

+
+
+ + + diff --git a/website/src/pages/api-reference/cloud.astro b/website/src/pages/api-reference/cloud.astro new file mode 100644 index 000000000..7fb634e58 --- /dev/null +++ b/website/src/pages/api-reference/cloud.astro @@ -0,0 +1,331 @@ +--- +import ApiReferenceLayout from '../../components/ApiReferenceLayout.astro' +import ScalarApiReferenceMulti from '../../components/react/ScalarApiReferenceMulti.jsx' + +const title = 'Jan Server API Reference' +const description = 'OpenAI-compatible API documentation for Jan Server powered by vLLM' +--- + + +
+
+ +

Jan Server API Reference

+

+ Self-hostable Jan Server powered by vLLM for high-throughput serving +

+
+
+ Base URL: + http://your-server:8000/v1 +
+
+ Engine: + vLLM +
+
+ Format: + OpenAI Compatible +
+
+
+
+ +
+
+ + + + + +
+
+ Authentication Required: All requests to Jan Server require authentication. + Include your API key in the Authorization header as Bearer YOUR_API_KEY. + Configure authentication in your server settings. +
+
+ +
+
+
+ + + +
+

High Performance

+

Powered by vLLM's PagedAttention for efficient memory usage and high throughput

+
+
+
+ + + + + +
+

Auto-Scaling

+

Automatically scales to handle your workload with intelligent load balancing

+
+
+
+ + + + + +
+

Multi-Model Support

+

Support for various model formats and sizes with optimized serving configurations

+
+
+ +
+ +
+ + +
diff --git a/website/src/pages/api-reference/local.astro b/website/src/pages/api-reference/local.astro new file mode 100644 index 000000000..f860620e3 --- /dev/null +++ b/website/src/pages/api-reference/local.astro @@ -0,0 +1,222 @@ +--- +import ApiReferenceLayout from '../../components/ApiReferenceLayout.astro' +import ScalarApiReferenceMulti from '../../components/react/ScalarApiReferenceMulti.jsx' + +const title = 'Jan Local API Reference' +const description = 'OpenAI-compatible API documentation for Jan running locally with llama.cpp' +--- + + +
+
+ +

Local API Reference

+

+ Run Jan locally on your machine with llama.cpp's high-performance inference engine +

+
+
+ Base URL: + http://localhost:1337 +
+
+ Engine: + llama.cpp +
+
+ Format: + OpenAI Compatible +
+
+
+
+ +
+
+ + + + + +
+
+ Getting Started: Make sure Jan is running locally on your machine. + You can start the server by launching the Jan application or running the CLI command. + Default port is 1337, but you can configure it in your settings. +
+
+ +
+ +
+ + +
diff --git a/website/src/pages/api.astro b/website/src/pages/api.astro new file mode 100644 index 000000000..5f28fe3b3 --- /dev/null +++ b/website/src/pages/api.astro @@ -0,0 +1,257 @@ +--- +import ApiReferenceLayout from '../components/ApiReferenceLayout.astro' + +const title = 'Jan API Documentation' +const description = 'OpenAI-compatible API for local and server deployments' +--- + + +
+
+

👋Jan API Documentation

+

OpenAI-compatible API for local and server deployments

+
+ +
+
+
+

Local API

+ llama.cpp +
+

Run Jan locally with complete privacy.

+
+ http://localhost:1337/v1 + Privacy-first • GGUF models • CPU/GPU +
+ View Documentation → +
+ +
+
+

Jan Server

+ vLLM +
+

Self-hostable server for high-throughput inference.

+
+ http://your-server:8000/v1 + Open source • Auto-scaling • Multi-GPU +
+ View Documentation → +
+
+ +
+

Quick Start

+
+
+ 1 + Choose deployment type +
+
+ 2 + Start your server +
+
+ 3 + Make API requests +
+
+
+
+ + +
diff --git a/website/src/styles/global.css b/website/src/styles/global.css new file mode 100644 index 000000000..48b9bc50a --- /dev/null +++ b/website/src/styles/global.css @@ -0,0 +1,72 @@ +@font-face { + font-family: 'Studio Feixen Sans'; + src: url('/assets/fonts/StudioFeixenSans-Regular.otf') format('opentype'); + font-weight: 400; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: 'Studio Feixen Sans'; + src: url('/assets/fonts/StudioFeixenSans-Light.otf') format('opentype'); + font-weight: 300; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: 'Studio Feixen Sans'; + src: url('/assets/fonts/StudioFeixenSans-Book.otf') format('opentype'); + font-weight: 350; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: 'Studio Feixen Sans'; + src: url('/assets/fonts/StudioFeixenSans-Medium.otf') format('opentype'); + font-weight: 500; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: 'Studio Feixen Sans'; + src: url('/assets/fonts/StudioFeixenSans-Semibold.otf') format('opentype'); + font-weight: 600; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: 'Studio Feixen Sans'; + src: url('/assets/fonts/StudioFeixenSans-Bold.otf') format('opentype'); + font-weight: 700; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: 'Studio Feixen Sans'; + src: url('/assets/fonts/StudioFeixenSans-Ultralight.otf') format('opentype'); + font-weight: 200; + font-style: normal; + font-display: swap; +} + +:root { + --sl-font: 'Studio Feixen Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', + 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', + 'Helvetica Neue', sans-serif; + --sl-font-mono: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', + 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', + 'Droid Sans Mono', 'Courier New', monospace; +} + +html { + font-family: var(--sl-font); +} + +body { + font-family: var(--sl-font); +}