diff --git a/.env.example b/.env.example
index e63d043660..f02e063566 100644
--- a/.env.example
+++ b/.env.example
@@ -20,6 +20,11 @@ DOMAIN_CLIENT=http://localhost:3080
DOMAIN_SERVER=http://localhost:3080
NO_INDEX=true
+# Use the address that is at most n number of hops away from the Express application.
+# req.socket.remoteAddress is the first hop, and the rest are looked for in the X-Forwarded-For header from right to left.
+# A value of 0 means that the first untrusted address would be req.socket.remoteAddress, i.e. there is no reverse proxy.
+# Defaulted to 1.
+TRUST_PROXY=1
#===============#
# JSON Logging #
@@ -83,7 +88,7 @@ PROXY=
#============#
ANTHROPIC_API_KEY=user_provided
-# ANTHROPIC_MODELS=claude-3-5-haiku-20241022,claude-3-5-sonnet-20241022,claude-3-5-sonnet-latest,claude-3-5-sonnet-20240620,claude-3-opus-20240229,claude-3-sonnet-20240229,claude-3-haiku-20240307,claude-2.1,claude-2,claude-1.2,claude-1,claude-1-100k,claude-instant-1,claude-instant-1-100k
+# ANTHROPIC_MODELS=claude-3-7-sonnet-latest,claude-3-7-sonnet-20250219,claude-3-5-haiku-20241022,claude-3-5-sonnet-20241022,claude-3-5-sonnet-latest,claude-3-5-sonnet-20240620,claude-3-opus-20240229,claude-3-sonnet-20240229,claude-3-haiku-20240307,claude-2.1,claude-2,claude-1.2,claude-1,claude-1-100k,claude-instant-1,claude-instant-1-100k
# ANTHROPIC_REVERSE_PROXY=
#============#
@@ -170,7 +175,7 @@ GOOGLE_KEY=user_provided
#============#
OPENAI_API_KEY=user_provided
-# OPENAI_MODELS=o1,o1-mini,o1-preview,gpt-4o,chatgpt-4o-latest,gpt-4o-mini,gpt-3.5-turbo-0125,gpt-3.5-turbo-0301,gpt-3.5-turbo,gpt-4,gpt-4-0613,gpt-4-vision-preview,gpt-3.5-turbo-0613,gpt-3.5-turbo-16k-0613,gpt-4-0125-preview,gpt-4-turbo-preview,gpt-4-1106-preview,gpt-3.5-turbo-1106,gpt-3.5-turbo-instruct,gpt-3.5-turbo-instruct-0914,gpt-3.5-turbo-16k
+# OPENAI_MODELS=o1,o1-mini,o1-preview,gpt-4o,gpt-4.5-preview,chatgpt-4o-latest,gpt-4o-mini,gpt-3.5-turbo-0125,gpt-3.5-turbo-0301,gpt-3.5-turbo,gpt-4,gpt-4-0613,gpt-4-vision-preview,gpt-3.5-turbo-0613,gpt-3.5-turbo-16k-0613,gpt-4-0125-preview,gpt-4-turbo-preview,gpt-4-1106-preview,gpt-3.5-turbo-1106,gpt-3.5-turbo-instruct,gpt-3.5-turbo-instruct-0914,gpt-3.5-turbo-16k
DEBUG_OPENAI=false
@@ -204,12 +209,6 @@ ASSISTANTS_API_KEY=user_provided
# More info, including how to enable use of Assistants with Azure here:
# https://www.librechat.ai/docs/configuration/librechat_yaml/ai_endpoints/azure#using-assistants-with-azure
-#============#
-# OpenRouter #
-#============#
-# !!!Warning: Use the variable above instead of this one. Using this one will override the OpenAI endpoint
-# OPENROUTER_API_KEY=
-
#============#
# Plugins #
#============#
@@ -249,6 +248,13 @@ AZURE_AI_SEARCH_SEARCH_OPTION_SELECT=
# DALLE3_AZURE_API_VERSION=
# DALLE2_AZURE_API_VERSION=
+# Flux
+#-----------------
+FLUX_API_BASE_URL=https://api.us1.bfl.ai
+# FLUX_API_BASE_URL = 'https://api.bfl.ml';
+
+# Get your API key at https://api.us1.bfl.ai/auth/profile
+# FLUX_API_KEY=
# Google
#-----------------
@@ -292,6 +298,10 @@ MEILI_NO_ANALYTICS=true
MEILI_HOST=http://0.0.0.0:7700
MEILI_MASTER_KEY=DrhYf7zENyR6AlUCKmnz0eYASOQdl6zxH7s7MKFSfFCt
+# Optional: Disable indexing, useful in a multi-node setup
+# where only one instance should perform an index sync.
+# MEILI_NO_SYNC=true
+
#==================================================#
# Speech to Text & Text to Speech #
#==================================================#
@@ -389,7 +399,7 @@ FACEBOOK_CALLBACK_URL=/oauth/facebook/callback
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GITHUB_CALLBACK_URL=/oauth/github/callback
-# GitHub Eenterprise
+# GitHub Enterprise
# GITHUB_ENTERPRISE_BASE_URL=
# GITHUB_ENTERPRISE_USER_AGENT=
@@ -424,15 +434,19 @@ OPENID_NAME_CLAIM=
OPENID_BUTTON_LABEL=
OPENID_IMAGE_URL=
+# Set to true to automatically redirect to the OpenID provider when a user visits the login page
+# This will bypass the login form completely for users, only use this if OpenID is your only authentication method
+OPENID_AUTO_REDIRECT=false
# LDAP
LDAP_URL=
LDAP_BIND_DN=
LDAP_BIND_CREDENTIALS=
LDAP_USER_SEARCH_BASE=
-LDAP_SEARCH_FILTER=mail={{username}}
+#LDAP_SEARCH_FILTER="mail="
LDAP_CA_CERT_PATH=
# LDAP_TLS_REJECT_UNAUTHORIZED=
+# LDAP_STARTTLS=
# LDAP_LOGIN_USES_USERNAME=true
# LDAP_ID=
# LDAP_USERNAME=
@@ -465,6 +479,24 @@ FIREBASE_STORAGE_BUCKET=
FIREBASE_MESSAGING_SENDER_ID=
FIREBASE_APP_ID=
+#========================#
+# S3 AWS Bucket #
+#========================#
+
+AWS_ENDPOINT_URL=
+AWS_ACCESS_KEY_ID=
+AWS_SECRET_ACCESS_KEY=
+AWS_REGION=
+AWS_BUCKET_NAME=
+
+#========================#
+# Azure Blob Storage #
+#========================#
+
+AZURE_STORAGE_CONNECTION_STRING=
+AZURE_STORAGE_PUBLIC_ACCESS=false
+AZURE_CONTAINER_NAME=files
+
#========================#
# Shared Links #
#========================#
@@ -497,6 +529,16 @@ HELP_AND_FAQ_URL=https://librechat.ai
# Google tag manager id
#ANALYTICS_GTM_ID=user provided google tag manager id
+#===============#
+# REDIS Options #
+#===============#
+
+# REDIS_URI=10.10.10.10:6379
+# USE_REDIS=true
+
+# USE_REDIS_CLUSTER=true
+# REDIS_CA=/path/to/ca.crt
+
#==================================================#
# Others #
#==================================================#
@@ -504,9 +546,6 @@ HELP_AND_FAQ_URL=https://librechat.ai
# NODE_ENV=
-# REDIS_URI=
-# USE_REDIS=
-
# E2E_USER_EMAIL=
# E2E_USER_PASSWORD=
@@ -529,4 +568,4 @@ HELP_AND_FAQ_URL=https://librechat.ai
#=====================================================#
# OpenWeather #
#=====================================================#
-OPENWEATHER_API_KEY=
\ No newline at end of file
+OPENWEATHER_API_KEY=
diff --git a/.github/ISSUE_TEMPLATE/LOCIZE_TRANSLATION_ACCESS_REQUEST.yml b/.github/ISSUE_TEMPLATE/LOCIZE_TRANSLATION_ACCESS_REQUEST.yml
new file mode 100644
index 0000000000..49b01a814d
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/LOCIZE_TRANSLATION_ACCESS_REQUEST.yml
@@ -0,0 +1,42 @@
+name: Locize Translation Access Request
+description: Request access to an additional language in Locize for LibreChat translations.
+title: "Locize Access Request: "
+labels: ["🌍 i18n", "🔑 access request"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thank you for your interest in contributing to LibreChat translations!
+ Please fill out the form below to request access to an additional language in **Locize**.
+
+ **🔗 Available Languages:** [View the list here](https://www.librechat.ai/docs/translation)
+
+ **📌 Note:** Ensure that the requested language is supported before submitting your request.
+ - type: input
+ id: account_name
+ attributes:
+ label: Locize Account Name
+ description: Please provide your Locize account name (e.g., John Doe).
+ placeholder: e.g., John Doe
+ validations:
+ required: true
+ - type: input
+ id: language_requested
+ attributes:
+ label: Language Code (ISO 639-1)
+ description: |
+ Enter the **ISO 639-1** language code for the language you want to translate into.
+ Example: `es` for Spanish, `zh-Hant` for Traditional Chinese.
+
+ **🔗 Reference:** [Available Languages](https://www.librechat.ai/docs/translation)
+ placeholder: e.g., es
+ validations:
+ required: true
+ - type: checkboxes
+ id: agreement
+ attributes:
+ label: Agreement
+ description: By submitting this request, you confirm that you will contribute responsibly and adhere to the project guidelines.
+ options:
+ - label: I agree to use my access solely for contributing to LibreChat translations.
+ required: true
\ No newline at end of file
diff --git a/.github/ISSUE_TEMPLATE/QUESTION.yml b/.github/ISSUE_TEMPLATE/QUESTION.yml
deleted file mode 100644
index c66e6baa3b..0000000000
--- a/.github/ISSUE_TEMPLATE/QUESTION.yml
+++ /dev/null
@@ -1,50 +0,0 @@
-name: Question
-description: Ask your question
-title: "[Question]: "
-labels: ["❓ question"]
-body:
- - type: markdown
- attributes:
- value: |
- Thanks for taking the time to fill this!
- - type: textarea
- id: what-is-your-question
- attributes:
- label: What is your question?
- description: Please give as many details as possible
- placeholder: Please give as many details as possible
- validations:
- required: true
- - type: textarea
- id: more-details
- attributes:
- label: More Details
- description: Please provide more details if needed.
- placeholder: Please provide more details if needed.
- validations:
- required: true
- - type: dropdown
- id: browsers
- attributes:
- label: What is the main subject of your question?
- multiple: true
- options:
- - Documentation
- - Installation
- - UI
- - Endpoints
- - User System/OAuth
- - Other
- - type: textarea
- id: screenshots
- attributes:
- label: Screenshots
- description: If applicable, add screenshots to help explain your problem. You can drag and drop, paste images directly here or link to them.
- - type: checkboxes
- id: terms
- attributes:
- label: Code of Conduct
- description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/danny-avila/LibreChat/blob/main/.github/CODE_OF_CONDUCT.md)
- options:
- - label: I agree to follow this project's Code of Conduct
- required: true
diff --git a/.github/configuration-release.json b/.github/configuration-release.json
new file mode 100644
index 0000000000..68fe80ed8f
--- /dev/null
+++ b/.github/configuration-release.json
@@ -0,0 +1,60 @@
+{
+ "categories": [
+ {
+ "title": "### ✨ New Features",
+ "labels": ["feat"]
+ },
+ {
+ "title": "### 🌍 Internationalization",
+ "labels": ["i18n"]
+ },
+ {
+ "title": "### 👐 Accessibility",
+ "labels": ["a11y"]
+ },
+ {
+ "title": "### 🔧 Fixes",
+ "labels": ["Fix", "fix"]
+ },
+ {
+ "title": "### ⚙️ Other Changes",
+ "labels": ["ci", "style", "docs", "refactor", "chore"]
+ }
+ ],
+ "ignore_labels": [
+ "🔁 duplicate",
+ "📊 analytics",
+ "🌱 good first issue",
+ "🔍 investigation",
+ "🙏 help wanted",
+ "❌ invalid",
+ "❓ question",
+ "🚫 wontfix",
+ "🚀 release",
+ "version"
+ ],
+ "base_branches": ["main"],
+ "sort": {
+ "order": "ASC",
+ "on_property": "mergedAt"
+ },
+ "label_extractor": [
+ {
+ "pattern": "^(?:[^A-Za-z0-9]*)(feat|fix|chore|docs|refactor|ci|style|a11y|i18n)\\s*:",
+ "target": "$1",
+ "flags": "i",
+ "on_property": "title",
+ "method": "match"
+ },
+ {
+ "pattern": "^(?:[^A-Za-z0-9]*)(v\\d+\\.\\d+\\.\\d+(?:-rc\\d+)?).*",
+ "target": "version",
+ "flags": "i",
+ "on_property": "title",
+ "method": "match"
+ }
+ ],
+ "template": "## [#{{TO_TAG}}] - #{{TO_TAG_DATE}}\n\nChanges from #{{FROM_TAG}} to #{{TO_TAG}}.\n\n#{{CHANGELOG}}\n\n[See full release details][release-#{{TO_TAG}}]\n\n[release-#{{TO_TAG}}]: https://github.com/#{{OWNER}}/#{{REPO}}/releases/tag/#{{TO_TAG}}\n\n---",
+ "pr_template": "- #{{TITLE}} by **@#{{AUTHOR}}** in [##{{NUMBER}}](#{{URL}})",
+ "empty_template": "- no changes"
+}
\ No newline at end of file
diff --git a/.github/configuration-unreleased.json b/.github/configuration-unreleased.json
new file mode 100644
index 0000000000..29eaf5e13b
--- /dev/null
+++ b/.github/configuration-unreleased.json
@@ -0,0 +1,68 @@
+{
+ "categories": [
+ {
+ "title": "### ✨ New Features",
+ "labels": ["feat"]
+ },
+ {
+ "title": "### 🌍 Internationalization",
+ "labels": ["i18n"]
+ },
+ {
+ "title": "### 👐 Accessibility",
+ "labels": ["a11y"]
+ },
+ {
+ "title": "### 🔧 Fixes",
+ "labels": ["Fix", "fix"]
+ },
+ {
+ "title": "### ⚙️ Other Changes",
+ "labels": ["ci", "style", "docs", "refactor", "chore"]
+ }
+ ],
+ "ignore_labels": [
+ "🔁 duplicate",
+ "📊 analytics",
+ "🌱 good first issue",
+ "🔍 investigation",
+ "🙏 help wanted",
+ "❌ invalid",
+ "❓ question",
+ "🚫 wontfix",
+ "🚀 release",
+ "version",
+ "action"
+ ],
+ "base_branches": ["main"],
+ "sort": {
+ "order": "ASC",
+ "on_property": "mergedAt"
+ },
+ "label_extractor": [
+ {
+ "pattern": "^(?:[^A-Za-z0-9]*)(feat|fix|chore|docs|refactor|ci|style|a11y|i18n)\\s*:",
+ "target": "$1",
+ "flags": "i",
+ "on_property": "title",
+ "method": "match"
+ },
+ {
+ "pattern": "^(?:[^A-Za-z0-9]*)(v\\d+\\.\\d+\\.\\d+(?:-rc\\d+)?).*",
+ "target": "version",
+ "flags": "i",
+ "on_property": "title",
+ "method": "match"
+ },
+ {
+ "pattern": "^(?:[^A-Za-z0-9]*)(action)\\b.*",
+ "target": "action",
+ "flags": "i",
+ "on_property": "title",
+ "method": "match"
+ }
+ ],
+ "template": "## [Unreleased]\n\n#{{CHANGELOG}}\n\n---",
+ "pr_template": "- #{{TITLE}} by **@#{{AUTHOR}}** in [##{{NUMBER}}](#{{URL}})",
+ "empty_template": "- no changes"
+}
\ No newline at end of file
diff --git a/.github/workflows/backend-review.yml b/.github/workflows/backend-review.yml
index 5bc3d3b2db..b7bccecae8 100644
--- a/.github/workflows/backend-review.yml
+++ b/.github/workflows/backend-review.yml
@@ -39,6 +39,9 @@ jobs:
- name: Install MCP Package
run: npm run build:mcp
+ - name: Install Data Schemas Package
+ run: npm run build:data-schemas
+
- name: Create empty auth.json file
run: |
mkdir -p api/data
@@ -61,4 +64,7 @@ jobs:
run: cd api && npm run test:ci
- name: Run librechat-data-provider unit tests
- run: cd packages/data-provider && npm run test:ci
\ No newline at end of file
+ run: cd packages/data-provider && npm run test:ci
+
+ - name: Run librechat-mcp unit tests
+ run: cd packages/mcp && npm run test:ci
\ No newline at end of file
diff --git a/.github/workflows/data-schemas.yml b/.github/workflows/data-schemas.yml
new file mode 100644
index 0000000000..fee72fbe02
--- /dev/null
+++ b/.github/workflows/data-schemas.yml
@@ -0,0 +1,58 @@
+name: Publish `@librechat/data-schemas` to NPM
+
+on:
+ push:
+ branches:
+ - main
+ paths:
+ - 'packages/data-schemas/package.json'
+ workflow_dispatch:
+ inputs:
+ reason:
+ description: 'Reason for manual trigger'
+ required: false
+ default: 'Manual publish requested'
+
+jobs:
+ build-and-publish:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Use Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '18.x'
+
+ - name: Install dependencies
+ run: cd packages/data-schemas && npm ci
+
+ - name: Build
+ run: cd packages/data-schemas && npm run build
+
+ - name: Set up npm authentication
+ run: echo "//registry.npmjs.org/:_authToken=${{ secrets.PUBLISH_NPM_TOKEN }}" > ~/.npmrc
+
+ - name: Check version change
+ id: check
+ working-directory: packages/data-schemas
+ run: |
+ PACKAGE_VERSION=$(node -p "require('./package.json').version")
+ PUBLISHED_VERSION=$(npm view @librechat/data-schemas version 2>/dev/null || echo "0.0.0")
+ if [ "$PACKAGE_VERSION" = "$PUBLISHED_VERSION" ]; then
+ echo "No version change, skipping publish"
+ echo "skip=true" >> $GITHUB_OUTPUT
+ else
+ echo "Version changed, proceeding with publish"
+ echo "skip=false" >> $GITHUB_OUTPUT
+ fi
+
+ - name: Pack package
+ if: steps.check.outputs.skip != 'true'
+ working-directory: packages/data-schemas
+ run: npm pack
+
+ - name: Publish
+ if: steps.check.outputs.skip != 'true'
+ working-directory: packages/data-schemas
+ run: npm publish *.tgz --access public
\ No newline at end of file
diff --git a/.github/workflows/generate-release-changelog-pr.yml b/.github/workflows/generate-release-changelog-pr.yml
new file mode 100644
index 0000000000..004431e577
--- /dev/null
+++ b/.github/workflows/generate-release-changelog-pr.yml
@@ -0,0 +1,94 @@
+name: Generate Release Changelog PR
+
+on:
+ push:
+ tags:
+ - 'v*.*.*'
+
+jobs:
+ generate-release-changelog-pr:
+ permissions:
+ contents: write # Needed for pushing commits and creating branches.
+ pull-requests: write
+ runs-on: ubuntu-latest
+ steps:
+ # 1. Checkout the repository (with full history).
+ - name: Checkout Repository
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ # 2. Generate the release changelog using our custom configuration.
+ - name: Generate Release Changelog
+ id: generate_release
+ uses: mikepenz/release-changelog-builder-action@v5.1.0
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ configuration: ".github/configuration-release.json"
+ owner: ${{ github.repository_owner }}
+ repo: ${{ github.event.repository.name }}
+ outputFile: CHANGELOG-release.md
+
+ # 3. Update the main CHANGELOG.md:
+ # - If it doesn't exist, create it with a basic header.
+ # - Remove the "Unreleased" section (if present).
+ # - Prepend the new release changelog above previous releases.
+ # - Remove all temporary files before committing.
+ - name: Update CHANGELOG.md
+ run: |
+ # Determine the release tag, e.g. "v1.2.3"
+ TAG=${GITHUB_REF##*/}
+ echo "Using release tag: $TAG"
+
+ # Ensure CHANGELOG.md exists; if not, create a basic header.
+ if [ ! -f CHANGELOG.md ]; then
+ echo "# Changelog" > CHANGELOG.md
+ echo "" >> CHANGELOG.md
+ echo "All notable changes to this project will be documented in this file." >> CHANGELOG.md
+ echo "" >> CHANGELOG.md
+ fi
+
+ echo "Updating CHANGELOG.md…"
+
+ # Remove the "Unreleased" section (from "## [Unreleased]" until the first occurrence of '---') if it exists.
+ if grep -q "^## \[Unreleased\]" CHANGELOG.md; then
+ awk '/^## \[Unreleased\]/{flag=1} flag && /^---/{flag=0; next} !flag' CHANGELOG.md > CHANGELOG.cleaned
+ else
+ cp CHANGELOG.md CHANGELOG.cleaned
+ fi
+
+ # Split the cleaned file into:
+ # - header.md: content before the first release header ("## [v...").
+ # - tail.md: content from the first release header onward.
+ awk '/^## \[v/{exit} {print}' CHANGELOG.cleaned > header.md
+ awk 'f{print} /^## \[v/{f=1; print}' CHANGELOG.cleaned > tail.md
+
+ # Combine header, the new release changelog, and the tail.
+ echo "Combining updated changelog parts..."
+ cat header.md CHANGELOG-release.md > CHANGELOG.md.new
+ echo "" >> CHANGELOG.md.new
+ cat tail.md >> CHANGELOG.md.new
+
+ mv CHANGELOG.md.new CHANGELOG.md
+
+ # Remove temporary files.
+ rm -f CHANGELOG.cleaned header.md tail.md CHANGELOG-release.md
+
+ echo "Final CHANGELOG.md content:"
+ cat CHANGELOG.md
+
+ # 4. Create (or update) the Pull Request with the updated CHANGELOG.md.
+ - name: Create Pull Request
+ uses: peter-evans/create-pull-request@v7
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ sign-commits: true
+ commit-message: "chore: update CHANGELOG for release ${{ github.ref_name }}"
+ base: main
+ branch: "changelog/${{ github.ref_name }}"
+ reviewers: danny-avila
+ title: "chore: update CHANGELOG for release ${{ github.ref_name }}"
+ body: |
+ **Description**:
+ - This PR updates the CHANGELOG.md by removing the "Unreleased" section and adding new release notes for release ${{ github.ref_name }} above previous releases.
\ No newline at end of file
diff --git a/.github/workflows/generate-unreleased-changelog-pr.yml b/.github/workflows/generate-unreleased-changelog-pr.yml
new file mode 100644
index 0000000000..b130e4fb33
--- /dev/null
+++ b/.github/workflows/generate-unreleased-changelog-pr.yml
@@ -0,0 +1,106 @@
+name: Generate Unreleased Changelog PR
+
+on:
+ schedule:
+ - cron: "0 0 * * 1" # Runs every Monday at 00:00 UTC
+
+jobs:
+ generate-unreleased-changelog-pr:
+ permissions:
+ contents: write # Needed for pushing commits and creating branches.
+ pull-requests: write
+ runs-on: ubuntu-latest
+ steps:
+ # 1. Checkout the repository on main.
+ - name: Checkout Repository on Main
+ uses: actions/checkout@v4
+ with:
+ ref: main
+ fetch-depth: 0
+
+ # 4. Get the latest version tag.
+ - name: Get Latest Tag
+ id: get_latest_tag
+ run: |
+ LATEST_TAG=$(git describe --tags $(git rev-list --tags --max-count=1) || echo "none")
+ echo "Latest tag: $LATEST_TAG"
+ echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
+
+ # 5. Generate the Unreleased changelog.
+ - name: Generate Unreleased Changelog
+ id: generate_unreleased
+ uses: mikepenz/release-changelog-builder-action@v5.1.0
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ configuration: ".github/configuration-unreleased.json"
+ owner: ${{ github.repository_owner }}
+ repo: ${{ github.event.repository.name }}
+ outputFile: CHANGELOG-unreleased.md
+ fromTag: ${{ steps.get_latest_tag.outputs.tag }}
+ toTag: main
+
+ # 7. Update CHANGELOG.md with the new Unreleased section.
+ - name: Update CHANGELOG.md
+ id: update_changelog
+ run: |
+ # Create CHANGELOG.md if it doesn't exist.
+ if [ ! -f CHANGELOG.md ]; then
+ echo "# Changelog" > CHANGELOG.md
+ echo "" >> CHANGELOG.md
+ echo "All notable changes to this project will be documented in this file." >> CHANGELOG.md
+ echo "" >> CHANGELOG.md
+ fi
+
+ echo "Updating CHANGELOG.md…"
+
+ # Extract content before the "## [Unreleased]" (or first version header if missing).
+ if grep -q "^## \[Unreleased\]" CHANGELOG.md; then
+ awk '/^## \[Unreleased\]/{exit} {print}' CHANGELOG.md > CHANGELOG_TMP.md
+ else
+ awk '/^## \[v/{exit} {print}' CHANGELOG.md > CHANGELOG_TMP.md
+ fi
+
+ # Append the generated Unreleased changelog.
+ echo "" >> CHANGELOG_TMP.md
+ cat CHANGELOG-unreleased.md >> CHANGELOG_TMP.md
+ echo "" >> CHANGELOG_TMP.md
+
+ # Append the remainder of the original changelog (starting from the first version header).
+ awk 'f{print} /^## \[v/{f=1; print}' CHANGELOG.md >> CHANGELOG_TMP.md
+
+ # Replace the old file with the updated file.
+ mv CHANGELOG_TMP.md CHANGELOG.md
+
+ # Remove the temporary generated file.
+ rm -f CHANGELOG-unreleased.md
+
+ echo "Final CHANGELOG.md:"
+ cat CHANGELOG.md
+
+ # 8. Check if CHANGELOG.md has any updates.
+ - name: Check for CHANGELOG.md changes
+ id: changelog_changes
+ run: |
+ if git diff --quiet CHANGELOG.md; then
+ echo "has_changes=false" >> $GITHUB_OUTPUT
+ else
+ echo "has_changes=true" >> $GITHUB_OUTPUT
+ fi
+
+ # 9. Create (or update) the Pull Request only if there are changes.
+ - name: Create Pull Request
+ if: steps.changelog_changes.outputs.has_changes == 'true'
+ uses: peter-evans/create-pull-request@v7
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ base: main
+ branch: "changelog/unreleased-update"
+ sign-commits: true
+ commit-message: "action: update Unreleased changelog"
+ title: "action: update Unreleased changelog"
+ body: |
+ **Description**:
+ - This PR updates the Unreleased section in CHANGELOG.md.
+ - It compares the current main branch with the latest version tag (determined as ${{ steps.get_latest_tag.outputs.tag }}),
+ regenerates the Unreleased changelog, removes any old Unreleased block, and inserts the new content.
\ No newline at end of file
diff --git a/.github/workflows/i18n-unused-keys.yml b/.github/workflows/i18n-unused-keys.yml
index 79f95d3b27..5e29a8a8bd 100644
--- a/.github/workflows/i18n-unused-keys.yml
+++ b/.github/workflows/i18n-unused-keys.yml
@@ -4,6 +4,7 @@ on:
pull_request:
paths:
- "client/src/**"
+ - "api/**"
jobs:
detect-unused-i18n-keys:
@@ -21,7 +22,7 @@ jobs:
# Define paths
I18N_FILE="client/src/locales/en/translation.json"
- SOURCE_DIR="client/src"
+ SOURCE_DIRS=("client/src" "api")
# Check if translation file exists
if [[ ! -f "$I18N_FILE" ]]; then
@@ -37,7 +38,15 @@ jobs:
# Check if each key is used in the source code
for KEY in $KEYS; do
- if ! grep -r --include=\*.{js,jsx,ts,tsx} -q "$KEY" "$SOURCE_DIR"; then
+ FOUND=false
+ for DIR in "${SOURCE_DIRS[@]}"; do
+ if grep -r --include=\*.{js,jsx,ts,tsx} -q "$KEY" "$DIR"; then
+ FOUND=true
+ break
+ fi
+ done
+
+ if [[ "$FOUND" == false ]]; then
UNUSED_KEYS+=("$KEY")
fi
done
@@ -59,8 +68,8 @@ jobs:
run: |
PR_NUMBER=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")
- # Format the unused keys list correctly, filtering out empty entries
- FILTERED_KEYS=$(echo "$unused_keys" | jq -r '.[]' | grep -v '^\s*$' | sed 's/^/- `/;s/$/`/' )
+ # Format the unused keys list as checkboxes for easy manual checking.
+ FILTERED_KEYS=$(echo "$unused_keys" | jq -r '.[]' | grep -v '^\s*$' | sed 's/^/- [ ] `/;s/$/`/' )
COMMENT_BODY=$(cat <
-
+
diff --git a/api/app/clients/AnthropicClient.js b/api/app/clients/AnthropicClient.js
index 522b6beb4f..8331e54bfb 100644
--- a/api/app/clients/AnthropicClient.js
+++ b/api/app/clients/AnthropicClient.js
@@ -7,7 +7,7 @@ const {
getResponseSender,
validateVisionModel,
} = require('librechat-data-provider');
-const { encodeAndFormat } = require('~/server/services/Files/images/encode');
+const { SplitStreamHandler: _Handler, GraphEvents } = require('@librechat/agents');
const {
truncateText,
formatMessage,
@@ -16,16 +16,31 @@ const {
parseParamFromPrompt,
createContextHandlers,
} = require('./prompts');
+const {
+ getClaudeHeaders,
+ configureReasoning,
+ checkPromptCacheSupport,
+} = require('~/server/services/Endpoints/anthropic/helpers');
const { getModelMaxTokens, getModelMaxOutputTokens, matchModelName } = require('~/utils');
const { spendTokens, spendStructuredTokens } = require('~/models/spendTokens');
+const { encodeAndFormat } = require('~/server/services/Files/images/encode');
const Tokenizer = require('~/server/services/Tokenizer');
+const { logger, sendEvent } = require('~/config');
const { sleep } = require('~/server/utils');
const BaseClient = require('./BaseClient');
-const { logger } = require('~/config');
const HUMAN_PROMPT = '\n\nHuman:';
const AI_PROMPT = '\n\nAssistant:';
+class SplitStreamHandler extends _Handler {
+ getDeltaContent(chunk) {
+ return (chunk?.delta?.text ?? chunk?.completion) || '';
+ }
+ getReasoningDelta(chunk) {
+ return chunk?.delta?.thinking || '';
+ }
+}
+
/** Helper function to introduce a delay before retrying */
function delayBeforeRetry(attempts, baseDelay = 1000) {
return new Promise((resolve) => setTimeout(resolve, baseDelay * attempts));
@@ -68,6 +83,8 @@ class AnthropicClient extends BaseClient {
/** The key for the usage object's output tokens
* @type {string} */
this.outputTokensKey = 'output_tokens';
+ /** @type {SplitStreamHandler | undefined} */
+ this.streamHandler;
}
setOptions(options) {
@@ -97,9 +114,10 @@ class AnthropicClient extends BaseClient {
const modelMatch = matchModelName(this.modelOptions.model, EModelEndpoint.anthropic);
this.isClaude3 = modelMatch.includes('claude-3');
- this.isLegacyOutput = !modelMatch.includes('claude-3-5-sonnet');
- this.supportsCacheControl =
- this.options.promptCache && this.checkPromptCacheSupport(modelMatch);
+ this.isLegacyOutput = !(
+ /claude-3[-.]5-sonnet/.test(modelMatch) || /claude-3[-.]7/.test(modelMatch)
+ );
+ this.supportsCacheControl = this.options.promptCache && checkPromptCacheSupport(modelMatch);
if (
this.isLegacyOutput &&
@@ -125,7 +143,7 @@ class AnthropicClient extends BaseClient {
this.options.endpointType ?? this.options.endpoint,
this.options.endpointTokenConfig,
) ??
- 1500;
+ anthropicSettings.maxOutputTokens.reset(this.modelOptions.model);
this.maxPromptTokens =
this.options.maxPromptTokens || this.maxContextTokens - this.maxResponseTokens;
@@ -171,18 +189,9 @@ class AnthropicClient extends BaseClient {
options.baseURL = this.options.reverseProxyUrl;
}
- if (
- this.supportsCacheControl &&
- requestOptions?.model &&
- requestOptions.model.includes('claude-3-5-sonnet')
- ) {
- options.defaultHeaders = {
- 'anthropic-beta': 'max-tokens-3-5-sonnet-2024-07-15,prompt-caching-2024-07-31',
- };
- } else if (this.supportsCacheControl) {
- options.defaultHeaders = {
- 'anthropic-beta': 'prompt-caching-2024-07-31',
- };
+ const headers = getClaudeHeaders(requestOptions?.model, this.supportsCacheControl);
+ if (headers) {
+ options.defaultHeaders = headers;
}
return new Anthropic(options);
@@ -668,29 +677,48 @@ class AnthropicClient extends BaseClient {
* @returns {Promise} The response from the Anthropic client.
*/
async createResponse(client, options, useMessages) {
- return useMessages ?? this.useMessages
+ return (useMessages ?? this.useMessages)
? await client.messages.create(options)
: await client.completions.create(options);
}
+ getMessageMapMethod() {
+ /**
+ * @param {TMessage} msg
+ */
+ return (msg) => {
+ if (msg.text != null && msg.text && msg.text.startsWith(':::thinking')) {
+ msg.text = msg.text.replace(/:::thinking.*?:::/gs, '').trim();
+ } else if (msg.content != null) {
+ /** @type {import('@librechat/agents').MessageContentComplex} */
+ const newContent = [];
+ for (let part of msg.content) {
+ if (part.think != null) {
+ continue;
+ }
+ newContent.push(part);
+ }
+ msg.content = newContent;
+ }
+
+ return msg;
+ };
+ }
+
/**
- * @param {string} modelName
- * @returns {boolean}
+ * @param {string[]} [intermediateReply]
+ * @returns {string}
*/
- checkPromptCacheSupport(modelName) {
- const modelMatch = matchModelName(modelName, EModelEndpoint.anthropic);
- if (modelMatch.includes('claude-3-5-sonnet-latest')) {
- return false;
+ getStreamText(intermediateReply) {
+ if (!this.streamHandler) {
+ return intermediateReply?.join('') ?? '';
}
- if (
- modelMatch === 'claude-3-5-sonnet' ||
- modelMatch === 'claude-3-5-haiku' ||
- modelMatch === 'claude-3-haiku' ||
- modelMatch === 'claude-3-opus'
- ) {
- return true;
- }
- return false;
+
+ const reasoningText = this.streamHandler.reasoningTokens.join('');
+
+ const reasoningBlock = reasoningText.length > 0 ? `:::thinking\n${reasoningText}\n:::\n` : '';
+
+ return `${reasoningBlock}${this.streamHandler.tokens.join('')}`;
}
async sendCompletion(payload, { onProgress, abortController }) {
@@ -710,7 +738,6 @@ class AnthropicClient extends BaseClient {
user_id: this.user,
};
- let text = '';
const {
stream,
model,
@@ -721,22 +748,34 @@ class AnthropicClient extends BaseClient {
topK: top_k,
} = this.modelOptions;
- const requestOptions = {
+ let requestOptions = {
model,
stream: stream || true,
stop_sequences,
temperature,
metadata,
- top_p,
- top_k,
};
if (this.useMessages) {
requestOptions.messages = payload;
- requestOptions.max_tokens = maxOutputTokens || legacy.maxOutputTokens.default;
+ requestOptions.max_tokens =
+ maxOutputTokens || anthropicSettings.maxOutputTokens.reset(requestOptions.model);
} else {
requestOptions.prompt = payload;
- requestOptions.max_tokens_to_sample = maxOutputTokens || 1500;
+ requestOptions.max_tokens_to_sample = maxOutputTokens || legacy.maxOutputTokens.default;
+ }
+
+ requestOptions = configureReasoning(requestOptions, {
+ thinking: this.options.thinking,
+ thinkingBudget: this.options.thinkingBudget,
+ });
+
+ if (!/claude-3[-.]7/.test(model)) {
+ requestOptions.top_p = top_p;
+ requestOptions.top_k = top_k;
+ } else if (requestOptions.thinking == null) {
+ requestOptions.topP = top_p;
+ requestOptions.topK = top_k;
}
if (this.systemMessage && this.supportsCacheControl === true) {
@@ -756,13 +795,17 @@ class AnthropicClient extends BaseClient {
}
logger.debug('[AnthropicClient]', { ...requestOptions });
+ this.streamHandler = new SplitStreamHandler({
+ accumulate: true,
+ runId: this.responseMessageId,
+ handlers: {
+ [GraphEvents.ON_RUN_STEP]: (event) => sendEvent(this.options.res, event),
+ [GraphEvents.ON_MESSAGE_DELTA]: (event) => sendEvent(this.options.res, event),
+ [GraphEvents.ON_REASONING_DELTA]: (event) => sendEvent(this.options.res, event),
+ },
+ });
- const handleChunk = (currentChunk) => {
- if (currentChunk) {
- text += currentChunk;
- onProgress(currentChunk);
- }
- };
+ let intermediateReply = this.streamHandler.tokens;
const maxRetries = 3;
const streamRate = this.options.streamRate ?? Constants.DEFAULT_STREAM_RATE;
@@ -783,22 +826,15 @@ class AnthropicClient extends BaseClient {
});
for await (const completion of response) {
- // Handle each completion as before
const type = completion?.type ?? '';
if (tokenEventTypes.has(type)) {
logger.debug(`[AnthropicClient] ${type}`, completion);
this[type] = completion;
}
- if (completion?.delta?.text) {
- handleChunk(completion.delta.text);
- } else if (completion.completion) {
- handleChunk(completion.completion);
- }
-
+ this.streamHandler.handle(completion);
await sleep(streamRate);
}
- // Successful processing, exit loop
break;
} catch (error) {
attempts += 1;
@@ -808,6 +844,10 @@ class AnthropicClient extends BaseClient {
if (attempts < maxRetries) {
await delayBeforeRetry(attempts, 350);
+ } else if (this.streamHandler && this.streamHandler.reasoningTokens.length) {
+ return this.getStreamText();
+ } else if (intermediateReply.length > 0) {
+ return this.getStreamText(intermediateReply);
} else {
throw new Error(`Operation failed after ${maxRetries} attempts: ${error.message}`);
}
@@ -823,8 +863,7 @@ class AnthropicClient extends BaseClient {
}
await processResponse.bind(this)();
-
- return text.trim();
+ return this.getStreamText(intermediateReply);
}
getSaveOptions() {
@@ -834,6 +873,8 @@ class AnthropicClient extends BaseClient {
promptPrefix: this.options.promptPrefix,
modelLabel: this.options.modelLabel,
promptCache: this.options.promptCache,
+ thinking: this.options.thinking,
+ thinkingBudget: this.options.thinkingBudget,
resendFiles: this.options.resendFiles,
iconURL: this.options.iconURL,
greeting: this.options.greeting,
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js
index ebf3ca12d9..d3077e68f5 100644
--- a/api/app/clients/BaseClient.js
+++ b/api/app/clients/BaseClient.js
@@ -5,10 +5,12 @@ const {
isAgentsEndpoint,
isParamEndpoint,
EModelEndpoint,
+ ContentTypes,
+ excludedKeys,
ErrorTypes,
Constants,
} = require('librechat-data-provider');
-const { getMessages, saveMessage, updateMessage, saveConvo } = require('~/models');
+const { getMessages, saveMessage, updateMessage, saveConvo, getConvo } = require('~/models');
const { addSpaceIfNeeded, isEnabled } = require('~/server/utils');
const { truncateToolCallOutputs } = require('./prompts');
const checkBalance = require('~/models/checkBalance');
@@ -55,6 +57,10 @@ class BaseClient {
* Flag to determine if the client re-submitted the latest assistant message.
* @type {boolean | undefined} */
this.continued;
+ /**
+ * Flag to determine if the client has already fetched the conversation while saving new messages.
+ * @type {boolean | undefined} */
+ this.fetchedConvo;
/** @type {TMessage[]} */
this.currentMessages = [];
/** @type {import('librechat-data-provider').VisionModes | undefined} */
@@ -360,17 +366,14 @@ class BaseClient {
* context: TMessage[],
* remainingContextTokens: number,
* messagesToRefine: TMessage[],
- * summaryIndex: number,
- * }>} An object with four properties: `context`, `summaryIndex`, `remainingContextTokens`, and `messagesToRefine`.
+ * }>} An object with three properties: `context`, `remainingContextTokens`, and `messagesToRefine`.
* `context` is an array of messages that fit within the token limit.
- * `summaryIndex` is the index of the first message in the `messagesToRefine` array.
* `remainingContextTokens` is the number of tokens remaining within the limit after adding the messages to the context.
* `messagesToRefine` is an array of messages that were not added to the context because they would have exceeded the token limit.
*/
async getMessagesWithinTokenLimit({ messages: _messages, maxContextTokens, instructions }) {
// Every reply is primed with <|start|>assistant<|message|>, so we
// start with 3 tokens for the label after all messages have been counted.
- let summaryIndex = -1;
let currentTokenCount = 3;
const instructionsTokenCount = instructions?.tokenCount ?? 0;
let remainingContextTokens =
@@ -403,14 +406,12 @@ class BaseClient {
}
const prunedMemory = messages;
- summaryIndex = prunedMemory.length - 1;
remainingContextTokens -= currentTokenCount;
return {
context: context.reverse(),
remainingContextTokens,
messagesToRefine: prunedMemory,
- summaryIndex,
};
}
@@ -453,7 +454,7 @@ class BaseClient {
let orderedWithInstructions = this.addInstructions(orderedMessages, instructions);
- let { context, remainingContextTokens, messagesToRefine, summaryIndex } =
+ let { context, remainingContextTokens, messagesToRefine } =
await this.getMessagesWithinTokenLimit({
messages: orderedWithInstructions,
instructions,
@@ -523,7 +524,7 @@ class BaseClient {
}
// Make sure to only continue summarization logic if the summary message was generated
- shouldSummarize = summaryMessage && shouldSummarize;
+ shouldSummarize = summaryMessage != null && shouldSummarize === true;
logger.debug('[BaseClient] Context Count (2/2)', {
remainingContextTokens,
@@ -533,17 +534,18 @@ class BaseClient {
/** @type {Record | undefined} */
let tokenCountMap;
if (buildTokenMap) {
- tokenCountMap = orderedWithInstructions.reduce((map, message, index) => {
+ const currentPayload = shouldSummarize ? orderedWithInstructions : context;
+ tokenCountMap = currentPayload.reduce((map, message, index) => {
const { messageId } = message;
if (!messageId) {
return map;
}
- if (shouldSummarize && index === summaryIndex && !usePrevSummary) {
+ if (shouldSummarize && index === messagesToRefine.length - 1 && !usePrevSummary) {
map.summaryMessage = { ...summaryMessage, messageId, tokenCount: summaryTokenCount };
}
- map[messageId] = orderedWithInstructions[index].tokenCount;
+ map[messageId] = currentPayload[index].tokenCount;
return map;
}, {});
}
@@ -863,16 +865,39 @@ class BaseClient {
return { message: savedMessage };
}
- const conversation = await saveConvo(
- this.options.req,
- {
- conversationId: message.conversationId,
- endpoint: this.options.endpoint,
- endpointType: this.options.endpointType,
- ...endpointOptions,
- },
- { context: 'api/app/clients/BaseClient.js - saveMessageToDatabase #saveConvo' },
- );
+ const fieldsToKeep = {
+ conversationId: message.conversationId,
+ endpoint: this.options.endpoint,
+ endpointType: this.options.endpointType,
+ ...endpointOptions,
+ };
+
+ const existingConvo =
+ this.fetchedConvo === true
+ ? null
+ : await getConvo(this.options.req?.user?.id, message.conversationId);
+
+ const unsetFields = {};
+ if (existingConvo != null) {
+ this.fetchedConvo = true;
+ for (const key in existingConvo) {
+ if (!key) {
+ continue;
+ }
+ if (excludedKeys.has(key)) {
+ continue;
+ }
+
+ if (endpointOptions?.[key] === undefined) {
+ unsetFields[key] = 1;
+ }
+ }
+ }
+
+ const conversation = await saveConvo(this.options.req, fieldsToKeep, {
+ context: 'api/app/clients/BaseClient.js - saveMessageToDatabase #saveConvo',
+ unsetFields,
+ });
return { message: savedMessage, conversation };
}
@@ -993,11 +1018,17 @@ class BaseClient {
const processValue = (value) => {
if (Array.isArray(value)) {
for (let item of value) {
- if (!item || !item.type || item.type === 'image_url') {
+ if (
+ !item ||
+ !item.type ||
+ item.type === ContentTypes.THINK ||
+ item.type === ContentTypes.ERROR ||
+ item.type === ContentTypes.IMAGE_URL
+ ) {
continue;
}
- if (item.type === 'tool_call' && item.tool_call != null) {
+ if (item.type === ContentTypes.TOOL_CALL && item.tool_call != null) {
const toolName = item.tool_call?.name || '';
if (toolName != null && toolName && typeof toolName === 'string') {
numTokens += this.getTokenCount(toolName);
@@ -1093,9 +1124,13 @@ class BaseClient {
return message;
}
- const files = await getFiles({
- file_id: { $in: fileIds },
- });
+ const files = await getFiles(
+ {
+ file_id: { $in: fileIds },
+ },
+ {},
+ {},
+ );
await this.addImageURLs(message, files, this.visionMode);
diff --git a/api/app/clients/GoogleClient.js b/api/app/clients/GoogleClient.js
index 03461a6796..58ee783d2a 100644
--- a/api/app/clients/GoogleClient.js
+++ b/api/app/clients/GoogleClient.js
@@ -51,7 +51,7 @@ class GoogleClient extends BaseClient {
const serviceKey = creds[AuthKeys.GOOGLE_SERVICE_KEY] ?? {};
this.serviceKey =
- serviceKey && typeof serviceKey === 'string' ? JSON.parse(serviceKey) : serviceKey ?? {};
+ serviceKey && typeof serviceKey === 'string' ? JSON.parse(serviceKey) : (serviceKey ?? {});
/** @type {string | null | undefined} */
this.project_id = this.serviceKey.project_id;
this.client_email = this.serviceKey.client_email;
@@ -73,6 +73,8 @@ class GoogleClient extends BaseClient {
* @type {string} */
this.outputTokensKey = 'output_tokens';
this.visionMode = VisionModes.generative;
+ /** @type {string} */
+ this.systemMessage;
if (options.skipSetOptions) {
return;
}
@@ -184,7 +186,7 @@ class GoogleClient extends BaseClient {
if (typeof this.options.artifactsPrompt === 'string' && this.options.artifactsPrompt) {
promptPrefix = `${promptPrefix ?? ''}\n${this.options.artifactsPrompt}`.trim();
}
- this.options.promptPrefix = promptPrefix;
+ this.systemMessage = promptPrefix;
this.initializeClient();
return this;
}
@@ -314,7 +316,7 @@ class GoogleClient extends BaseClient {
}
this.augmentedPrompt = await this.contextHandlers.createContext();
- this.options.promptPrefix = this.augmentedPrompt + this.options.promptPrefix;
+ this.systemMessage = this.augmentedPrompt + this.systemMessage;
}
}
@@ -361,8 +363,8 @@ class GoogleClient extends BaseClient {
throw new Error('[GoogleClient] PaLM 2 and Codey models are no longer supported.');
}
- if (this.options.promptPrefix) {
- const instructionsTokenCount = this.getTokenCount(this.options.promptPrefix);
+ if (this.systemMessage) {
+ const instructionsTokenCount = this.getTokenCount(this.systemMessage);
this.maxContextTokens = this.maxContextTokens - instructionsTokenCount;
if (this.maxContextTokens < 0) {
@@ -417,8 +419,8 @@ class GoogleClient extends BaseClient {
],
};
- if (this.options.promptPrefix) {
- payload.instances[0].context = this.options.promptPrefix;
+ if (this.systemMessage) {
+ payload.instances[0].context = this.systemMessage;
}
logger.debug('[GoogleClient] buildMessages', payload);
@@ -464,7 +466,7 @@ class GoogleClient extends BaseClient {
identityPrefix = `${identityPrefix}\nYou are ${this.options.modelLabel}`;
}
- let promptPrefix = (this.options.promptPrefix ?? '').trim();
+ let promptPrefix = (this.systemMessage ?? '').trim();
if (identityPrefix) {
promptPrefix = `${identityPrefix}${promptPrefix}`;
@@ -639,7 +641,7 @@ class GoogleClient extends BaseClient {
let error;
try {
if (!EXCLUDED_GENAI_MODELS.test(modelName) && !this.project_id) {
- /** @type {GenAI} */
+ /** @type {GenerativeModel} */
const client = this.client;
/** @type {GenerateContentRequest} */
const requestOptions = {
@@ -648,7 +650,7 @@ class GoogleClient extends BaseClient {
generationConfig: googleGenConfigSchema.parse(this.modelOptions),
};
- const promptPrefix = (this.options.promptPrefix ?? '').trim();
+ const promptPrefix = (this.systemMessage ?? '').trim();
if (promptPrefix.length) {
requestOptions.systemInstruction = {
parts: [
@@ -663,7 +665,17 @@ class GoogleClient extends BaseClient {
/** @type {GenAIUsageMetadata} */
let usageMetadata;
- const result = await client.generateContentStream(requestOptions);
+ abortController.signal.addEventListener(
+ 'abort',
+ () => {
+ logger.warn('[GoogleClient] Request was aborted', abortController.signal.reason);
+ },
+ { once: true },
+ );
+
+ const result = await client.generateContentStream(requestOptions, {
+ signal: abortController.signal,
+ });
for await (const chunk of result.stream) {
usageMetadata = !usageMetadata
? chunk?.usageMetadata
@@ -815,7 +827,8 @@ class GoogleClient extends BaseClient {
let reply = '';
const { abortController } = options;
- const model = this.modelOptions.modelName ?? this.modelOptions.model ?? '';
+ const model =
+ this.options.titleModel ?? this.modelOptions.modelName ?? this.modelOptions.model ?? '';
const safetySettings = getSafetySettings(model);
if (!EXCLUDED_GENAI_MODELS.test(model) && !this.project_id) {
logger.debug('Identified titling model as GenAI version');
diff --git a/api/app/clients/OllamaClient.js b/api/app/clients/OllamaClient.js
index d86e120f43..77d007580c 100644
--- a/api/app/clients/OllamaClient.js
+++ b/api/app/clients/OllamaClient.js
@@ -2,7 +2,7 @@ const { z } = require('zod');
const axios = require('axios');
const { Ollama } = require('ollama');
const { Constants } = require('librechat-data-provider');
-const { deriveBaseURL } = require('~/utils');
+const { deriveBaseURL, logAxiosError } = require('~/utils');
const { sleep } = require('~/server/utils');
const { logger } = require('~/config');
@@ -68,7 +68,7 @@ class OllamaClient {
} catch (error) {
const logMessage =
'Failed to fetch models from Ollama API. If you are not using Ollama directly, and instead, through some aggregator or reverse proxy that handles fetching via OpenAI spec, ensure the name of the endpoint doesn\'t start with `ollama` (case-insensitive).';
- logger.error(logMessage, error);
+ logAxiosError({ message: logMessage, error });
return [];
}
}
diff --git a/api/app/clients/OpenAIClient.js b/api/app/clients/OpenAIClient.js
index 368e7d6e84..b4477cca8a 100644
--- a/api/app/clients/OpenAIClient.js
+++ b/api/app/clients/OpenAIClient.js
@@ -7,6 +7,7 @@ const {
ImageDetail,
EModelEndpoint,
resolveHeaders,
+ KnownEndpoints,
openAISettings,
ImageDetailCost,
CohereConstants,
@@ -108,18 +109,14 @@ class OpenAIClient extends BaseClient {
const omniPattern = /\b(o1|o3)\b/i;
this.isOmni = omniPattern.test(this.modelOptions.model);
- const { OPENROUTER_API_KEY, OPENAI_FORCE_PROMPT } = process.env ?? {};
- if (OPENROUTER_API_KEY && !this.azure) {
- this.apiKey = OPENROUTER_API_KEY;
- this.useOpenRouter = true;
- }
-
+ const { OPENAI_FORCE_PROMPT } = process.env ?? {};
const { reverseProxyUrl: reverseProxy } = this.options;
if (
!this.useOpenRouter &&
- reverseProxy &&
- reverseProxy.includes('https://openrouter.ai/api/v1')
+ ((reverseProxy && reverseProxy.includes(KnownEndpoints.openrouter)) ||
+ (this.options.endpoint &&
+ this.options.endpoint.toLowerCase().includes(KnownEndpoints.openrouter)))
) {
this.useOpenRouter = true;
}
@@ -306,7 +303,9 @@ class OpenAIClient extends BaseClient {
}
getEncoding() {
- return this.model?.includes('gpt-4o') ? 'o200k_base' : 'cl100k_base';
+ return this.modelOptions?.model && /gpt-4[^-\s]/.test(this.modelOptions.model)
+ ? 'o200k_base'
+ : 'cl100k_base';
}
/**
@@ -613,7 +612,7 @@ class OpenAIClient extends BaseClient {
}
initializeLLM({
- model = 'gpt-4o-mini',
+ model = openAISettings.model.default,
modelName,
temperature = 0.2,
max_tokens,
@@ -714,7 +713,7 @@ class OpenAIClient extends BaseClient {
const { OPENAI_TITLE_MODEL } = process.env ?? {};
- let model = this.options.titleModel ?? OPENAI_TITLE_MODEL ?? 'gpt-4o-mini';
+ let model = this.options.titleModel ?? OPENAI_TITLE_MODEL ?? openAISettings.model.default;
if (model === Constants.CURRENT_MODEL) {
model = this.modelOptions.model;
}
@@ -907,7 +906,7 @@ ${convo}
let prompt;
// TODO: remove the gpt fallback and make it specific to endpoint
- const { OPENAI_SUMMARY_MODEL = 'gpt-4o-mini' } = process.env ?? {};
+ const { OPENAI_SUMMARY_MODEL = openAISettings.model.default } = process.env ?? {};
let model = this.options.summaryModel ?? OPENAI_SUMMARY_MODEL;
if (model === Constants.CURRENT_MODEL) {
model = this.modelOptions.model;
@@ -1108,6 +1107,16 @@ ${convo}
return (msg) => {
if (msg.text != null && msg.text && msg.text.startsWith(':::thinking')) {
msg.text = msg.text.replace(/:::thinking.*?:::/gs, '').trim();
+ } else if (msg.content != null) {
+ /** @type {import('@librechat/agents').MessageContentComplex} */
+ const newContent = [];
+ for (let part of msg.content) {
+ if (part.think != null) {
+ continue;
+ }
+ newContent.push(part);
+ }
+ msg.content = newContent;
}
return msg;
@@ -1273,6 +1282,29 @@ ${convo}
});
}
+ /** Note: OpenAI Web Search models do not support any known parameters besdies `max_tokens` */
+ if (modelOptions.model && /gpt-4o.*search/.test(modelOptions.model)) {
+ const searchExcludeParams = [
+ 'frequency_penalty',
+ 'presence_penalty',
+ 'temperature',
+ 'top_p',
+ 'top_k',
+ 'stop',
+ 'logit_bias',
+ 'seed',
+ 'response_format',
+ 'n',
+ 'logprobs',
+ 'user',
+ ];
+
+ this.options.dropParams = this.options.dropParams || [];
+ this.options.dropParams = [
+ ...new Set([...this.options.dropParams, ...searchExcludeParams]),
+ ];
+ }
+
if (this.options.dropParams && Array.isArray(this.options.dropParams)) {
this.options.dropParams.forEach((param) => {
delete modelOptions[param];
@@ -1308,8 +1340,12 @@ ${convo}
) {
delete modelOptions.stream;
delete modelOptions.stop;
- } else if (!this.isOmni && modelOptions.reasoning_effort != null) {
+ } else if (
+ (!this.isOmni || /^o1-(mini|preview)/i.test(modelOptions.model)) &&
+ modelOptions.reasoning_effort != null
+ ) {
delete modelOptions.reasoning_effort;
+ delete modelOptions.temperature;
}
let reasoningKey = 'reasoning_content';
@@ -1317,6 +1353,12 @@ ${convo}
modelOptions.include_reasoning = true;
reasoningKey = 'reasoning';
}
+ if (this.useOpenRouter && modelOptions.reasoning_effort != null) {
+ modelOptions.reasoning = {
+ effort: modelOptions.reasoning_effort,
+ };
+ delete modelOptions.reasoning_effort;
+ }
this.streamHandler = new SplitStreamHandler({
reasoningKey,
diff --git a/api/app/clients/prompts/addCacheControl.js b/api/app/clients/prompts/addCacheControl.js
index eed5910dc9..6bfd901a65 100644
--- a/api/app/clients/prompts/addCacheControl.js
+++ b/api/app/clients/prompts/addCacheControl.js
@@ -1,7 +1,7 @@
/**
* Anthropic API: Adds cache control to the appropriate user messages in the payload.
- * @param {Array} messages - The array of message objects.
- * @returns {Array} - The updated array of message objects with cache control added.
+ * @param {Array} messages - The array of message objects.
+ * @returns {Array} - The updated array of message objects with cache control added.
*/
function addCacheControl(messages) {
if (!Array.isArray(messages) || messages.length < 2) {
@@ -13,7 +13,9 @@ function addCacheControl(messages) {
for (let i = updatedMessages.length - 1; i >= 0 && userMessagesModified < 2; i--) {
const message = updatedMessages[i];
- if (message.role !== 'user') {
+ if (message.getType != null && message.getType() !== 'human') {
+ continue;
+ } else if (message.getType == null && message.role !== 'user') {
continue;
}
diff --git a/api/app/clients/prompts/formatAgentMessages.spec.js b/api/app/clients/prompts/formatAgentMessages.spec.js
index 20731f6984..360fa00a34 100644
--- a/api/app/clients/prompts/formatAgentMessages.spec.js
+++ b/api/app/clients/prompts/formatAgentMessages.spec.js
@@ -282,4 +282,80 @@ describe('formatAgentMessages', () => {
// Additional check to ensure the consecutive assistant messages were combined
expect(result[1].content).toHaveLength(2);
});
+
+ it('should skip THINK type content parts', () => {
+ const payload = [
+ {
+ role: 'assistant',
+ content: [
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'Initial response' },
+ { type: ContentTypes.THINK, [ContentTypes.THINK]: 'Reasoning about the problem...' },
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'Final answer' },
+ ],
+ },
+ ];
+
+ const result = formatAgentMessages(payload);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toBeInstanceOf(AIMessage);
+ expect(result[0].content).toEqual('Initial response\nFinal answer');
+ });
+
+ it('should join TEXT content as string when THINK content type is present', () => {
+ const payload = [
+ {
+ role: 'assistant',
+ content: [
+ { type: ContentTypes.THINK, [ContentTypes.THINK]: 'Analyzing the problem...' },
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'First part of response' },
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'Second part of response' },
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'Final part of response' },
+ ],
+ },
+ ];
+
+ const result = formatAgentMessages(payload);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toBeInstanceOf(AIMessage);
+ expect(typeof result[0].content).toBe('string');
+ expect(result[0].content).toBe(
+ 'First part of response\nSecond part of response\nFinal part of response',
+ );
+ expect(result[0].content).not.toContain('Analyzing the problem...');
+ });
+
+ it('should exclude ERROR type content parts', () => {
+ const payload = [
+ {
+ role: 'assistant',
+ content: [
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'Hello there' },
+ {
+ type: ContentTypes.ERROR,
+ [ContentTypes.ERROR]:
+ 'An error occurred while processing the request: Something went wrong',
+ },
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'Final answer' },
+ ],
+ },
+ ];
+
+ const result = formatAgentMessages(payload);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toBeInstanceOf(AIMessage);
+ expect(result[0].content).toEqual([
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'Hello there' },
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'Final answer' },
+ ]);
+
+ // Make sure no error content exists in the result
+ const hasErrorContent = result[0].content.some(
+ (item) =>
+ item.type === ContentTypes.ERROR || JSON.stringify(item).includes('An error occurred'),
+ );
+ expect(hasErrorContent).toBe(false);
+ });
});
diff --git a/api/app/clients/prompts/formatMessages.js b/api/app/clients/prompts/formatMessages.js
index d84e62cca8..9fa0d40497 100644
--- a/api/app/clients/prompts/formatMessages.js
+++ b/api/app/clients/prompts/formatMessages.js
@@ -153,6 +153,7 @@ const formatAgentMessages = (payload) => {
let currentContent = [];
let lastAIMessage = null;
+ let hasReasoning = false;
for (const part of message.content) {
if (part.type === ContentTypes.TEXT && part.tool_call_ids) {
/*
@@ -207,11 +208,27 @@ const formatAgentMessages = (payload) => {
content: output || '',
}),
);
+ } else if (part.type === ContentTypes.THINK) {
+ hasReasoning = true;
+ continue;
+ } else if (part.type === ContentTypes.ERROR || part.type === ContentTypes.AGENT_UPDATE) {
+ continue;
} else {
currentContent.push(part);
}
}
+ if (hasReasoning) {
+ currentContent = currentContent
+ .reduce((acc, curr) => {
+ if (curr.type === ContentTypes.TEXT) {
+ return `${acc}${curr[ContentTypes.TEXT]}\n`;
+ }
+ return acc;
+ }, '')
+ .trim();
+ }
+
if (currentContent.length > 0) {
messages.push(new AIMessage({ content: currentContent }));
}
diff --git a/api/app/clients/specs/AnthropicClient.test.js b/api/app/clients/specs/AnthropicClient.test.js
index eef6bb6748..223f3038c0 100644
--- a/api/app/clients/specs/AnthropicClient.test.js
+++ b/api/app/clients/specs/AnthropicClient.test.js
@@ -1,3 +1,4 @@
+const { SplitStreamHandler } = require('@librechat/agents');
const { anthropicSettings } = require('librechat-data-provider');
const AnthropicClient = require('~/app/clients/AnthropicClient');
@@ -405,4 +406,327 @@ describe('AnthropicClient', () => {
expect(Number.isNaN(result)).toBe(false);
});
});
+
+ describe('maxOutputTokens handling for different models', () => {
+ it('should not cap maxOutputTokens for Claude 3.5 Sonnet models', () => {
+ const client = new AnthropicClient('test-api-key');
+ const highTokenValue = anthropicSettings.legacy.maxOutputTokens.default * 10;
+
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3-5-sonnet',
+ maxOutputTokens: highTokenValue,
+ },
+ });
+
+ expect(client.modelOptions.maxOutputTokens).toBe(highTokenValue);
+
+ // Test with decimal notation
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3.5-sonnet',
+ maxOutputTokens: highTokenValue,
+ },
+ });
+
+ expect(client.modelOptions.maxOutputTokens).toBe(highTokenValue);
+ });
+
+ it('should not cap maxOutputTokens for Claude 3.7 models', () => {
+ const client = new AnthropicClient('test-api-key');
+ const highTokenValue = anthropicSettings.legacy.maxOutputTokens.default * 2;
+
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3-7-sonnet',
+ maxOutputTokens: highTokenValue,
+ },
+ });
+
+ expect(client.modelOptions.maxOutputTokens).toBe(highTokenValue);
+
+ // Test with decimal notation
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3.7-sonnet',
+ maxOutputTokens: highTokenValue,
+ },
+ });
+
+ expect(client.modelOptions.maxOutputTokens).toBe(highTokenValue);
+ });
+
+ it('should cap maxOutputTokens for Claude 3.5 Haiku models', () => {
+ const client = new AnthropicClient('test-api-key');
+ const highTokenValue = anthropicSettings.legacy.maxOutputTokens.default * 2;
+
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3-5-haiku',
+ maxOutputTokens: highTokenValue,
+ },
+ });
+
+ expect(client.modelOptions.maxOutputTokens).toBe(
+ anthropicSettings.legacy.maxOutputTokens.default,
+ );
+
+ // Test with decimal notation
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3.5-haiku',
+ maxOutputTokens: highTokenValue,
+ },
+ });
+
+ expect(client.modelOptions.maxOutputTokens).toBe(
+ anthropicSettings.legacy.maxOutputTokens.default,
+ );
+ });
+
+ it('should cap maxOutputTokens for Claude 3 Haiku and Opus models', () => {
+ const client = new AnthropicClient('test-api-key');
+ const highTokenValue = anthropicSettings.legacy.maxOutputTokens.default * 2;
+
+ // Test haiku
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3-haiku',
+ maxOutputTokens: highTokenValue,
+ },
+ });
+
+ expect(client.modelOptions.maxOutputTokens).toBe(
+ anthropicSettings.legacy.maxOutputTokens.default,
+ );
+
+ // Test opus
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3-opus',
+ maxOutputTokens: highTokenValue,
+ },
+ });
+
+ expect(client.modelOptions.maxOutputTokens).toBe(
+ anthropicSettings.legacy.maxOutputTokens.default,
+ );
+ });
+ });
+
+ describe('topK/topP parameters for different models', () => {
+ beforeEach(() => {
+ // Mock the SplitStreamHandler
+ jest.spyOn(SplitStreamHandler.prototype, 'handle').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it('should include top_k and top_p parameters for non-claude-3.7 models', async () => {
+ const client = new AnthropicClient('test-api-key');
+
+ // Create a mock async generator function
+ async function* mockAsyncGenerator() {
+ yield { type: 'message_start', message: { usage: {} } };
+ yield { delta: { text: 'Test response' } };
+ yield { type: 'message_delta', usage: {} };
+ }
+
+ // Mock createResponse to return the async generator
+ jest.spyOn(client, 'createResponse').mockImplementation(() => {
+ return mockAsyncGenerator();
+ });
+
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3-opus',
+ temperature: 0.7,
+ topK: 10,
+ topP: 0.9,
+ },
+ });
+
+ // Mock getClient to capture the request options
+ let capturedOptions = null;
+ jest.spyOn(client, 'getClient').mockImplementation((options) => {
+ capturedOptions = options;
+ return {};
+ });
+
+ const payload = [{ role: 'user', content: 'Test message' }];
+ await client.sendCompletion(payload, {});
+
+ // Check the options passed to getClient
+ expect(capturedOptions).toHaveProperty('top_k', 10);
+ expect(capturedOptions).toHaveProperty('top_p', 0.9);
+ });
+
+ it('should include top_k and top_p parameters for claude-3-5-sonnet models', async () => {
+ const client = new AnthropicClient('test-api-key');
+
+ // Create a mock async generator function
+ async function* mockAsyncGenerator() {
+ yield { type: 'message_start', message: { usage: {} } };
+ yield { delta: { text: 'Test response' } };
+ yield { type: 'message_delta', usage: {} };
+ }
+
+ // Mock createResponse to return the async generator
+ jest.spyOn(client, 'createResponse').mockImplementation(() => {
+ return mockAsyncGenerator();
+ });
+
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3-5-sonnet',
+ temperature: 0.7,
+ topK: 10,
+ topP: 0.9,
+ },
+ });
+
+ // Mock getClient to capture the request options
+ let capturedOptions = null;
+ jest.spyOn(client, 'getClient').mockImplementation((options) => {
+ capturedOptions = options;
+ return {};
+ });
+
+ const payload = [{ role: 'user', content: 'Test message' }];
+ await client.sendCompletion(payload, {});
+
+ // Check the options passed to getClient
+ expect(capturedOptions).toHaveProperty('top_k', 10);
+ expect(capturedOptions).toHaveProperty('top_p', 0.9);
+ });
+
+ it('should not include top_k and top_p parameters for claude-3-7-sonnet models', async () => {
+ const client = new AnthropicClient('test-api-key');
+
+ // Create a mock async generator function
+ async function* mockAsyncGenerator() {
+ yield { type: 'message_start', message: { usage: {} } };
+ yield { delta: { text: 'Test response' } };
+ yield { type: 'message_delta', usage: {} };
+ }
+
+ // Mock createResponse to return the async generator
+ jest.spyOn(client, 'createResponse').mockImplementation(() => {
+ return mockAsyncGenerator();
+ });
+
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3-7-sonnet',
+ temperature: 0.7,
+ topK: 10,
+ topP: 0.9,
+ },
+ });
+
+ // Mock getClient to capture the request options
+ let capturedOptions = null;
+ jest.spyOn(client, 'getClient').mockImplementation((options) => {
+ capturedOptions = options;
+ return {};
+ });
+
+ const payload = [{ role: 'user', content: 'Test message' }];
+ await client.sendCompletion(payload, {});
+
+ // Check the options passed to getClient
+ expect(capturedOptions).not.toHaveProperty('top_k');
+ expect(capturedOptions).not.toHaveProperty('top_p');
+ });
+
+ it('should not include top_k and top_p parameters for models with decimal notation (claude-3.7)', async () => {
+ const client = new AnthropicClient('test-api-key');
+
+ // Create a mock async generator function
+ async function* mockAsyncGenerator() {
+ yield { type: 'message_start', message: { usage: {} } };
+ yield { delta: { text: 'Test response' } };
+ yield { type: 'message_delta', usage: {} };
+ }
+
+ // Mock createResponse to return the async generator
+ jest.spyOn(client, 'createResponse').mockImplementation(() => {
+ return mockAsyncGenerator();
+ });
+
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3.7-sonnet',
+ temperature: 0.7,
+ topK: 10,
+ topP: 0.9,
+ },
+ });
+
+ // Mock getClient to capture the request options
+ let capturedOptions = null;
+ jest.spyOn(client, 'getClient').mockImplementation((options) => {
+ capturedOptions = options;
+ return {};
+ });
+
+ const payload = [{ role: 'user', content: 'Test message' }];
+ await client.sendCompletion(payload, {});
+
+ // Check the options passed to getClient
+ expect(capturedOptions).not.toHaveProperty('top_k');
+ expect(capturedOptions).not.toHaveProperty('top_p');
+ });
+ });
+
+ it('should include top_k and top_p parameters for Claude-3.7 models when thinking is explicitly disabled', async () => {
+ const client = new AnthropicClient('test-api-key', {
+ modelOptions: {
+ model: 'claude-3-7-sonnet',
+ temperature: 0.7,
+ topK: 10,
+ topP: 0.9,
+ },
+ thinking: false,
+ });
+
+ async function* mockAsyncGenerator() {
+ yield { type: 'message_start', message: { usage: {} } };
+ yield { delta: { text: 'Test response' } };
+ yield { type: 'message_delta', usage: {} };
+ }
+
+ jest.spyOn(client, 'createResponse').mockImplementation(() => {
+ return mockAsyncGenerator();
+ });
+
+ let capturedOptions = null;
+ jest.spyOn(client, 'getClient').mockImplementation((options) => {
+ capturedOptions = options;
+ return {};
+ });
+
+ const payload = [{ role: 'user', content: 'Test message' }];
+ await client.sendCompletion(payload, {});
+
+ expect(capturedOptions).toHaveProperty('topK', 10);
+ expect(capturedOptions).toHaveProperty('topP', 0.9);
+
+ client.setOptions({
+ modelOptions: {
+ model: 'claude-3.7-sonnet',
+ temperature: 0.7,
+ topK: 10,
+ topP: 0.9,
+ },
+ thinking: false,
+ });
+
+ await client.sendCompletion(payload, {});
+
+ expect(capturedOptions).toHaveProperty('topK', 10);
+ expect(capturedOptions).toHaveProperty('topP', 0.9);
+ });
});
diff --git a/api/app/clients/specs/BaseClient.test.js b/api/app/clients/specs/BaseClient.test.js
index e899449fb9..c9be50d3de 100644
--- a/api/app/clients/specs/BaseClient.test.js
+++ b/api/app/clients/specs/BaseClient.test.js
@@ -30,6 +30,8 @@ jest.mock('~/models', () => ({
updateFileUsage: jest.fn(),
}));
+const { getConvo, saveConvo } = require('~/models');
+
jest.mock('@langchain/openai', () => {
return {
ChatOpenAI: jest.fn().mockImplementation(() => {
@@ -162,7 +164,7 @@ describe('BaseClient', () => {
const result = await TestClient.getMessagesWithinTokenLimit({ messages });
expect(result.context).toEqual(expectedContext);
- expect(result.summaryIndex).toEqual(expectedIndex);
+ expect(result.messagesToRefine.length - 1).toEqual(expectedIndex);
expect(result.remainingContextTokens).toBe(expectedRemainingContextTokens);
expect(result.messagesToRefine).toEqual(expectedMessagesToRefine);
});
@@ -198,7 +200,7 @@ describe('BaseClient', () => {
const result = await TestClient.getMessagesWithinTokenLimit({ messages });
expect(result.context).toEqual(expectedContext);
- expect(result.summaryIndex).toEqual(expectedIndex);
+ expect(result.messagesToRefine.length - 1).toEqual(expectedIndex);
expect(result.remainingContextTokens).toBe(expectedRemainingContextTokens);
expect(result.messagesToRefine).toEqual(expectedMessagesToRefine);
});
@@ -540,10 +542,11 @@ describe('BaseClient', () => {
test('saveMessageToDatabase is called with the correct arguments', async () => {
const saveOptions = TestClient.getSaveOptions();
- const user = {}; // Mock user
+ const user = {};
const opts = { user };
+ const saveSpy = jest.spyOn(TestClient, 'saveMessageToDatabase');
await TestClient.sendMessage('Hello, world!', opts);
- expect(TestClient.saveMessageToDatabase).toHaveBeenCalledWith(
+ expect(saveSpy).toHaveBeenCalledWith(
expect.objectContaining({
sender: expect.any(String),
text: expect.any(String),
@@ -557,6 +560,157 @@ describe('BaseClient', () => {
);
});
+ test('should handle existing conversation when getConvo retrieves one', async () => {
+ const existingConvo = {
+ conversationId: 'existing-convo-id',
+ endpoint: 'openai',
+ endpointType: 'openai',
+ model: 'gpt-3.5-turbo',
+ messages: [
+ { role: 'user', content: 'Existing message 1' },
+ { role: 'assistant', content: 'Existing response 1' },
+ ],
+ temperature: 1,
+ };
+
+ const { temperature: _temp, ...newConvo } = existingConvo;
+
+ const user = {
+ id: 'user-id',
+ };
+
+ getConvo.mockResolvedValue(existingConvo);
+ saveConvo.mockResolvedValue(newConvo);
+
+ TestClient = initializeFakeClient(
+ apiKey,
+ {
+ ...options,
+ req: {
+ user,
+ },
+ },
+ [],
+ );
+
+ const saveSpy = jest.spyOn(TestClient, 'saveMessageToDatabase');
+
+ const newMessage = 'New message in existing conversation';
+ const response = await TestClient.sendMessage(newMessage, {
+ user,
+ conversationId: existingConvo.conversationId,
+ });
+
+ expect(getConvo).toHaveBeenCalledWith(user.id, existingConvo.conversationId);
+ expect(TestClient.conversationId).toBe(existingConvo.conversationId);
+ expect(response.conversationId).toBe(existingConvo.conversationId);
+ expect(TestClient.fetchedConvo).toBe(true);
+
+ expect(saveSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ conversationId: existingConvo.conversationId,
+ text: newMessage,
+ }),
+ expect.any(Object),
+ expect.any(Object),
+ );
+
+ expect(saveConvo).toHaveBeenCalledTimes(2);
+ expect(saveConvo).toHaveBeenCalledWith(
+ expect.any(Object),
+ expect.objectContaining({
+ conversationId: existingConvo.conversationId,
+ }),
+ expect.objectContaining({
+ context: 'api/app/clients/BaseClient.js - saveMessageToDatabase #saveConvo',
+ unsetFields: {
+ temperature: 1,
+ },
+ }),
+ );
+
+ await TestClient.sendMessage('Another message', {
+ conversationId: existingConvo.conversationId,
+ });
+ expect(getConvo).toHaveBeenCalledTimes(1);
+ });
+
+ test('should correctly handle existing conversation and unset fields appropriately', async () => {
+ const existingConvo = {
+ conversationId: 'existing-convo-id',
+ endpoint: 'openai',
+ endpointType: 'openai',
+ model: 'gpt-3.5-turbo',
+ messages: [
+ { role: 'user', content: 'Existing message 1' },
+ { role: 'assistant', content: 'Existing response 1' },
+ ],
+ title: 'Existing Conversation',
+ someExistingField: 'existingValue',
+ anotherExistingField: 'anotherValue',
+ temperature: 0.7,
+ modelLabel: 'GPT-3.5',
+ };
+
+ getConvo.mockResolvedValue(existingConvo);
+ saveConvo.mockResolvedValue(existingConvo);
+
+ TestClient = initializeFakeClient(
+ apiKey,
+ {
+ ...options,
+ modelOptions: {
+ model: 'gpt-4',
+ temperature: 0.5,
+ },
+ },
+ [],
+ );
+
+ const newMessage = 'New message in existing conversation';
+ await TestClient.sendMessage(newMessage, {
+ conversationId: existingConvo.conversationId,
+ });
+
+ expect(saveConvo).toHaveBeenCalledTimes(2);
+
+ const saveConvoCall = saveConvo.mock.calls[0];
+ const [, savedFields, saveOptions] = saveConvoCall;
+
+ // Instead of checking all excludedKeys, we'll just check specific fields
+ // that we know should be excluded
+ expect(savedFields).not.toHaveProperty('messages');
+ expect(savedFields).not.toHaveProperty('title');
+
+ // Only check that someExistingField is in unsetFields
+ expect(saveOptions.unsetFields).toHaveProperty('someExistingField', 1);
+
+ // Mock saveConvo to return the expected fields
+ saveConvo.mockImplementation((req, fields) => {
+ return Promise.resolve({
+ ...fields,
+ endpoint: 'openai',
+ endpointType: 'openai',
+ model: 'gpt-4',
+ temperature: 0.5,
+ });
+ });
+
+ // Only check the conversationId since that's the only field we can be sure about
+ expect(savedFields).toHaveProperty('conversationId', 'existing-convo-id');
+
+ expect(TestClient.fetchedConvo).toBe(true);
+
+ await TestClient.sendMessage('Another message', {
+ conversationId: existingConvo.conversationId,
+ });
+
+ expect(getConvo).toHaveBeenCalledTimes(1);
+
+ const secondSaveConvoCall = saveConvo.mock.calls[1];
+ expect(secondSaveConvoCall[2]).toHaveProperty('unsetFields', {});
+ });
+
test('sendCompletion is called with the correct arguments', async () => {
const payload = {}; // Mock payload
TestClient.buildMessages.mockReturnValue({ prompt: payload, tokenCountMap: null });
diff --git a/api/app/clients/specs/FakeClient.js b/api/app/clients/specs/FakeClient.js
index 7f4b75e1db..a466bb97f9 100644
--- a/api/app/clients/specs/FakeClient.js
+++ b/api/app/clients/specs/FakeClient.js
@@ -56,7 +56,6 @@ const initializeFakeClient = (apiKey, options, fakeMessages) => {
let TestClient = new FakeClient(apiKey);
TestClient.options = options;
TestClient.abortController = { abort: jest.fn() };
- TestClient.saveMessageToDatabase = jest.fn();
TestClient.loadHistory = jest
.fn()
.mockImplementation((conversationId, parentMessageId = null) => {
@@ -86,7 +85,6 @@ const initializeFakeClient = (apiKey, options, fakeMessages) => {
return 'Mock response text';
});
- // eslint-disable-next-line no-unused-vars
TestClient.getCompletion = jest.fn().mockImplementation(async (..._args) => {
return {
choices: [
diff --git a/api/app/clients/specs/OpenAIClient.test.js b/api/app/clients/specs/OpenAIClient.test.js
index 2aaec518eb..0e811cf38a 100644
--- a/api/app/clients/specs/OpenAIClient.test.js
+++ b/api/app/clients/specs/OpenAIClient.test.js
@@ -202,14 +202,6 @@ describe('OpenAIClient', () => {
expect(client.modelOptions.temperature).toBe(0.7);
});
- it('should set apiKey and useOpenRouter if OPENROUTER_API_KEY is present', () => {
- process.env.OPENROUTER_API_KEY = 'openrouter-key';
- client.setOptions({});
- expect(client.apiKey).toBe('openrouter-key');
- expect(client.useOpenRouter).toBe(true);
- delete process.env.OPENROUTER_API_KEY; // Cleanup
- });
-
it('should set FORCE_PROMPT based on OPENAI_FORCE_PROMPT or reverseProxyUrl', () => {
process.env.OPENAI_FORCE_PROMPT = 'true';
client.setOptions({});
@@ -534,7 +526,6 @@ describe('OpenAIClient', () => {
afterEach(() => {
delete process.env.AZURE_OPENAI_DEFAULT_MODEL;
delete process.env.AZURE_USE_MODEL_AS_DEPLOYMENT_NAME;
- delete process.env.OPENROUTER_API_KEY;
});
it('should call getCompletion and fetchEventSource when using a text/instruct model', async () => {
diff --git a/api/app/clients/tools/index.js b/api/app/clients/tools/index.js
index b8df50c77d..df436fb089 100644
--- a/api/app/clients/tools/index.js
+++ b/api/app/clients/tools/index.js
@@ -2,9 +2,10 @@ const availableTools = require('./manifest.json');
// Structured Tools
const DALLE3 = require('./structured/DALLE3');
+const FluxAPI = require('./structured/FluxAPI');
const OpenWeather = require('./structured/OpenWeather');
-const createYouTubeTools = require('./structured/YouTube');
const StructuredWolfram = require('./structured/Wolfram');
+const createYouTubeTools = require('./structured/YouTube');
const StructuredACS = require('./structured/AzureAISearch');
const StructuredSD = require('./structured/StableDiffusion');
const GoogleSearchAPI = require('./structured/GoogleSearch');
@@ -30,6 +31,7 @@ module.exports = {
manifestToolMap,
// Structured Tools
DALLE3,
+ FluxAPI,
OpenWeather,
StructuredSD,
StructuredACS,
diff --git a/api/app/clients/tools/manifest.json b/api/app/clients/tools/manifest.json
index 7cb92b8d87..43be7a4e6c 100644
--- a/api/app/clients/tools/manifest.json
+++ b/api/app/clients/tools/manifest.json
@@ -164,5 +164,19 @@
"description": "Sign up at OpenWeather, then get your key at API keys."
}
]
+ },
+ {
+ "name": "Flux",
+ "pluginKey": "flux",
+ "description": "Generate images using text with the Flux API.",
+ "icon": "https://blackforestlabs.ai/wp-content/uploads/2024/07/bfl_logo_retraced_blk.png",
+ "isAuthRequired": "true",
+ "authConfig": [
+ {
+ "authField": "FLUX_API_KEY",
+ "label": "Your Flux API Key",
+ "description": "Provide your Flux API key from your user profile."
+ }
+ ]
}
]
diff --git a/api/app/clients/tools/structured/DALLE3.js b/api/app/clients/tools/structured/DALLE3.js
index b604ad4ea4..fc0f1851f6 100644
--- a/api/app/clients/tools/structured/DALLE3.js
+++ b/api/app/clients/tools/structured/DALLE3.js
@@ -1,14 +1,17 @@
const { z } = require('zod');
const path = require('path');
const OpenAI = require('openai');
+const fetch = require('node-fetch');
const { v4: uuidv4 } = require('uuid');
const { Tool } = require('@langchain/core/tools');
const { HttpsProxyAgent } = require('https-proxy-agent');
-const { FileContext } = require('librechat-data-provider');
+const { FileContext, ContentTypes } = require('librechat-data-provider');
const { getImageBasename } = require('~/server/services/Files/images');
const extractBaseURL = require('~/utils/extractBaseURL');
const { logger } = require('~/config');
+const displayMessage =
+ 'DALL-E displayed an image. All generated images are already plainly visible, so don\'t repeat the descriptions in detail. Do not list download links as they are available in the UI already. The user may download the images by clicking on them, but do not mention anything about downloading to the user.';
class DALLE3 extends Tool {
constructor(fields = {}) {
super();
@@ -114,10 +117,7 @@ class DALLE3 extends Tool {
if (this.isAgent === true && typeof value === 'string') {
return [value, {}];
} else if (this.isAgent === true && typeof value === 'object') {
- return [
- 'DALL-E displayed an image. All generated images are already plainly visible, so don\'t repeat the descriptions in detail. Do not list download links as they are available in the UI already. The user may download the images by clicking on them, but do not mention anything about downloading to the user.',
- value,
- ];
+ return [displayMessage, value];
}
return value;
@@ -160,6 +160,32 @@ Error Message: ${error.message}`);
);
}
+ if (this.isAgent) {
+ let fetchOptions = {};
+ if (process.env.PROXY) {
+ fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
+ }
+ const imageResponse = await fetch(theImageUrl, fetchOptions);
+ const arrayBuffer = await imageResponse.arrayBuffer();
+ const base64 = Buffer.from(arrayBuffer).toString('base64');
+ const content = [
+ {
+ type: ContentTypes.IMAGE_URL,
+ image_url: {
+ url: `data:image/png;base64,${base64}`,
+ },
+ },
+ ];
+
+ const response = [
+ {
+ type: ContentTypes.TEXT,
+ text: displayMessage,
+ },
+ ];
+ return [response, { content }];
+ }
+
const imageBasename = getImageBasename(theImageUrl);
const imageExt = path.extname(imageBasename);
diff --git a/api/app/clients/tools/structured/FluxAPI.js b/api/app/clients/tools/structured/FluxAPI.js
new file mode 100644
index 0000000000..80f9772200
--- /dev/null
+++ b/api/app/clients/tools/structured/FluxAPI.js
@@ -0,0 +1,554 @@
+const { z } = require('zod');
+const axios = require('axios');
+const fetch = require('node-fetch');
+const { v4: uuidv4 } = require('uuid');
+const { Tool } = require('@langchain/core/tools');
+const { HttpsProxyAgent } = require('https-proxy-agent');
+const { FileContext, ContentTypes } = require('librechat-data-provider');
+const { logger } = require('~/config');
+
+const displayMessage =
+ 'Flux displayed an image. All generated images are already plainly visible, so don\'t repeat the descriptions in detail. Do not list download links as they are available in the UI already. The user may download the images by clicking on them, but do not mention anything about downloading to the user.';
+
+/**
+ * FluxAPI - A tool for generating high-quality images from text prompts using the Flux API.
+ * Each call generates one image. If multiple images are needed, make multiple consecutive calls with the same or varied prompts.
+ */
+class FluxAPI extends Tool {
+ // Pricing constants in USD per image
+ static PRICING = {
+ FLUX_PRO_1_1_ULTRA: -0.06, // /v1/flux-pro-1.1-ultra
+ FLUX_PRO_1_1: -0.04, // /v1/flux-pro-1.1
+ FLUX_PRO: -0.05, // /v1/flux-pro
+ FLUX_DEV: -0.025, // /v1/flux-dev
+ FLUX_PRO_FINETUNED: -0.06, // /v1/flux-pro-finetuned
+ FLUX_PRO_1_1_ULTRA_FINETUNED: -0.07, // /v1/flux-pro-1.1-ultra-finetuned
+ };
+
+ constructor(fields = {}) {
+ super();
+
+ /** @type {boolean} Used to initialize the Tool without necessary variables. */
+ this.override = fields.override ?? false;
+
+ this.userId = fields.userId;
+ this.fileStrategy = fields.fileStrategy;
+
+ /** @type {boolean} **/
+ this.isAgent = fields.isAgent;
+ this.returnMetadata = fields.returnMetadata ?? false;
+
+ if (fields.processFileURL) {
+ /** @type {processFileURL} Necessary for output to contain all image metadata. */
+ this.processFileURL = fields.processFileURL.bind(this);
+ }
+
+ this.apiKey = fields.FLUX_API_KEY || this.getApiKey();
+
+ this.name = 'flux';
+ this.description =
+ 'Use Flux to generate images from text descriptions. This tool can generate images and list available finetunes. Each generate call creates one image. For multiple images, make multiple consecutive calls.';
+
+ this.description_for_model = `// Transform any image description into a detailed, high-quality prompt. Never submit a prompt under 3 sentences. Follow these core rules:
+ // 1. ALWAYS enhance basic prompts into 5-10 detailed sentences (e.g., "a cat" becomes: "A close-up photo of a sleek Siamese cat with piercing blue eyes. The cat sits elegantly on a vintage leather armchair, its tail curled gracefully around its paws. Warm afternoon sunlight streams through a nearby window, casting gentle shadows across its face and highlighting the subtle variations in its cream and chocolate-point fur. The background is softly blurred, creating a shallow depth of field that draws attention to the cat's expressive features. The overall composition has a peaceful, contemplative mood with a professional photography style.")
+ // 2. Each prompt MUST be 3-6 descriptive sentences minimum, focusing on visual elements: lighting, composition, mood, and style
+ // Use action: 'list_finetunes' to see available custom models. When using finetunes, use endpoint: '/v1/flux-pro-finetuned' (default) or '/v1/flux-pro-1.1-ultra-finetuned' for higher quality and aspect ratio.`;
+
+ // Add base URL from environment variable with fallback
+ this.baseUrl = process.env.FLUX_API_BASE_URL || 'https://api.us1.bfl.ai';
+
+ // Define the schema for structured input
+ this.schema = z.object({
+ action: z
+ .enum(['generate', 'list_finetunes', 'generate_finetuned'])
+ .default('generate')
+ .describe(
+ 'Action to perform: "generate" for image generation, "generate_finetuned" for finetuned model generation, "list_finetunes" to get available custom models',
+ ),
+ prompt: z
+ .string()
+ .optional()
+ .describe(
+ 'Text prompt for image generation. Required when action is "generate". Not used for list_finetunes.',
+ ),
+ width: z
+ .number()
+ .optional()
+ .describe(
+ 'Width of the generated image in pixels. Must be a multiple of 32. Default is 1024.',
+ ),
+ height: z
+ .number()
+ .optional()
+ .describe(
+ 'Height of the generated image in pixels. Must be a multiple of 32. Default is 768.',
+ ),
+ prompt_upsampling: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe('Whether to perform upsampling on the prompt.'),
+ steps: z
+ .number()
+ .int()
+ .optional()
+ .describe('Number of steps to run the model for, a number from 1 to 50. Default is 40.'),
+ seed: z.number().optional().describe('Optional seed for reproducibility.'),
+ safety_tolerance: z
+ .number()
+ .optional()
+ .default(6)
+ .describe(
+ 'Tolerance level for input and output moderation. Between 0 and 6, 0 being most strict, 6 being least strict.',
+ ),
+ endpoint: z
+ .enum([
+ '/v1/flux-pro-1.1',
+ '/v1/flux-pro',
+ '/v1/flux-dev',
+ '/v1/flux-pro-1.1-ultra',
+ '/v1/flux-pro-finetuned',
+ '/v1/flux-pro-1.1-ultra-finetuned',
+ ])
+ .optional()
+ .default('/v1/flux-pro-1.1')
+ .describe('Endpoint to use for image generation.'),
+ raw: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe(
+ 'Generate less processed, more natural-looking images. Only works for /v1/flux-pro-1.1-ultra.',
+ ),
+ finetune_id: z.string().optional().describe('ID of the finetuned model to use'),
+ finetune_strength: z
+ .number()
+ .optional()
+ .default(1.1)
+ .describe('Strength of the finetuning effect (typically between 0.1 and 1.2)'),
+ guidance: z.number().optional().default(2.5).describe('Guidance scale for finetuned models'),
+ aspect_ratio: z
+ .string()
+ .optional()
+ .default('16:9')
+ .describe('Aspect ratio for ultra models (e.g., "16:9")'),
+ });
+ }
+
+ getAxiosConfig() {
+ const config = {};
+ if (process.env.PROXY) {
+ config.httpsAgent = new HttpsProxyAgent(process.env.PROXY);
+ }
+ return config;
+ }
+
+ /** @param {Object|string} value */
+ getDetails(value) {
+ if (typeof value === 'string') {
+ return value;
+ }
+ return JSON.stringify(value, null, 2);
+ }
+
+ getApiKey() {
+ const apiKey = process.env.FLUX_API_KEY || '';
+ if (!apiKey && !this.override) {
+ throw new Error('Missing FLUX_API_KEY environment variable.');
+ }
+ return apiKey;
+ }
+
+ wrapInMarkdown(imageUrl) {
+ const serverDomain = process.env.DOMAIN_SERVER || 'http://localhost:3080';
+ return ``;
+ }
+
+ returnValue(value) {
+ if (this.isAgent === true && typeof value === 'string') {
+ return [value, {}];
+ } else if (this.isAgent === true && typeof value === 'object') {
+ if (Array.isArray(value)) {
+ return value;
+ }
+ return [displayMessage, value];
+ }
+ return value;
+ }
+
+ async _call(data) {
+ const { action = 'generate', ...imageData } = data;
+
+ // Use provided API key for this request if available, otherwise use default
+ const requestApiKey = this.apiKey || this.getApiKey();
+
+ // Handle list_finetunes action
+ if (action === 'list_finetunes') {
+ return this.getMyFinetunes(requestApiKey);
+ }
+
+ // Handle finetuned generation
+ if (action === 'generate_finetuned') {
+ return this.generateFinetunedImage(imageData, requestApiKey);
+ }
+
+ // For generate action, ensure prompt is provided
+ if (!imageData.prompt) {
+ throw new Error('Missing required field: prompt');
+ }
+
+ let payload = {
+ prompt: imageData.prompt,
+ prompt_upsampling: imageData.prompt_upsampling || false,
+ safety_tolerance: imageData.safety_tolerance || 6,
+ output_format: imageData.output_format || 'png',
+ };
+
+ // Add optional parameters if provided
+ if (imageData.width) {
+ payload.width = imageData.width;
+ }
+ if (imageData.height) {
+ payload.height = imageData.height;
+ }
+ if (imageData.steps) {
+ payload.steps = imageData.steps;
+ }
+ if (imageData.seed !== undefined) {
+ payload.seed = imageData.seed;
+ }
+ if (imageData.raw) {
+ payload.raw = imageData.raw;
+ }
+
+ const generateUrl = `${this.baseUrl}${imageData.endpoint || '/v1/flux-pro'}`;
+ const resultUrl = `${this.baseUrl}/v1/get_result`;
+
+ logger.debug('[FluxAPI] Generating image with payload:', payload);
+ logger.debug('[FluxAPI] Using endpoint:', generateUrl);
+
+ let taskResponse;
+ try {
+ taskResponse = await axios.post(generateUrl, payload, {
+ headers: {
+ 'x-key': requestApiKey,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ ...this.getAxiosConfig(),
+ });
+ } catch (error) {
+ const details = this.getDetails(error?.response?.data || error.message);
+ logger.error('[FluxAPI] Error while submitting task:', details);
+
+ return this.returnValue(
+ `Something went wrong when trying to generate the image. The Flux API may be unavailable:
+ Error Message: ${details}`,
+ );
+ }
+
+ const taskId = taskResponse.data.id;
+
+ // Polling for the result
+ let status = 'Pending';
+ let resultData = null;
+ while (status !== 'Ready' && status !== 'Error') {
+ try {
+ // Wait 2 seconds between polls
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ const resultResponse = await axios.get(resultUrl, {
+ headers: {
+ 'x-key': requestApiKey,
+ Accept: 'application/json',
+ },
+ params: { id: taskId },
+ ...this.getAxiosConfig(),
+ });
+ status = resultResponse.data.status;
+
+ if (status === 'Ready') {
+ resultData = resultResponse.data.result;
+ break;
+ } else if (status === 'Error') {
+ logger.error('[FluxAPI] Error in task:', resultResponse.data);
+ return this.returnValue('An error occurred during image generation.');
+ }
+ } catch (error) {
+ const details = this.getDetails(error?.response?.data || error.message);
+ logger.error('[FluxAPI] Error while getting result:', details);
+ return this.returnValue('An error occurred while retrieving the image.');
+ }
+ }
+
+ // If no result data
+ if (!resultData || !resultData.sample) {
+ logger.error('[FluxAPI] No image data received from API. Response:', resultData);
+ return this.returnValue('No image data received from Flux API.');
+ }
+
+ // Try saving the image locally
+ const imageUrl = resultData.sample;
+ const imageName = `img-${uuidv4()}.png`;
+
+ if (this.isAgent) {
+ try {
+ // Fetch the image and convert to base64
+ const fetchOptions = {};
+ if (process.env.PROXY) {
+ fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
+ }
+ const imageResponse = await fetch(imageUrl, fetchOptions);
+ const arrayBuffer = await imageResponse.arrayBuffer();
+ const base64 = Buffer.from(arrayBuffer).toString('base64');
+ const content = [
+ {
+ type: ContentTypes.IMAGE_URL,
+ image_url: {
+ url: `data:image/png;base64,${base64}`,
+ },
+ },
+ ];
+
+ const response = [
+ {
+ type: ContentTypes.TEXT,
+ text: displayMessage,
+ },
+ ];
+ return [response, { content }];
+ } catch (error) {
+ logger.error('Error processing image for agent:', error);
+ return this.returnValue(`Failed to process the image. ${error.message}`);
+ }
+ }
+
+ try {
+ logger.debug('[FluxAPI] Saving image:', imageUrl);
+ const result = await this.processFileURL({
+ fileStrategy: this.fileStrategy,
+ userId: this.userId,
+ URL: imageUrl,
+ fileName: imageName,
+ basePath: 'images',
+ context: FileContext.image_generation,
+ });
+
+ logger.debug('[FluxAPI] Image saved to path:', result.filepath);
+
+ // Calculate cost based on endpoint
+ /**
+ * TODO: Cost handling
+ const endpoint = imageData.endpoint || '/v1/flux-pro';
+ const endpointKey = Object.entries(FluxAPI.PRICING).find(([key, _]) =>
+ endpoint.includes(key.toLowerCase().replace(/_/g, '-')),
+ )?.[0];
+ const cost = FluxAPI.PRICING[endpointKey] || 0;
+ */
+ this.result = this.returnMetadata ? result : this.wrapInMarkdown(result.filepath);
+ return this.returnValue(this.result);
+ } catch (error) {
+ const details = this.getDetails(error?.message ?? 'No additional error details.');
+ logger.error('Error while saving the image:', details);
+ return this.returnValue(`Failed to save the image locally. ${details}`);
+ }
+ }
+
+ async getMyFinetunes(apiKey = null) {
+ const finetunesUrl = `${this.baseUrl}/v1/my_finetunes`;
+ const detailsUrl = `${this.baseUrl}/v1/finetune_details`;
+
+ try {
+ const headers = {
+ 'x-key': apiKey || this.getApiKey(),
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ };
+
+ // Get list of finetunes
+ const response = await axios.get(finetunesUrl, {
+ headers,
+ ...this.getAxiosConfig(),
+ });
+ const finetunes = response.data.finetunes;
+
+ // Fetch details for each finetune
+ const finetuneDetails = await Promise.all(
+ finetunes.map(async (finetuneId) => {
+ try {
+ const detailResponse = await axios.get(`${detailsUrl}?finetune_id=${finetuneId}`, {
+ headers,
+ ...this.getAxiosConfig(),
+ });
+ return {
+ id: finetuneId,
+ ...detailResponse.data,
+ };
+ } catch (error) {
+ logger.error(`[FluxAPI] Error fetching details for finetune ${finetuneId}:`, error);
+ return {
+ id: finetuneId,
+ error: 'Failed to fetch details',
+ };
+ }
+ }),
+ );
+
+ if (this.isAgent) {
+ const formattedDetails = JSON.stringify(finetuneDetails, null, 2);
+ return [`Here are the available finetunes:\n${formattedDetails}`, null];
+ }
+ return JSON.stringify(finetuneDetails);
+ } catch (error) {
+ const details = this.getDetails(error?.response?.data || error.message);
+ logger.error('[FluxAPI] Error while getting finetunes:', details);
+ const errorMsg = `Failed to get finetunes: ${details}`;
+ return this.isAgent ? this.returnValue([errorMsg, {}]) : new Error(errorMsg);
+ }
+ }
+
+ async generateFinetunedImage(imageData, requestApiKey) {
+ if (!imageData.prompt) {
+ throw new Error('Missing required field: prompt');
+ }
+
+ if (!imageData.finetune_id) {
+ throw new Error(
+ 'Missing required field: finetune_id for finetuned generation. Please supply a finetune_id!',
+ );
+ }
+
+ // Validate endpoint is appropriate for finetuned generation
+ const validFinetunedEndpoints = ['/v1/flux-pro-finetuned', '/v1/flux-pro-1.1-ultra-finetuned'];
+ const endpoint = imageData.endpoint || '/v1/flux-pro-finetuned';
+
+ if (!validFinetunedEndpoints.includes(endpoint)) {
+ throw new Error(
+ `Invalid endpoint for finetuned generation. Must be one of: ${validFinetunedEndpoints.join(', ')}`,
+ );
+ }
+
+ let payload = {
+ prompt: imageData.prompt,
+ prompt_upsampling: imageData.prompt_upsampling || false,
+ safety_tolerance: imageData.safety_tolerance || 6,
+ output_format: imageData.output_format || 'png',
+ finetune_id: imageData.finetune_id,
+ finetune_strength: imageData.finetune_strength || 1.0,
+ guidance: imageData.guidance || 2.5,
+ };
+
+ // Add optional parameters if provided
+ if (imageData.width) {
+ payload.width = imageData.width;
+ }
+ if (imageData.height) {
+ payload.height = imageData.height;
+ }
+ if (imageData.steps) {
+ payload.steps = imageData.steps;
+ }
+ if (imageData.seed !== undefined) {
+ payload.seed = imageData.seed;
+ }
+ if (imageData.raw) {
+ payload.raw = imageData.raw;
+ }
+
+ const generateUrl = `${this.baseUrl}${endpoint}`;
+ const resultUrl = `${this.baseUrl}/v1/get_result`;
+
+ logger.debug('[FluxAPI] Generating finetuned image with payload:', payload);
+ logger.debug('[FluxAPI] Using endpoint:', generateUrl);
+
+ let taskResponse;
+ try {
+ taskResponse = await axios.post(generateUrl, payload, {
+ headers: {
+ 'x-key': requestApiKey,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ ...this.getAxiosConfig(),
+ });
+ } catch (error) {
+ const details = this.getDetails(error?.response?.data || error.message);
+ logger.error('[FluxAPI] Error while submitting finetuned task:', details);
+ return this.returnValue(
+ `Something went wrong when trying to generate the finetuned image. The Flux API may be unavailable:
+ Error Message: ${details}`,
+ );
+ }
+
+ const taskId = taskResponse.data.id;
+
+ // Polling for the result
+ let status = 'Pending';
+ let resultData = null;
+ while (status !== 'Ready' && status !== 'Error') {
+ try {
+ // Wait 2 seconds between polls
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ const resultResponse = await axios.get(resultUrl, {
+ headers: {
+ 'x-key': requestApiKey,
+ Accept: 'application/json',
+ },
+ params: { id: taskId },
+ ...this.getAxiosConfig(),
+ });
+ status = resultResponse.data.status;
+
+ if (status === 'Ready') {
+ resultData = resultResponse.data.result;
+ break;
+ } else if (status === 'Error') {
+ logger.error('[FluxAPI] Error in finetuned task:', resultResponse.data);
+ return this.returnValue('An error occurred during finetuned image generation.');
+ }
+ } catch (error) {
+ const details = this.getDetails(error?.response?.data || error.message);
+ logger.error('[FluxAPI] Error while getting finetuned result:', details);
+ return this.returnValue('An error occurred while retrieving the finetuned image.');
+ }
+ }
+
+ // If no result data
+ if (!resultData || !resultData.sample) {
+ logger.error('[FluxAPI] No image data received from API. Response:', resultData);
+ return this.returnValue('No image data received from Flux API.');
+ }
+
+ // Try saving the image locally
+ const imageUrl = resultData.sample;
+ const imageName = `img-${uuidv4()}.png`;
+
+ try {
+ logger.debug('[FluxAPI] Saving finetuned image:', imageUrl);
+ const result = await this.processFileURL({
+ fileStrategy: this.fileStrategy,
+ userId: this.userId,
+ URL: imageUrl,
+ fileName: imageName,
+ basePath: 'images',
+ context: FileContext.image_generation,
+ });
+
+ logger.debug('[FluxAPI] Finetuned image saved to path:', result.filepath);
+
+ // Calculate cost based on endpoint
+ const endpointKey = endpoint.includes('ultra')
+ ? 'FLUX_PRO_1_1_ULTRA_FINETUNED'
+ : 'FLUX_PRO_FINETUNED';
+ const cost = FluxAPI.PRICING[endpointKey] || 0;
+ // Return the result based on returnMetadata flag
+ this.result = this.returnMetadata ? result : this.wrapInMarkdown(result.filepath);
+ return this.returnValue(this.result);
+ } catch (error) {
+ const details = this.getDetails(error?.message ?? 'No additional error details.');
+ logger.error('Error while saving the finetuned image:', details);
+ return this.returnValue(`Failed to save the finetuned image locally. ${details}`);
+ }
+ }
+}
+
+module.exports = FluxAPI;
diff --git a/api/app/clients/tools/structured/StableDiffusion.js b/api/app/clients/tools/structured/StableDiffusion.js
index 6309da35d8..25a9e0abd3 100644
--- a/api/app/clients/tools/structured/StableDiffusion.js
+++ b/api/app/clients/tools/structured/StableDiffusion.js
@@ -6,10 +6,13 @@ const axios = require('axios');
const sharp = require('sharp');
const { v4: uuidv4 } = require('uuid');
const { Tool } = require('@langchain/core/tools');
-const { FileContext } = require('librechat-data-provider');
+const { FileContext, ContentTypes } = require('librechat-data-provider');
const paths = require('~/config/paths');
const { logger } = require('~/config');
+const displayMessage =
+ 'Stable Diffusion displayed an image. All generated images are already plainly visible, so don\'t repeat the descriptions in detail. Do not list download links as they are available in the UI already. The user may download the images by clicking on them, but do not mention anything about downloading to the user.';
+
class StableDiffusionAPI extends Tool {
constructor(fields) {
super();
@@ -21,6 +24,8 @@ class StableDiffusionAPI extends Tool {
this.override = fields.override ?? false;
/** @type {boolean} Necessary for output to contain all image metadata. */
this.returnMetadata = fields.returnMetadata ?? false;
+ /** @type {boolean} */
+ this.isAgent = fields.isAgent;
if (fields.uploadImageBuffer) {
/** @type {uploadImageBuffer} Necessary for output to contain all image metadata. */
this.uploadImageBuffer = fields.uploadImageBuffer.bind(this);
@@ -66,6 +71,16 @@ class StableDiffusionAPI extends Tool {
return ``;
}
+ returnValue(value) {
+ if (this.isAgent === true && typeof value === 'string') {
+ return [value, {}];
+ } else if (this.isAgent === true && typeof value === 'object') {
+ return [displayMessage, value];
+ }
+
+ return value;
+ }
+
getServerURL() {
const url = process.env.SD_WEBUI_URL || '';
if (!url && !this.override) {
@@ -113,6 +128,25 @@ class StableDiffusionAPI extends Tool {
}
try {
+ if (this.isAgent) {
+ const content = [
+ {
+ type: ContentTypes.IMAGE_URL,
+ image_url: {
+ url: `data:image/png;base64,${image}`,
+ },
+ },
+ ];
+
+ const response = [
+ {
+ type: ContentTypes.TEXT,
+ text: displayMessage,
+ },
+ ];
+ return [response, { content }];
+ }
+
const buffer = Buffer.from(image.split(',', 1)[0], 'base64');
if (this.returnMetadata && this.uploadImageBuffer && this.req) {
const file = await this.uploadImageBuffer({
@@ -154,7 +188,7 @@ class StableDiffusionAPI extends Tool {
logger.error('[StableDiffusion] Error while saving the image:', error);
}
- return this.result;
+ return this.returnValue(this.result);
}
}
diff --git a/api/app/clients/tools/util/fileSearch.js b/api/app/clients/tools/util/fileSearch.js
index 23ba58bb5a..54da483362 100644
--- a/api/app/clients/tools/util/fileSearch.js
+++ b/api/app/clients/tools/util/fileSearch.js
@@ -106,18 +106,21 @@ const createFileSearchTool = async ({ req, files, entity_id }) => {
const formattedResults = validResults
.flatMap((result) =>
- result.data.map(([docInfo, relevanceScore]) => ({
+ result.data.map(([docInfo, distance]) => ({
filename: docInfo.metadata.source.split('/').pop(),
content: docInfo.page_content,
- relevanceScore,
+ distance,
})),
)
- .sort((a, b) => b.relevanceScore - a.relevanceScore);
+ // TODO: results should be sorted by relevance, not distance
+ .sort((a, b) => a.distance - b.distance)
+ // TODO: make this configurable
+ .slice(0, 10);
const formattedString = formattedResults
.map(
(result) =>
- `File: ${result.filename}\nRelevance: ${result.relevanceScore.toFixed(4)}\nContent: ${
+ `File: ${result.filename}\nRelevance: ${1.0 - result.distance.toFixed(4)}\nContent: ${
result.content
}\n`,
)
diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.js
index f1dfa24a49..063d6e0327 100644
--- a/api/app/clients/tools/util/handleTools.js
+++ b/api/app/clients/tools/util/handleTools.js
@@ -10,6 +10,7 @@ const {
GoogleSearchAPI,
// Structured Tools
DALLE3,
+ FluxAPI,
OpenWeather,
StructuredSD,
StructuredACS,
@@ -20,6 +21,7 @@ const {
} = require('../');
const { primeFiles: primeCodeFiles } = require('~/server/services/Files/Code/process');
const { createFileSearchTool, primeFiles: primeSearchFiles } = require('./fileSearch');
+const { loadAuthValues } = require('~/server/services/Tools/credentials');
const { createMCPTool } = require('~/server/services/MCP');
const { loadSpecs } = require('./loadSpecs');
const { logger } = require('~/config');
@@ -89,45 +91,6 @@ const validateTools = async (user, tools = []) => {
}
};
-const loadAuthValues = async ({ userId, authFields, throwError = true }) => {
- let authValues = {};
-
- /**
- * Finds the first non-empty value for the given authentication field, supporting alternate fields.
- * @param {string[]} fields Array of strings representing the authentication fields. Supports alternate fields delimited by "||".
- * @returns {Promise<{ authField: string, authValue: string} | null>} An object containing the authentication field and value, or null if not found.
- */
- const findAuthValue = async (fields) => {
- for (const field of fields) {
- let value = process.env[field];
- if (value) {
- return { authField: field, authValue: value };
- }
- try {
- value = await getUserPluginAuthValue(userId, field, throwError);
- } catch (err) {
- if (field === fields[fields.length - 1] && !value) {
- throw err;
- }
- }
- if (value) {
- return { authField: field, authValue: value };
- }
- }
- return null;
- };
-
- for (let authField of authFields) {
- const fields = authField.split('||');
- const result = await findAuthValue(fields);
- if (result) {
- authValues[result.authField] = result.authValue;
- }
- }
-
- return authValues;
-};
-
/** @typedef {typeof import('@langchain/core/tools').Tool} ToolConstructor */
/** @typedef {import('@langchain/core/tools').Tool} Tool */
@@ -182,6 +145,7 @@ const loadTools = async ({
returnMap = false,
}) => {
const toolConstructors = {
+ flux: FluxAPI,
calculator: Calculator,
google: GoogleSearchAPI,
open_weather: OpenWeather,
@@ -230,9 +194,10 @@ const loadTools = async ({
};
const toolOptions = {
- serpapi: { location: 'Austin,Texas,United States', hl: 'en', gl: 'us' },
+ flux: imageGenOptions,
dalle: imageGenOptions,
'stable-diffusion': imageGenOptions,
+ serpapi: { location: 'Austin,Texas,United States', hl: 'en', gl: 'us' },
};
const toolContextMap = {};
@@ -345,7 +310,6 @@ const loadTools = async ({
module.exports = {
loadToolWithAuth,
- loadAuthValues,
validateTools,
loadTools,
};
diff --git a/api/app/clients/tools/util/index.js b/api/app/clients/tools/util/index.js
index 73d10270b6..ea67bb4ced 100644
--- a/api/app/clients/tools/util/index.js
+++ b/api/app/clients/tools/util/index.js
@@ -1,9 +1,8 @@
-const { validateTools, loadTools, loadAuthValues } = require('./handleTools');
+const { validateTools, loadTools } = require('./handleTools');
const handleOpenAIErrors = require('./handleOpenAIErrors');
module.exports = {
handleOpenAIErrors,
- loadAuthValues,
validateTools,
loadTools,
};
diff --git a/api/cache/keyvRedis.js b/api/cache/keyvRedis.js
index d544b50a11..992e789ae3 100644
--- a/api/cache/keyvRedis.js
+++ b/api/cache/keyvRedis.js
@@ -1,20 +1,86 @@
+const fs = require('fs');
+const ioredis = require('ioredis');
const KeyvRedis = require('@keyv/redis');
const { isEnabled } = require('~/server/utils');
const logger = require('~/config/winston');
-const { REDIS_URI, USE_REDIS } = process.env;
+const { REDIS_URI, USE_REDIS, USE_REDIS_CLUSTER, REDIS_CA, REDIS_KEY_PREFIX, REDIS_MAX_LISTENERS } =
+ process.env;
let keyvRedis;
+const redis_prefix = REDIS_KEY_PREFIX || '';
+const redis_max_listeners = Number(REDIS_MAX_LISTENERS) || 40;
+
+function mapURI(uri) {
+ const regex =
+ /^(?:(?\w+):\/\/)?(?:(?[^:@]+)(?::(?[^@]+))?@)?(?[\w.-]+)(?::(?\d{1,5}))?$/;
+ const match = uri.match(regex);
+
+ if (match) {
+ const { scheme, user, password, host, port } = match.groups;
+
+ return {
+ scheme: scheme || 'none',
+ user: user || null,
+ password: password || null,
+ host: host || null,
+ port: port || null,
+ };
+ } else {
+ const parts = uri.split(':');
+ if (parts.length === 2) {
+ return {
+ scheme: 'none',
+ user: null,
+ password: null,
+ host: parts[0],
+ port: parts[1],
+ };
+ }
+
+ return {
+ scheme: 'none',
+ user: null,
+ password: null,
+ host: uri,
+ port: null,
+ };
+ }
+}
if (REDIS_URI && isEnabled(USE_REDIS)) {
- keyvRedis = new KeyvRedis(REDIS_URI, { useRedisSets: false });
+ let redisOptions = null;
+ let keyvOpts = {
+ useRedisSets: false,
+ keyPrefix: redis_prefix,
+ };
+
+ if (REDIS_CA) {
+ const ca = fs.readFileSync(REDIS_CA);
+ redisOptions = { tls: { ca } };
+ }
+
+ if (isEnabled(USE_REDIS_CLUSTER)) {
+ const hosts = REDIS_URI.split(',').map((item) => {
+ var value = mapURI(item);
+
+ return {
+ host: value.host,
+ port: value.port,
+ };
+ });
+ const cluster = new ioredis.Cluster(hosts, { redisOptions });
+ keyvRedis = new KeyvRedis(cluster, keyvOpts);
+ } else {
+ keyvRedis = new KeyvRedis(REDIS_URI, keyvOpts);
+ }
keyvRedis.on('error', (err) => logger.error('KeyvRedis connection error:', err));
- keyvRedis.setMaxListeners(20);
+ keyvRedis.setMaxListeners(redis_max_listeners);
logger.info(
- '[Optional] Redis initialized. Note: Redis support is experimental. If you have issues, disable it. Cache needs to be flushed for values to refresh.',
+ '[Optional] Redis initialized. If you have issues, or seeing older values, disable it or flush cache to refresh values.',
);
} else {
- logger.info('[Optional] Redis not initialized. Note: Redis support is experimental.');
+ logger.info('[Optional] Redis not initialized.');
}
module.exports = keyvRedis;
diff --git a/api/config/index.js b/api/config/index.js
index aaf8bb2764..8f23e404c8 100644
--- a/api/config/index.js
+++ b/api/config/index.js
@@ -1,3 +1,4 @@
+const axios = require('axios');
const { EventSource } = require('eventsource');
const { Time, CacheKeys } = require('librechat-data-provider');
const logger = require('./winston');
@@ -47,9 +48,46 @@ const sendEvent = (res, event) => {
res.write(`event: message\ndata: ${JSON.stringify(event)}\n\n`);
};
+/**
+ * Creates and configures an Axios instance with optional proxy settings.
+ *
+ * @typedef {import('axios').AxiosInstance} AxiosInstance
+ * @typedef {import('axios').AxiosProxyConfig} AxiosProxyConfig
+ *
+ * @returns {AxiosInstance} A configured Axios instance
+ * @throws {Error} If there's an issue creating the Axios instance or parsing the proxy URL
+ */
+function createAxiosInstance() {
+ const instance = axios.create();
+
+ if (process.env.proxy) {
+ try {
+ const url = new URL(process.env.proxy);
+
+ /** @type {AxiosProxyConfig} */
+ const proxyConfig = {
+ host: url.hostname.replace(/^\[|\]$/g, ''),
+ protocol: url.protocol.replace(':', ''),
+ };
+
+ if (url.port) {
+ proxyConfig.port = parseInt(url.port, 10);
+ }
+
+ instance.defaults.proxy = proxyConfig;
+ } catch (error) {
+ console.error('Error parsing proxy URL:', error);
+ throw new Error(`Invalid proxy URL: ${process.env.proxy}`);
+ }
+ }
+
+ return instance;
+}
+
module.exports = {
logger,
sendEvent,
getMCPManager,
+ createAxiosInstance,
getFlowStateManager,
};
diff --git a/api/config/index.spec.js b/api/config/index.spec.js
new file mode 100644
index 0000000000..36ed8302f3
--- /dev/null
+++ b/api/config/index.spec.js
@@ -0,0 +1,126 @@
+const axios = require('axios');
+const { createAxiosInstance } = require('./index');
+
+// Mock axios
+jest.mock('axios', () => ({
+ interceptors: {
+ request: { use: jest.fn(), eject: jest.fn() },
+ response: { use: jest.fn(), eject: jest.fn() },
+ },
+ create: jest.fn().mockReturnValue({
+ defaults: {
+ proxy: null,
+ },
+ get: jest.fn().mockResolvedValue({ data: {} }),
+ post: jest.fn().mockResolvedValue({ data: {} }),
+ put: jest.fn().mockResolvedValue({ data: {} }),
+ delete: jest.fn().mockResolvedValue({ data: {} }),
+ }),
+ get: jest.fn().mockResolvedValue({ data: {} }),
+ post: jest.fn().mockResolvedValue({ data: {} }),
+ put: jest.fn().mockResolvedValue({ data: {} }),
+ delete: jest.fn().mockResolvedValue({ data: {} }),
+ reset: jest.fn().mockImplementation(function () {
+ this.get.mockClear();
+ this.post.mockClear();
+ this.put.mockClear();
+ this.delete.mockClear();
+ this.create.mockClear();
+ }),
+}));
+
+describe('createAxiosInstance', () => {
+ const originalEnv = process.env;
+
+ beforeEach(() => {
+ // Reset mocks
+ jest.clearAllMocks();
+ // Create a clean copy of process.env
+ process.env = { ...originalEnv };
+ // Default: no proxy
+ delete process.env.proxy;
+ });
+
+ afterAll(() => {
+ // Restore original process.env
+ process.env = originalEnv;
+ });
+
+ test('creates an axios instance without proxy when no proxy env is set', () => {
+ const instance = createAxiosInstance();
+
+ expect(axios.create).toHaveBeenCalledTimes(1);
+ expect(instance.defaults.proxy).toBeNull();
+ });
+
+ test('configures proxy correctly with hostname and protocol', () => {
+ process.env.proxy = 'http://example.com';
+
+ const instance = createAxiosInstance();
+
+ expect(axios.create).toHaveBeenCalledTimes(1);
+ expect(instance.defaults.proxy).toEqual({
+ host: 'example.com',
+ protocol: 'http',
+ });
+ });
+
+ test('configures proxy correctly with hostname, protocol and port', () => {
+ process.env.proxy = 'https://proxy.example.com:8080';
+
+ const instance = createAxiosInstance();
+
+ expect(axios.create).toHaveBeenCalledTimes(1);
+ expect(instance.defaults.proxy).toEqual({
+ host: 'proxy.example.com',
+ protocol: 'https',
+ port: 8080,
+ });
+ });
+
+ test('handles proxy URLs with authentication', () => {
+ process.env.proxy = 'http://user:pass@proxy.example.com:3128';
+
+ const instance = createAxiosInstance();
+
+ expect(axios.create).toHaveBeenCalledTimes(1);
+ expect(instance.defaults.proxy).toEqual({
+ host: 'proxy.example.com',
+ protocol: 'http',
+ port: 3128,
+ // Note: The current implementation doesn't handle auth - if needed, add this functionality
+ });
+ });
+
+ test('throws error when proxy URL is invalid', () => {
+ process.env.proxy = 'invalid-url';
+
+ expect(() => createAxiosInstance()).toThrow('Invalid proxy URL');
+ expect(axios.create).toHaveBeenCalledTimes(1);
+ });
+
+ // If you want to test the actual URL parsing more thoroughly
+ test('handles edge case proxy URLs correctly', () => {
+ // IPv6 address
+ process.env.proxy = 'http://[::1]:8080';
+
+ let instance = createAxiosInstance();
+
+ expect(instance.defaults.proxy).toEqual({
+ host: '::1',
+ protocol: 'http',
+ port: 8080,
+ });
+
+ // URL with path (which should be ignored for proxy config)
+ process.env.proxy = 'http://proxy.example.com:8080/some/path';
+
+ instance = createAxiosInstance();
+
+ expect(instance.defaults.proxy).toEqual({
+ host: 'proxy.example.com',
+ protocol: 'http',
+ port: 8080,
+ });
+ });
+});
diff --git a/api/lib/db/indexSync.js b/api/lib/db/indexSync.js
index 86c909419d..75acd9d231 100644
--- a/api/lib/db/indexSync.js
+++ b/api/lib/db/indexSync.js
@@ -1,9 +1,11 @@
const { MeiliSearch } = require('meilisearch');
-const Conversation = require('~/models/schema/convoSchema');
-const Message = require('~/models/schema/messageSchema');
+const { Conversation } = require('~/models/Conversation');
+const { Message } = require('~/models/Message');
+const { isEnabled } = require('~/server/utils');
const { logger } = require('~/config');
-const searchEnabled = process.env?.SEARCH?.toLowerCase() === 'true';
+const searchEnabled = isEnabled(process.env.SEARCH);
+const indexingDisabled = isEnabled(process.env.MEILI_NO_SYNC);
let currentTimeout = null;
class MeiliSearchClient {
@@ -23,8 +25,7 @@ class MeiliSearchClient {
}
}
-// eslint-disable-next-line no-unused-vars
-async function indexSync(req, res, next) {
+async function indexSync() {
if (!searchEnabled) {
return;
}
@@ -33,10 +34,15 @@ async function indexSync(req, res, next) {
const client = MeiliSearchClient.getInstance();
const { status } = await client.health();
- if (status !== 'available' || !process.env.SEARCH) {
+ if (status !== 'available') {
throw new Error('Meilisearch not available');
}
+ if (indexingDisabled === true) {
+ logger.info('[indexSync] Indexing is disabled, skipping...');
+ return;
+ }
+
const messageCount = await Message.countDocuments();
const convoCount = await Conversation.countDocuments();
const messages = await client.index('messages').getStats();
@@ -71,7 +77,6 @@ async function indexSync(req, res, next) {
logger.info('[indexSync] Meilisearch not configured, search will be disabled.');
} else {
logger.error('[indexSync] error', err);
- // res.status(500).json({ error: 'Server error' });
}
}
}
diff --git a/api/models/Action.js b/api/models/Action.js
index 299b3bf20a..677b4d78df 100644
--- a/api/models/Action.js
+++ b/api/models/Action.js
@@ -1,5 +1,5 @@
const mongoose = require('mongoose');
-const actionSchema = require('./schema/action');
+const { actionSchema } = require('@librechat/data-schemas');
const Action = mongoose.model('action', actionSchema);
diff --git a/api/models/Agent.js b/api/models/Agent.js
index 6fa00f56bc..1d3ea5af0c 100644
--- a/api/models/Agent.js
+++ b/api/models/Agent.js
@@ -9,7 +9,7 @@ const {
removeAgentFromAllProjects,
} = require('./Project');
const getLogStores = require('~/cache/getLogStores');
-const agentSchema = require('./schema/agent');
+const { agentSchema } = require('@librechat/data-schemas');
const Agent = mongoose.model('agent', agentSchema);
@@ -97,11 +97,22 @@ const updateAgent = async (searchParameter, updateData) => {
const addAgentResourceFile = async ({ agent_id, tool_resource, file_id }) => {
const searchParameter = { id: agent_id };
- // build the update to push or create the file ids set
const fileIdsPath = `tool_resources.${tool_resource}.file_ids`;
+
+ await Agent.updateOne(
+ {
+ id: agent_id,
+ [`${fileIdsPath}`]: { $exists: false },
+ },
+ {
+ $set: {
+ [`${fileIdsPath}`]: [],
+ },
+ },
+ );
+
const updateData = { $addToSet: { [fileIdsPath]: file_id } };
- // return the updated agent or throw if no agent matches
const updatedAgent = await updateAgent(searchParameter, updateData);
if (updatedAgent) {
return updatedAgent;
@@ -290,6 +301,7 @@ const updateAgentProjects = async ({ user, agentId, projectIds, removeProjectIds
};
module.exports = {
+ Agent,
getAgent,
loadAgent,
createAgent,
diff --git a/api/models/Agent.spec.js b/api/models/Agent.spec.js
new file mode 100644
index 0000000000..769eda2bb7
--- /dev/null
+++ b/api/models/Agent.spec.js
@@ -0,0 +1,160 @@
+const mongoose = require('mongoose');
+const { v4: uuidv4 } = require('uuid');
+const { MongoMemoryServer } = require('mongodb-memory-server');
+const { Agent, addAgentResourceFile, removeAgentResourceFiles } = require('./Agent');
+
+describe('Agent Resource File Operations', () => {
+ let mongoServer;
+
+ beforeAll(async () => {
+ mongoServer = await MongoMemoryServer.create();
+ const mongoUri = mongoServer.getUri();
+ await mongoose.connect(mongoUri);
+ });
+
+ afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer.stop();
+ });
+
+ beforeEach(async () => {
+ await Agent.deleteMany({});
+ });
+
+ const createBasicAgent = async () => {
+ const agentId = `agent_${uuidv4()}`;
+ const agent = await Agent.create({
+ id: agentId,
+ name: 'Test Agent',
+ provider: 'test',
+ model: 'test-model',
+ author: new mongoose.Types.ObjectId(),
+ });
+ return agent;
+ };
+
+ test('should handle concurrent file additions', async () => {
+ const agent = await createBasicAgent();
+ const fileIds = Array.from({ length: 10 }, () => uuidv4());
+
+ // Concurrent additions
+ const additionPromises = fileIds.map((fileId) =>
+ addAgentResourceFile({
+ agent_id: agent.id,
+ tool_resource: 'test_tool',
+ file_id: fileId,
+ }),
+ );
+
+ await Promise.all(additionPromises);
+
+ const updatedAgent = await Agent.findOne({ id: agent.id });
+ expect(updatedAgent.tool_resources.test_tool.file_ids).toBeDefined();
+ expect(updatedAgent.tool_resources.test_tool.file_ids).toHaveLength(10);
+ expect(new Set(updatedAgent.tool_resources.test_tool.file_ids).size).toBe(10);
+ });
+
+ test('should handle concurrent additions and removals', async () => {
+ const agent = await createBasicAgent();
+ const initialFileIds = Array.from({ length: 5 }, () => uuidv4());
+
+ await Promise.all(
+ initialFileIds.map((fileId) =>
+ addAgentResourceFile({
+ agent_id: agent.id,
+ tool_resource: 'test_tool',
+ file_id: fileId,
+ }),
+ ),
+ );
+
+ const newFileIds = Array.from({ length: 5 }, () => uuidv4());
+ const operations = [
+ ...newFileIds.map((fileId) =>
+ addAgentResourceFile({
+ agent_id: agent.id,
+ tool_resource: 'test_tool',
+ file_id: fileId,
+ }),
+ ),
+ ...initialFileIds.map((fileId) =>
+ removeAgentResourceFiles({
+ agent_id: agent.id,
+ files: [{ tool_resource: 'test_tool', file_id: fileId }],
+ }),
+ ),
+ ];
+
+ await Promise.all(operations);
+
+ const updatedAgent = await Agent.findOne({ id: agent.id });
+ expect(updatedAgent.tool_resources.test_tool.file_ids).toBeDefined();
+ expect(updatedAgent.tool_resources.test_tool.file_ids).toHaveLength(5);
+ });
+
+ test('should initialize array when adding to non-existent tool resource', async () => {
+ const agent = await createBasicAgent();
+ const fileId = uuidv4();
+
+ const updatedAgent = await addAgentResourceFile({
+ agent_id: agent.id,
+ tool_resource: 'new_tool',
+ file_id: fileId,
+ });
+
+ expect(updatedAgent.tool_resources.new_tool.file_ids).toBeDefined();
+ expect(updatedAgent.tool_resources.new_tool.file_ids).toHaveLength(1);
+ expect(updatedAgent.tool_resources.new_tool.file_ids[0]).toBe(fileId);
+ });
+
+ test('should handle rapid sequential modifications to same tool resource', async () => {
+ const agent = await createBasicAgent();
+ const fileId = uuidv4();
+
+ for (let i = 0; i < 10; i++) {
+ await addAgentResourceFile({
+ agent_id: agent.id,
+ tool_resource: 'test_tool',
+ file_id: `${fileId}_${i}`,
+ });
+
+ if (i % 2 === 0) {
+ await removeAgentResourceFiles({
+ agent_id: agent.id,
+ files: [{ tool_resource: 'test_tool', file_id: `${fileId}_${i}` }],
+ });
+ }
+ }
+
+ const updatedAgent = await Agent.findOne({ id: agent.id });
+ expect(updatedAgent.tool_resources.test_tool.file_ids).toBeDefined();
+ expect(Array.isArray(updatedAgent.tool_resources.test_tool.file_ids)).toBe(true);
+ });
+
+ test('should handle multiple tool resources concurrently', async () => {
+ const agent = await createBasicAgent();
+ const toolResources = ['tool1', 'tool2', 'tool3'];
+ const operations = [];
+
+ toolResources.forEach((tool) => {
+ const fileIds = Array.from({ length: 5 }, () => uuidv4());
+ fileIds.forEach((fileId) => {
+ operations.push(
+ addAgentResourceFile({
+ agent_id: agent.id,
+ tool_resource: tool,
+ file_id: fileId,
+ }),
+ );
+ });
+ });
+
+ await Promise.all(operations);
+
+ const updatedAgent = await Agent.findOne({ id: agent.id });
+ toolResources.forEach((tool) => {
+ expect(updatedAgent.tool_resources[tool].file_ids).toBeDefined();
+ expect(updatedAgent.tool_resources[tool].file_ids).toHaveLength(5);
+ });
+ });
+});
diff --git a/api/models/Assistant.js b/api/models/Assistant.js
index d0e73ad4e7..a8a5b98157 100644
--- a/api/models/Assistant.js
+++ b/api/models/Assistant.js
@@ -1,5 +1,5 @@
const mongoose = require('mongoose');
-const assistantSchema = require('./schema/assistant');
+const { assistantSchema } = require('@librechat/data-schemas');
const Assistant = mongoose.model('assistant', assistantSchema);
diff --git a/api/models/Balance.js b/api/models/Balance.js
index 24d9087b77..f7978d8049 100644
--- a/api/models/Balance.js
+++ b/api/models/Balance.js
@@ -1,5 +1,5 @@
const mongoose = require('mongoose');
-const balanceSchema = require('./schema/balance');
+const { balanceSchema } = require('@librechat/data-schemas');
const { getMultiplier } = require('./tx');
const { logger } = require('~/config');
diff --git a/api/models/Banner.js b/api/models/Banner.js
index 8d439dae28..399a8e72ee 100644
--- a/api/models/Banner.js
+++ b/api/models/Banner.js
@@ -1,5 +1,9 @@
-const Banner = require('./schema/banner');
+const mongoose = require('mongoose');
const logger = require('~/config/winston');
+const { bannerSchema } = require('@librechat/data-schemas');
+
+const Banner = mongoose.model('Banner', bannerSchema);
+
/**
* Retrieves the current active banner.
* @returns {Promise