-
-
Notifications
You must be signed in to change notification settings - Fork 24.5k
Add Baidu Qianfan rerank retriever #6439
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jimmyzhuu
wants to merge
5
commits into
FlowiseAI:main
Choose a base branch
from
jimmyzhuu:feature/baidu-qianfan-rerank-retriever
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+586
−0
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
7315e70
feat(components): add Baidu Qianfan rerank compressor
jimmyzhuu 3f39e84
feat(components): add Baidu Qianfan rerank retriever node
jimmyzhuu 2b4752e
feat(components): register Baidu Qianfan rerank assets
jimmyzhuu d52527f
fix(components): use Qianfan bearer rerank API
jimmyzhuu 84891fc
fix(components): validate Qianfan rerank inputs
jimmyzhuu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
23 changes: 23 additions & 0 deletions
23
packages/components/credentials/BaiduQianfanApiKey.credential.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { INodeParams, INodeCredential } from '../src/Interface' | ||
|
|
||
| class BaiduQianfanApiKey implements INodeCredential { | ||
| label: string | ||
| name: string | ||
| version: number | ||
| inputs: INodeParams[] | ||
|
|
||
| constructor() { | ||
| this.label = 'Baidu Qianfan API Key' | ||
| this.name = 'baiduQianfanApiKey' | ||
| this.version = 1.0 | ||
| this.inputs = [ | ||
| { | ||
| label: 'Qianfan API Key', | ||
| name: 'qianfanApiKey', | ||
| type: 'password' | ||
| } | ||
| ] | ||
| } | ||
| } | ||
|
|
||
| module.exports = { credClass: BaiduQianfanApiKey } |
96 changes: 96 additions & 0 deletions
96
packages/components/nodes/retrievers/BaiduQianfanRerankRetriever/BaiduQianfanRerank.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import { Document } from '@langchain/core/documents' | ||
| import { BaiduQianfanRerank } from './BaiduQianfanRerank' | ||
|
|
||
| const originalFetch = global.fetch | ||
| const mockedFetch = jest.fn() | ||
|
|
||
| describe('BaiduQianfanRerank', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks() | ||
| global.fetch = mockedFetch as unknown as typeof fetch | ||
| }) | ||
|
|
||
| afterAll(() => { | ||
| global.fetch = originalFetch | ||
| }) | ||
|
|
||
| it('calls Qianfan rerank API and preserves metadata from ranked indexes', async () => { | ||
| mockedFetch.mockResolvedValue({ | ||
| ok: true, | ||
| json: jest.fn().mockResolvedValue({ | ||
| results: [ | ||
| { index: 1, document: 'second', relevance_score: 0.92 }, | ||
| { index: 0, document: 'first', relevance_score: 0.41 } | ||
| ] | ||
| }) | ||
| }) | ||
|
|
||
| const compressor = new BaiduQianfanRerank('api-key', 'bce-reranker-base', 2) | ||
| const documents = [ | ||
| new Document({ pageContent: 'first', metadata: { source: 'a' } }), | ||
| new Document({ pageContent: 'second', metadata: { source: 'b' } }) | ||
| ] | ||
|
|
||
| const result = await compressor.compressDocuments(documents, 'weather in Shanghai') | ||
|
|
||
| expect(mockedFetch).toHaveBeenCalledWith('https://qianfan.baidubce.com/v2/rerank', { | ||
| method: 'POST', | ||
| headers: { | ||
| Authorization: 'Bearer api-key', | ||
| 'Content-Type': 'application/json' | ||
| }, | ||
| body: JSON.stringify({ | ||
| model: 'bce-reranker-base', | ||
| query: 'weather in Shanghai', | ||
| documents: ['first', 'second'], | ||
| top_n: 2 | ||
| }) | ||
| }) | ||
| expect(result.map((doc) => doc.pageContent)).toEqual(['second', 'first']) | ||
| expect(result[0].metadata).toEqual({ source: 'b', relevance_score: 0.92 }) | ||
| expect(result[1].metadata).toEqual({ source: 'a', relevance_score: 0.41 }) | ||
| }) | ||
|
|
||
| it('returns an empty array without calling Qianfan when no documents are provided', async () => { | ||
| const compressor = new BaiduQianfanRerank('api-key', 'bce-reranker-base', 4) | ||
|
|
||
| await expect(compressor.compressDocuments([], 'query')).resolves.toEqual([]) | ||
| expect(mockedFetch).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('falls back to the original documents when Qianfan returns an invalid index', async () => { | ||
| mockedFetch.mockResolvedValue({ | ||
| ok: true, | ||
| json: jest.fn().mockResolvedValue({ | ||
| results: [{ index: 99, document: 'missing', relevance_score: 0.9 }] | ||
| }) | ||
| }) | ||
|
|
||
| const compressor = new BaiduQianfanRerank('api-key', 'bce-reranker-base', 4) | ||
| const documents = [new Document({ pageContent: 'first', metadata: { source: 'a' } })] | ||
|
|
||
| await expect(compressor.compressDocuments(documents, 'query')).resolves.toBe(documents) | ||
| }) | ||
|
|
||
| it('falls back to the original documents when Qianfan returns an API error', async () => { | ||
| mockedFetch.mockResolvedValue({ | ||
| ok: false, | ||
| status: 404, | ||
| text: jest.fn().mockResolvedValue('model not found') | ||
| }) | ||
|
|
||
| const compressor = new BaiduQianfanRerank('api-key', 'missing-model', 4) | ||
| const documents = [new Document({ pageContent: 'first', metadata: { source: 'a' } })] | ||
|
|
||
| await expect(compressor.compressDocuments(documents, 'query')).resolves.toBe(documents) | ||
| }) | ||
|
|
||
| it('falls back to the original documents when the Qianfan call fails', async () => { | ||
| mockedFetch.mockRejectedValue(new Error('network failed')) | ||
|
|
||
| const compressor = new BaiduQianfanRerank('api-key', 'bce-reranker-base', 4) | ||
| const documents = [new Document({ pageContent: 'first', metadata: { source: 'a' } })] | ||
|
|
||
| await expect(compressor.compressDocuments(documents, 'query')).resolves.toBe(documents) | ||
| }) | ||
| }) |
77 changes: 77 additions & 0 deletions
77
packages/components/nodes/retrievers/BaiduQianfanRerankRetriever/BaiduQianfanRerank.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| import { Callbacks } from '@langchain/core/callbacks/manager' | ||
| import { Document } from '@langchain/core/documents' | ||
| import { BaseDocumentCompressor } from '@langchain/classic/retrievers/document_compressors' | ||
|
|
||
| const QIANFAN_RERANK_API_URL = 'https://qianfan.baidubce.com/v2/rerank' | ||
|
|
||
| type QianfanRerankResult = { | ||
| index: number | ||
| document: string | ||
| relevance_score: number | ||
| } | ||
|
|
||
| type QianfanRerankResponse = { | ||
| results?: QianfanRerankResult[] | ||
| } | ||
|
|
||
| export class BaiduQianfanRerank extends BaseDocumentCompressor { | ||
| private readonly qianfanApiKey: string | ||
| private readonly model: string | ||
| private readonly topN: number | ||
|
|
||
| constructor(qianfanApiKey: string, model: string, topN: number) { | ||
| super() | ||
| this.qianfanApiKey = qianfanApiKey | ||
| this.model = model | ||
| this.topN = topN | ||
| } | ||
|
|
||
| async compressDocuments( | ||
| documents: Document<Record<string, any>>[], | ||
| query: string, | ||
| _?: Callbacks | undefined | ||
| ): Promise<Document<Record<string, any>>[]> { | ||
| if (documents.length === 0) return [] | ||
|
|
||
| try { | ||
| const response = await fetch(QIANFAN_RERANK_API_URL, { | ||
| method: 'POST', | ||
| headers: { | ||
| Authorization: `Bearer ${this.qianfanApiKey}`, | ||
| 'Content-Type': 'application/json' | ||
| }, | ||
| body: JSON.stringify({ | ||
| model: this.model, | ||
| query, | ||
| documents: documents.map((doc) => doc.pageContent), | ||
| top_n: this.topN | ||
| }) | ||
| }) | ||
|
|
||
| if (!response.ok) throw new Error(`Baidu Qianfan Rerank API call failed with status ${response.status}`) | ||
|
|
||
| const rerankResponse = (await response.json()) as QianfanRerankResponse | ||
|
|
||
| if (!Array.isArray(rerankResponse.results)) return documents | ||
|
|
||
| const rerankedDocuments: Document<Record<string, any>>[] = [] | ||
| for (const result of rerankResponse.results) { | ||
| const doc = documents[result.index] | ||
| if (!doc) return documents | ||
| rerankedDocuments.push( | ||
| new Document({ | ||
| pageContent: doc.pageContent, | ||
| metadata: { | ||
| ...doc.metadata, | ||
| relevance_score: result.relevance_score | ||
| } | ||
| }) | ||
| ) | ||
| } | ||
|
|
||
| return rerankedDocuments | ||
| } catch (error) { | ||
| return documents | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Swallowing all errors silently makes debugging extremely difficult if the API key is invalid, rate limits are hit, or the model name is incorrect. Consider logging the error to
console.errorbefore returning the fallback documents so that users and administrators can troubleshoot issues.