Skip to content

feat: add AIMLAPI (aimlapi.com) as a model provider - #17311

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
aimlapi:feat/aimlapi-provider-pr
Jul 24, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
aimlapi:feat/aimlapi-provider-pr

Conversation

@eugeneBackDev

@eugeneBackDev eugeneBackDev commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR adds aimlapi.com as a model provider, so a RAGFlow user can enter one API key in the model settings and use AIMLAPI's models across the app. AIMLAPI (aimlapi.com) is an OpenAI-compatible aggregator that serves 700+ models (LLM, embedding, vision, TTS, ASR) from many providers behind a single API.

The change mirrors the repo's existing "add provider" pattern (e.g. FuturMix / OpenRouter): provider logic lives in the same files those providers use, and shared / UI files get only registration entries.

Backend

  • conf/llm_factories.json — the aimlapi.com factory entry.
  • rag/llm/__init__.py, rag/llm/{chat,embedding,cv}_model.py — LiteLLM adapters (chat, embedding, image2text) with a production base URL, overridable via AIMLAPI_API_URL.
  • rag/llm/model_meta.py — an AIMLAPI model-meta so the provider lists its full /v1/models catalog dynamically (classified by the endpoint type), the same way OpenRouter does.
  • api/apps/restful_apis/aimlapi_api.py — an optional "Get API key" flow using AIMLAPI's agent-authorization (OAuth 2.0 Device Authorization Grant, RFC 8628). The device code is kept server-side (Redis); only the issued key reaches the browser.

Frontend (web/)

  • Provider registration (constant, icon allowlist, brand logo), the model picker (LIST_MODEL_PROVIDERS + a buildLocalConfig entry), and the "Get API key" button in the provider dialog. Locales added to en and zh.

Configuration — production defaults are compiled in; endpoints and the partner id are overridable through AIMLAPI_* environment variables, so the same build works across environments.

Testing — the web build passes; chat, embedding and dynamic model listing were smoke-tested against the live API.

Register aimlapi.com in the provider catalog (conf/llm_factories.json) with
OpenAI-compatible LiteLLM adapters (chat, embedding, image2text), dynamic
/v1/models listing (rag/llm/model_meta.py AIMLAPI, classified by endpoint
type), and the AIMLAPI agent-authorization endpoints (OAuth 2.0 device grant,
api/apps/restful_apis/aimlapi_api.py). Production defaults; base_url and
partner id are env-overridable (AIMLAPI_API_URL / AIMLAPI_PARTNER_ID).
… API key)

Register aimlapi.com in the provider settings: constants + svg-icon allowlist,
LIST_MODEL_PROVIDERS + a buildLocalConfig entry so the dynamic /v1/models
picker shows the full catalog, and a data-driven logo. Add the OAuth
device-grant "Get API key" button (owned hook + component) wired into the
draft provider card, plus the authorize endpoints. Recommended badge +
aimlapi-first ordering on the Available models list. Require at least one
selected model before saving a list-model provider. i18n en + zh.
The provider logo is data-driven via LlmIcon (renders the SVG as an <img>),
so the near-black placeholder mark was invisible on the dark provider cards
and fell back to the generic icon. Ship the brand logo SVG (black badge +
white hexagon/pulse mark) that reads on both light and dark backgrounds.
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ef1cda26-6553-4c78-bec6-88b28d3de004

📥 Commits

Reviewing files that changed from the base of the PR and between 8ec5101 and 666037c.

📒 Files selected for processing (4)
  • api/apps/restful_apis/aimlapi_api.py
  • conf/llm_factories.json
  • web/src/hooks/use-aimlapi-authorize.ts
  • web/src/pages/user-setting/setting-model/instance-card/aimlapi-get-key-button.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
  • conf/llm_factories.json
  • web/src/pages/user-setting/setting-model/instance-card/aimlapi-get-key-button.tsx
  • api/apps/restful_apis/aimlapi_api.py

📝 Walkthrough

Walkthrough

Adds AIMLAPI as a supported provider, including model metadata, LiteLLM wrappers, OAuth device authorization, Redis-backed polling, frontend key acquisition, provider configuration, UI presentation, and documentation.

Changes

AIMLAPI provider integration

Layer / File(s) Summary
Device authorization backend
api/apps/restful_apis/aimlapi_api.py
Adds authenticated start and poll endpoints that call AIMLAPI, persist device authorization data in Redis, enforce user ownership, and return authorization status or API keys.
Provider runtime and model catalog
rag/llm/*, conf/llm_factories.json, docs/guides/models/supported_models.mdx
Registers AIMLAPI defaults and wrappers for chat, vision, and embeddings, formats its model catalog, and documents the provider and initial models.
Authorization hook and key entry
web/src/hooks/use-aimlapi-authorize.ts, web/src/services/llm-service.ts, web/src/utils/api.ts, web/src/pages/user-setting/.../aimlapi-get-key-button.tsx, web/src/locales/*
Connects frontend endpoints to popup-based device authorization, polling, status handling, API-key injection, and translated messages.
Provider settings and model selection
web/src/constants/llm.ts, web/src/components/svg-icon.tsx, web/src/pages/user-setting/..., web/src/utils/common-util.ts
Adds AIMLAPI identifiers, icon and key URL mappings, prioritized ordering, list-model configuration, selection validation, responsive presentation, and a recommended badge.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant AimlapiGetKeyButton
  participant useAimlapiAuthorize
  participant RAGFlowAPI
  participant AIMLAPI
  participant Redis

  User->>AimlapiGetKeyButton: Start authorization
  AimlapiGetKeyButton->>useAimlapiAuthorize: start()
  useAimlapiAuthorize->>RAGFlowAPI: POST authorization start
  RAGFlowAPI->>AIMLAPI: Create device authorization
  RAGFlowAPI->>Redis: Store device code and user ID
  RAGFlowAPI-->>useAimlapiAuthorize: request ID and verification URI
  useAimlapiAuthorize->>AIMLAPI: User completes consent in popup
  useAimlapiAuthorize->>RAGFlowAPI: Poll authorization status
  RAGFlowAPI->>Redis: Load device authorization
  RAGFlowAPI->>AIMLAPI: Exchange device code
  RAGFlowAPI-->>useAimlapiAuthorize: API key or status
  useAimlapiAuthorize-->>AimlapiGetKeyButton: Update status and key
Loading

Poem

A rabbit hops through models bright,
And opens keys by moonlit light.
Redis guards the waiting code,
While AIMLAPI shares the road.
“Ready!” twitches whiskers three—
New provider joy for you and me.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding AIMLAPI as a model provider.
Description check ✅ Passed The description matches the required Summary template and provides enough background and implementation context.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Checkov (3.3.8)
conf/llm_factories.json

Traceback (most recent call last):
File "/usr/local/bin/checkov", line 2, in
from checkov.main import Checkov
ModuleNotFoundError: No module named 'checkov'


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@eugeneBackDev
eugeneBackDev marked this pull request as ready for review July 23, 2026 12:10
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. 🧰 typescript Pull requests that update Typescript code labels Jul 23, 2026
Comment thread api/apps/restful_apis/aimlapi_api.py Outdated
@@ -0,0 +1,192 @@
#
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copyright 2026

@JinHai-CN

Copy link
Copy Markdown
Member

RAGFlow is shifting to a Go-first architecture. New features and long-term maintenance will focus on the Go version.

Sould you consider contributing the same provider to the Go codebase, as well?

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
api/apps/restful_apis/aimlapi_api.py (1)

96-141: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging for the success paths of this new flow.

Only failure paths are logged (LOGGER.warning on non-2xx responses). Per repo conventions for new flows, consider adding LOGGER.info on successful authorize-start (with request_id, no PII) and on poll-ready, to aid observability/debugging of this new OAuth device-grant flow in production.

As per path instructions, "**/*.py: Add logging for new flows."

Also applies to: 177-192

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/restful_apis/aimlapi_api.py` around lines 96 - 141, Add LOGGER.info
success logs to the new OAuth device-grant flow: log authorize-start completion
after validating and storing the request in the authorization-start handler,
including request_id only and no PII. Also log when the polling handler reaches
the ready/success state, using the existing request identifier where available.
Keep existing failure logging unchanged.

Source: Path instructions

web/src/pages/user-setting/setting-model/instance-card/aimlapi-get-key-button.tsx (2)

11-17: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the top-level constant to PascalCase.

STATUS_TEXT_KEY should use PascalCase, e.g. AimlapiStatusTextKey.

As per coding guidelines: “Use PascalCase for React component names and top-level constants.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@web/src/pages/user-setting/setting-model/instance-card/aimlapi-get-key-button.tsx`
around lines 11 - 17, Rename the top-level constant STATUS_TEXT_KEY to
AimlapiStatusTextKey and update every reference to it, preserving its type and
status-to-text mappings.

Source: Coding guidelines


2-2: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use useTranslation directly.

Replace the project wrapper with useTranslation('setting').

Proposed fix
-import { useTranslate } from '`@/hooks/common-hooks`';
+import { useTranslation } from 'react-i18next';
@@
-  const { t } = useTranslate('setting');
+  const { t } = useTranslation('setting');

As per coding guidelines: “Prefer useTranslation from react-i18next over project-wrapped utilities such as useTranslate.”

Also applies to: 27-27

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@web/src/pages/user-setting/setting-model/instance-card/aimlapi-get-key-button.tsx`
at line 2, Replace the useTranslate wrapper import and usage in the aimlapi key
button component with useTranslation from react-i18next, passing the 'setting'
namespace. Update all affected translation calls, including the second
referenced usage, while preserving their existing keys and behavior.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/apps/restful_apis/aimlapi_api.py`:
- Around line 83-95: Update the request-body handling around get_request_json so
only dictionary bodies are accepted before reading return_url, avoiding
attribute errors for arrays or other JSON types. Validate the client-provided
return_url in this flow and use it only when it matches the trusted verification
destination; otherwise fall back to _verification_base_url() before assigning
payload["returnUrl"].

In `@conf/llm_factories.json`:
- Around line 11-24: Consolidate the duplicate aimlapi.com entry for
openai/gpt-4o into one record using the file’s array-based model_type
convention, including both chat and image2text capabilities, and remove the
redundant image2text-only record. Update openai/gpt-4o-mini’s model_type to an
array that matches its existing IMAGE2TEXT tag while retaining chat support.

In `@web/src/hooks/use-aimlapi-authorize.ts`:
- Around line 134-149: Validate that both requestId and verificationUri are
present immediately after destructuring the start response in
useAimlapiAuthorize, before assigning refs, navigating the popup, or entering
the awaiting_consent flow. Treat a missing value as an invalid response and
follow the hook’s existing error-handling path instead of continuing with an
undefined request ID.

---

Nitpick comments:
In `@api/apps/restful_apis/aimlapi_api.py`:
- Around line 96-141: Add LOGGER.info success logs to the new OAuth device-grant
flow: log authorize-start completion after validating and storing the request in
the authorization-start handler, including request_id only and no PII. Also log
when the polling handler reaches the ready/success state, using the existing
request identifier where available. Keep existing failure logging unchanged.

In
`@web/src/pages/user-setting/setting-model/instance-card/aimlapi-get-key-button.tsx`:
- Around line 11-17: Rename the top-level constant STATUS_TEXT_KEY to
AimlapiStatusTextKey and update every reference to it, preserving its type and
status-to-text mappings.
- Line 2: Replace the useTranslate wrapper import and usage in the aimlapi key
button component with useTranslation from react-i18next, passing the 'setting'
namespace. Update all affected translation calls, including the second
referenced usage, while preserving their existing keys and behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 34bbb7d9-17de-46c7-abc4-ff273119dc5c

📥 Commits

Reviewing files that changed from the base of the PR and between d12fd3b and 8ec5101.

⛔ Files ignored due to path filters (1)
  • web/src/assets/svg/llm/aimlapi.svg is excluded by !**/*.svg
📒 Files selected for processing (22)
  • api/apps/restful_apis/aimlapi_api.py
  • conf/llm_factories.json
  • docs/guides/models/supported_models.mdx
  • rag/llm/__init__.py
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • rag/llm/embedding_model.py
  • rag/llm/model_meta.py
  • web/src/components/svg-icon.tsx
  • web/src/constants/llm.ts
  • web/src/hooks/use-aimlapi-authorize.ts
  • web/src/locales/en.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/setting-model/instance-card/aimlapi-get-key-button.tsx
  • web/src/pages/user-setting/setting-model/instance-card/available-models.tsx
  • web/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsx
  • web/src/pages/user-setting/setting-model/provider-schema/constants.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/local-llm-configs.ts
  • web/src/services/llm-service.ts
  • web/src/utils/api.ts
  • web/src/utils/common-util.ts

Comment thread api/apps/restful_apis/aimlapi_api.py Resolved
Comment thread conf/llm_factories.json Resolved
Comment thread web/src/hooks/use-aimlapi-authorize.ts Resolved
@eugeneBackDev

Copy link
Copy Markdown
Contributor Author

RAGFlow is shifting to a Go-first architecture. New features and long-term maintenance will focus on the Go version.

Sould you consider contributing the same provider to the Go codebase, as well?

Okay, we can look at adding this to the Go version in a
separate PR. Could this one be merged in the meantime?

Backend:
- llm_factories: collapse the duplicate openai/gpt-4o rows into a single
  entry with an array model_type (["chat","image2text"]) and tag
  gpt-4o-mini for vision too, matching the file's dual-capability
  convention (the duplicate rows collide on merge-by-name at seed load).
- authorize/start: stop forwarding a client-supplied return_url to AIMLAPI
  (open-redirect surface) and drop the non-dict body access; always use
  the trusted verification host. The flow never depends on the
  post-consent redirect — the key arrives via authenticated polling and
  the popup is closed on success.
- log authorize-start success and poll-ready (request_id only, no PII).
- bump the new file's copyright header to 2026.

Frontend:
- use-aimlapi-authorize: drop the now-unused return_url argument and guard
  a malformed start response (missing request_id / verification_uri)
  instead of polling with an undefined id.
- aimlapi-get-key-button: use useTranslation('translation', { keyPrefix })
  directly and rename the top-level constant to PascalCase, per the
  frontend conventions.
@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 24, 2026
@codecov

codecov Bot commented Jul 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (8af2467) to head (666037c).
⚠️ Report is 64 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17311   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit 6b11f62 into infiniflow:main Jul 24, 2026
8 of 12 checks passed
yingfeng pushed a commit that referenced this pull request Jul 28, 2026
…17491)

### Summary

The **aimlapi.com** provider added in #17311 does not identify itself on
any of its outgoing requests, so its traffic cannot be attributed to the
integration. This PR adds the two headers AIMLAPI expects —
`X-AIMLAPI-Source` and `X-AIMLAPI-Partner-ID` — to every request the
provider makes.
buua436 pushed a commit to buua436/ragflow that referenced this pull request Jul 29, 2026
…nfiniflow#17491)

### Summary

The **aimlapi.com** provider added in infiniflow#17311 does not identify itself on
any of its outgoing requests, so its traffic cannot be attributed to the
integration. This PR adds the two headers AIMLAPI expects —
`X-AIMLAPI-Source` and `X-AIMLAPI-Partner-ID` — to every request the
provider makes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:XL This PR changes 500-999 lines, ignoring generated files. 🧰 typescript Pull requests that update Typescript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants