Changesets · Branches · Tags · Compare
| Changeset | 03a05235ea45477f154c963e3d9970f4a525e27b770f34f07022a71e36ba52d8 |
|---|---|
| Author | Huy Huynh <huy.huynh@dal.ca> · 2025-07-20 14:54 -03:00 |
| Committer | GitHub <noreply@github.com> · 2025-07-20 14:54 -03:00 |
| Parents | bd477015e5d4, 9df0fa5d79c7 |
98 files changed
modified .github/workflows/pr_checks.yaml +41 −0
| @@ -572,6 +572,43 @@ | ||
| 572 | 572 | cd packages/config-yaml |
| 573 | 573 | npm test |
| 574 | 574 | |
| 575 | + openai-adapters-tests: | |
| 576 | + needs: install-openai-adapters | |
| 577 | + runs-on: ubuntu-latest | |
| 578 | + steps: | |
| 579 | + - uses: actions/checkout@v4 | |
| 580 | + | |
| 581 | + - uses: actions/setup-node@v4 | |
| 582 | + with: | |
| 583 | + node-version-file: ".nvmrc" | |
| 584 | + | |
| 585 | + - uses: actions/cache@v4 | |
| 586 | + with: | |
| 587 | + path: node_modules | |
| 588 | + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} | |
| 589 | + | |
| 590 | + - uses: actions/cache@v4 | |
| 591 | + id: openai-adapters-cache | |
| 592 | + with: | |
| 593 | + path: packages/openai-adapters/node_modules | |
| 594 | + key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} | |
| 595 | + | |
| 596 | + - name: Run openai-adapters tests | |
| 597 | + run: | | |
| 598 | + cd packages/openai-adapters | |
| 599 | + npm test | |
| 600 | + env: | |
| 601 | + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} | |
| 602 | + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} | |
| 603 | + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} | |
| 604 | + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} | |
| 605 | + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} | |
| 606 | + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} | |
| 607 | + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} | |
| 608 | + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} | |
| 609 | + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} | |
| 610 | + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} | |
| 611 | + | |
| 575 | 612 | vscode-get-test-file-matrix: |
| 576 | 613 | runs-on: ubuntu-latest |
| 577 | 614 | needs: [install-root, install-vscode, install-config-yaml] |
| @@ -613,6 +650,9 @@ | ||
| 613 | 650 | echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT |
| 614 | 651 | echo "$FILES" >> $GITHUB_OUTPUT |
| 615 | 652 | echo "EOF" >> $GITHUB_OUTPUT |
| 653 | + env: | |
| 654 | + # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 | |
| 655 | + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} | |
| 616 | 656 | |
| 617 | 657 | - name: Debug Outputs |
| 618 | 658 | run: | |
| @@ -1068,6 +1108,7 @@ | ||
| 1068 | 1108 | - config-yaml-checks |
| 1069 | 1109 | - install-config-yaml |
| 1070 | 1110 | - install-openai-adapters |
| 1111 | + - openai-adapters-tests | |
| 1071 | 1112 | |
| 1072 | 1113 | steps: |
| 1073 | 1114 | - name: Decide whether the needed jobs succeeded or failed |
modified .github/workflows/release-config-yaml.yml +16 −0
| @@ -6,6 +6,13 @@ | ||
| 6 | 6 | - main |
| 7 | 7 | paths: |
| 8 | 8 | - "packages/config-yaml/**" |
| 9 | + - ".github/workflows/release-config-yaml.yml" | |
| 10 | + - ".github/workflows/reusable-release.yml" | |
| 11 | + | |
| 12 | +permissions: | |
| 13 | + contents: write | |
| 14 | + issues: write | |
| 15 | + pull-requests: write | |
| 9 | 16 | |
| 10 | 17 | jobs: |
| 11 | 18 | release: |
| @@ -16,3 +23,12 @@ | ||
| 16 | 23 | secrets: |
| 17 | 24 | SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} |
| 18 | 25 | SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} |
| 26 | + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} | |
| 27 | + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} | |
| 28 | + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} | |
| 29 | + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} | |
| 30 | + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} | |
| 31 | + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} | |
| 32 | + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} | |
| 33 | + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} | |
| 34 | + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
modified .github/workflows/release-fetch.yml +16 −0
| @@ -6,6 +6,13 @@ | ||
| 6 | 6 | - main |
| 7 | 7 | paths: |
| 8 | 8 | - "packages/fetch/**" |
| 9 | + - ".github/workflows/release-fetch.yml" | |
| 10 | + - ".github/workflows/reusable-release.yml" | |
| 11 | + | |
| 12 | +permissions: | |
| 13 | + contents: write | |
| 14 | + issues: write | |
| 15 | + pull-requests: write | |
| 9 | 16 | |
| 10 | 17 | jobs: |
| 11 | 18 | release: |
| @@ -16,3 +23,12 @@ | ||
| 16 | 23 | secrets: |
| 17 | 24 | SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} |
| 18 | 25 | SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} |
| 26 | + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} | |
| 27 | + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} | |
| 28 | + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} | |
| 29 | + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} | |
| 30 | + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} | |
| 31 | + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} | |
| 32 | + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} | |
| 33 | + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} | |
| 34 | + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
modified .github/workflows/release-llm-info.yml +8 −0
| @@ -16,3 +16,11 @@ | ||
| 16 | 16 | secrets: |
| 17 | 17 | SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} |
| 18 | 18 | SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} |
| 19 | + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} | |
| 20 | + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} | |
| 21 | + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} | |
| 22 | + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} | |
| 23 | + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} | |
| 24 | + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} | |
| 25 | + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} | |
| 26 | + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} | |
| No newline at the end of the file |
modified .github/workflows/release-openai-adapters.yml +16 −0
| @@ -6,6 +6,13 @@ | ||
| 6 | 6 | - main |
| 7 | 7 | paths: |
| 8 | 8 | - "packages/openai-adapters/**" |
| 9 | + - ".github/workflows/release-openai-adapters.yml" | |
| 10 | + - ".github/workflows/reusable-release.yml" | |
| 11 | + | |
| 12 | +permissions: | |
| 13 | + contents: write | |
| 14 | + issues: write | |
| 15 | + pull-requests: write | |
| 9 | 16 | |
| 10 | 17 | jobs: |
| 11 | 18 | release: |
| @@ -16,3 +23,12 @@ | ||
| 16 | 23 | secrets: |
| 17 | 24 | SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} |
| 18 | 25 | SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} |
| 26 | + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} | |
| 27 | + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} | |
| 28 | + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} | |
| 29 | + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} | |
| 30 | + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} | |
| 31 | + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} | |
| 32 | + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} | |
| 33 | + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} | |
| 34 | + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} |
modified .github/workflows/reusable-release.yml +29 −1
| @@ -14,6 +14,24 @@ | ||
| 14 | 14 | required: true |
| 15 | 15 | SEMANTIC_RELEASE_NPM_TOKEN: |
| 16 | 16 | required: true |
| 17 | + OPENAI_API_KEY: | |
| 18 | + required: false | |
| 19 | + ANTHROPIC_API_KEY: | |
| 20 | + required: false | |
| 21 | + GEMINI_API_KEY: | |
| 22 | + required: false | |
| 23 | + MISTRAL_API_KEY: | |
| 24 | + required: false | |
| 25 | + AZURE_OPENAI_API_KEY: | |
| 26 | + required: false | |
| 27 | + AZURE_FOUNDRY_CODESTRAL_API_KEY: | |
| 28 | + required: false | |
| 29 | + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: | |
| 30 | + required: false | |
| 31 | + AZURE_OPENAI_GPT41_API_KEY: | |
| 32 | + required: false | |
| 33 | + VOYAGE_API_KEY: | |
| 34 | + required: false | |
| 17 | 35 | |
| 18 | 36 | permissions: |
| 19 | 37 | contents: write |
| @@ -46,10 +64,20 @@ | ||
| 46 | 64 | |
| 47 | 65 | - name: Run tests |
| 48 | 66 | run: npm test |
| 67 | + env: | |
| 68 | + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} | |
| 69 | + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} | |
| 70 | + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} | |
| 71 | + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} | |
| 72 | + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} | |
| 73 | + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} | |
| 74 | + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} | |
| 75 | + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} | |
| 76 | + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} | |
| 49 | 77 | |
| 50 | 78 | - name: Release |
| 51 | 79 | env: |
| 52 | 80 | GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} |
| 53 | 81 | NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} |
| 54 | 82 | NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} |
| 55 | - run: npx semantic-release | |
| No newline at the end of the file | ||
| 83 | + run: npx semantic-release |
modified core/.eslintrc.json +9 −1
| @@ -19,5 +19,13 @@ | ||
| 19 | 19 | "max-depth": ["error", { "max": 6 }], |
| 20 | 20 | "max-nested-callbacks": ["error", { "max": 4 }], |
| 21 | 21 | "max-params": ["error", { "max": 8 }] |
| 22 | - } | |
| 22 | + }, | |
| 23 | + "overrides": [ | |
| 24 | + { | |
| 25 | + "files": ["**/*.vitest.ts"], | |
| 26 | + "rules": { | |
| 27 | + "max-lines-per-function": "off" | |
| 28 | + } | |
| 29 | + } | |
| 30 | + ] | |
| 23 | 31 | } |
modified core/core.ts +23 −0
| @@ -24,6 +24,7 @@ | ||
| 24 | 24 | import { callTool } from "./tools/callTool"; |
| 25 | 25 | import { ChatDescriber } from "./util/chatDescriber"; |
| 26 | 26 | import { clipboardCache } from "./util/clipboardCache"; |
| 27 | +import { compactConversation } from "./util/conversationCompaction"; | |
| 27 | 28 | import { GlobalContext } from "./util/GlobalContext"; |
| 28 | 29 | import historyManager from "./util/history"; |
| 29 | 30 | import { editConfigFile, migrateV1DevDataFiles } from "./util/paths"; |
| @@ -549,6 +550,28 @@ | ||
| 549 | 550 | return await ChatDescriber.describe(currentModel, {}, msg.data.text); |
| 550 | 551 | }); |
| 551 | 552 | |
| 553 | + on("conversation/compact", async (msg) => { | |
| 554 | + const currentModel = (await this.configHandler.loadConfig()).config | |
| 555 | + ?.selectedModelByRole.chat; | |
| 556 | + | |
| 557 | + if (!currentModel) { | |
| 558 | + throw new Error("No chat model selected"); | |
| 559 | + } | |
| 560 | + | |
| 561 | + try { | |
| 562 | + await compactConversation({ | |
| 563 | + sessionId: msg.data.sessionId, | |
| 564 | + index: msg.data.index, | |
| 565 | + historyManager, | |
| 566 | + currentModel, | |
| 567 | + }); | |
| 568 | + return undefined; | |
| 569 | + } catch (error) { | |
| 570 | + console.error("Error compacting conversation:", error); | |
| 571 | + return undefined; | |
| 572 | + } | |
| 573 | + }); | |
| 574 | + | |
| 552 | 575 | // Autocomplete |
| 553 | 576 | on("autocomplete/complete", async (msg) => { |
| 554 | 577 | const outcome = |
modified core/index.d.ts +29 −13
| @@ -369,10 +369,32 @@ | ||
| 369 | 369 | toolCalls?: ToolCallDelta[]; |
| 370 | 370 | } |
| 371 | 371 | |
| 372 | +/** | |
| 373 | + * This is meant to be equivalent to the OpenAI [usage object](https://platform.openai.com/docs/api-reference/chat/object#chat/object-usage) | |
| 374 | + * but potentially with additional information that is needed for other providers. | |
| 375 | + */ | |
| 376 | +export interface Usage { | |
| 377 | + completionTokens: number; | |
| 378 | + promptTokens: number; | |
| 379 | + promptTokensDetails?: { | |
| 380 | + cachedTokens?: number; | |
| 381 | + /** This an Anthropic-specific property */ | |
| 382 | + cacheWriteTokens?: number; | |
| 383 | + audioTokens?: number; | |
| 384 | + }; | |
| 385 | + completionTokensDetails?: { | |
| 386 | + acceptedPredictionTokens?: number; | |
| 387 | + reasoningTokens?: number; | |
| 388 | + rejectedPredictionTokens?: number; | |
| 389 | + audioTokens?: number; | |
| 390 | + }; | |
| 391 | +} | |
| 392 | + | |
| 372 | 393 | export interface AssistantChatMessage { |
| 373 | 394 | role: "assistant"; |
| 374 | 395 | content: MessageContent; |
| 375 | 396 | toolCalls?: ToolCallDelta[]; |
| 397 | + usage?: Usage; | |
| 376 | 398 | } |
| 377 | 399 | |
| 378 | 400 | export interface SystemChatMessage { |
| @@ -472,6 +494,7 @@ | ||
| 472 | 494 | isGatheringContext?: boolean; |
| 473 | 495 | reasoning?: Reasoning; |
| 474 | 496 | appliedRules?: RuleWithSource[]; |
| 497 | + conversationSummary?: string; | |
| 475 | 498 | } |
| 476 | 499 | |
| 477 | 500 | export interface LLMFullCompletionOptions extends BaseCompletionOptions { |
| @@ -490,12 +513,14 @@ | ||
| 490 | 513 | kind: "startChat"; |
| 491 | 514 | messages: ChatMessage[]; |
| 492 | 515 | options: CompletionOptions; |
| 516 | + provider: string; | |
| 493 | 517 | } |
| 494 | 518 | |
| 495 | 519 | export interface LLMInteractionStartComplete extends LLMInteractionBase { |
| 496 | 520 | kind: "startComplete"; |
| 497 | 521 | prompt: string; |
| 498 | 522 | options: CompletionOptions; |
| 523 | + provider: string; | |
| 499 | 524 | } |
| 500 | 525 | |
| 501 | 526 | export interface LLMInteractionStartFim extends LLMInteractionBase { |
| @@ -503,6 +528,7 @@ | ||
| 503 | 528 | prefix: string; |
| 504 | 529 | suffix: string; |
| 505 | 530 | options: CompletionOptions; |
| 531 | + provider: string; | |
| 506 | 532 | } |
| 507 | 533 | |
| 508 | 534 | export interface LLMInteractionChunk extends LLMInteractionBase { |
| @@ -519,6 +545,7 @@ | ||
| 519 | 545 | promptTokens: number; |
| 520 | 546 | generatedTokens: number; |
| 521 | 547 | thinkingTokens: number; |
| 548 | + usage: Usage | undefined; | |
| 522 | 549 | } |
| 523 | 550 | |
| 524 | 551 | export interface LLMInteractionSuccess extends LLMInteractionEnd { |
| @@ -1685,23 +1712,12 @@ | ||
| 1685 | 1712 | apiKey?: string; |
| 1686 | 1713 | } |
| 1687 | 1714 | |
| 1688 | -export type PruningStatus = "deleted-last-input" | "pruned" | "not-pruned"; | |
| 1689 | - | |
| 1690 | 1715 | export interface CompiledMessagesResult { |
| 1691 | 1716 | compiledChatMessages: ChatMessage[]; |
| 1692 | - pruningStatus: PruningStatus; | |
| 1717 | + didPrune: boolean; | |
| 1718 | + contextPercentage: number; | |
| 1693 | 1719 | } |
| 1694 | 1720 | |
| 1695 | 1721 | export interface MessageOption { |
| 1696 | 1722 | precompiled: boolean; |
| 1697 | 1723 | } |
| 1698 | - | |
| 1699 | -export type WarningMessageLevel = "warning" | "fatal"; | |
| 1700 | - | |
| 1701 | -export type WarningCategory = "exceeded-context-length" | "deleted-last-input"; | |
| 1702 | - | |
| 1703 | -export interface WarningMessage { | |
| 1704 | - message: string; | |
| 1705 | - level: WarningMessageLevel; | |
| 1706 | - category: WarningCategory; | |
| 1707 | -} |
modified core/indexing/docs/crawlers/DocsCrawler.test.ts +1 −1
| @@ -53,7 +53,7 @@ | ||
| 53 | 53 | }; |
| 54 | 54 | } |
| 55 | 55 | |
| 56 | - describe("GitHub Crawler", () => { | |
| 56 | + describe.skip("GitHub Crawler", () => { | |
| 57 | 57 | const repoUrl = |
| 58 | 58 | "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling"; |
| 59 | 59 |
modified core/llm/countTokens.ts +31 −36
| @@ -5,7 +5,6 @@ | ||
| 5 | 5 | CompiledMessagesResult, |
| 6 | 6 | MessageContent, |
| 7 | 7 | MessagePart, |
| 8 | - PruningStatus, | |
| 9 | 8 | Tool, |
| 10 | 9 | } from "../index.js"; |
| 11 | 10 | import { autodetectTemplateType } from "./autodetect.js"; |
| @@ -363,9 +362,6 @@ | ||
| 363 | 362 | } |
| 364 | 363 | |
| 365 | 364 | const MIN_RESPONSE_TOKENS = 1000; |
| 366 | -function getMinResponseTokens(maxTokens: number) { | |
| 367 | - return Math.min(MIN_RESPONSE_TOKENS, maxTokens); | |
| 368 | -} | |
| 369 | 365 | |
| 370 | 366 | function pruneRawPromptFromTop( |
| 371 | 367 | modelName: string, |
| @@ -425,6 +421,8 @@ | ||
| 425 | 421 | supportsImages: boolean; |
| 426 | 422 | tools?: Tool[]; |
| 427 | 423 | }): CompiledMessagesResult { |
| 424 | + let didPrune = false; | |
| 425 | + | |
| 428 | 426 | let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); |
| 429 | 427 | |
| 430 | 428 | // If images not supported, convert MessagePart[] to string |
| @@ -446,21 +444,14 @@ | ||
| 446 | 444 | |
| 447 | 445 | msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); |
| 448 | 446 | |
| 449 | - while (msgsCopy.length > 1) { | |
| 450 | - if (isUserOrToolMsg(msgsCopy.at(-1))) { | |
| 451 | - break; | |
| 452 | - } | |
| 453 | - msgsCopy.pop(); | |
| 454 | - } | |
| 455 | - | |
| 456 | - // // Extract the tool sequence from the end of the message array | |
| 457 | - // const toolSequence = extractToolSequence(msgsCopy); | |
| 447 | + // Extract the tool sequence from the end of the message array | |
| 448 | + const toolSequence = extractToolSequence(msgsCopy); | |
| 458 | 449 | |
| 459 | - // // Count tokens for all messages in the tool sequence | |
| 460 | - // let lastMessagesTokens = 0; | |
| 461 | - // for (const msg of toolSequence) { | |
| 462 | - // lastMessagesTokens += countChatMessageTokens(modelName, msg); | |
| 463 | - // } | |
| 450 | + // Count tokens for all messages in the tool sequence | |
| 451 | + let lastMessagesTokens = 0; | |
| 452 | + for (const msg of toolSequence) { | |
| 453 | + lastMessagesTokens += countChatMessageTokens(modelName, msg); | |
| 454 | + } | |
| 464 | 455 | |
| 465 | 456 | // System message |
| 466 | 457 | let systemMsgTokens = 0; |
| @@ -475,7 +466,7 @@ | ||
| 475 | 466 | } |
| 476 | 467 | |
| 477 | 468 | const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); |
| 478 | - const minOutputTokens = getMinResponseTokens(maxTokens); | |
| 469 | + const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens); | |
| 479 | 470 | |
| 480 | 471 | let inputTokensAvailable = contextLength; |
| 481 | 472 | |
| @@ -486,19 +477,19 @@ | ||
| 486 | 477 | // Non-negotiable messages |
| 487 | 478 | inputTokensAvailable -= toolTokens; |
| 488 | 479 | inputTokensAvailable -= systemMsgTokens; |
| 489 | - // inputTokensAvailable -= lastMessagesTokens; | |
| 480 | + inputTokensAvailable -= lastMessagesTokens; | |
| 490 | 481 | |
| 491 | 482 | // Make sure there's enough context for the non-excludable items |
| 492 | 483 | if (inputTokensAvailable < 0) { |
| 493 | 484 | throw new Error( |
| 494 | 485 | `Not enough context available to include the system message, last user message, and tools. |
| 495 | - There must be at least ${minOutputTokens} tokens remaining for output. | |
| 496 | - Request had the following token counts: | |
| 497 | - - contextLength: ${contextLength} | |
| 498 | - - counting safety buffer: ${countingSafetyBuffer} | |
| 499 | - - tools: ~${toolTokens} | |
| 500 | - - system message: ~${systemMsgTokens} | |
| 501 | - - max output tokens: ${maxTokens}`, | |
| 486 | + There must be at least ${minOutputTokens} tokens remaining for output. | |
| 487 | + Request had the following token counts: | |
| 488 | + - contextLength: ${contextLength} | |
| 489 | + - counting safety buffer: ${countingSafetyBuffer} | |
| 490 | + - tools: ~${toolTokens} | |
| 491 | + - system message: ~${systemMsgTokens} | |
| 492 | + - max output tokens: ${maxTokens}`, | |
| 502 | 493 | ); |
| 503 | 494 | } |
| 504 | 495 | |
| @@ -513,12 +504,10 @@ | ||
| 513 | 504 | }; |
| 514 | 505 | }); |
| 515 | 506 | |
| 516 | - let pruningStatus: PruningStatus = "not-pruned"; | |
| 517 | - | |
| 518 | 507 | while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) { |
| 519 | 508 | const message = historyWithTokens.shift()!; |
| 520 | 509 | currentTotal -= message.tokens; |
| 521 | - pruningStatus = "pruned"; | |
| 510 | + didPrune = true; | |
| 522 | 511 | |
| 523 | 512 | // At this point make sure no latent tool response without corresponding call |
| 524 | 513 | while (historyWithTokens[0]?.role === "tool") { |
| @@ -527,18 +516,24 @@ | ||
| 527 | 516 | } |
| 528 | 517 | } |
| 529 | 518 | |
| 530 | - if (historyWithTokens.length === 0) { | |
| 531 | - pruningStatus = "deleted-last-input"; | |
| 532 | - } | |
| 533 | - | |
| 534 | 519 | // Now reassemble |
| 535 | 520 | const reassembled: ChatMessage[] = []; |
| 536 | 521 | if (systemMsg) { |
| 537 | 522 | reassembled.push(systemMsg); |
| 538 | 523 | } |
| 539 | 524 | reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest)); |
| 540 | - | |
| 541 | - return { compiledChatMessages: reassembled, pruningStatus }; | |
| 525 | + reassembled.push(...toolSequence); | |
| 526 | + | |
| 527 | + const inputTokens = | |
| 528 | + currentTotal + systemMsgTokens + toolTokens + lastMessagesTokens; | |
| 529 | + const availableTokens = | |
| 530 | + contextLength - countingSafetyBuffer - minOutputTokens; | |
| 531 | + const contextPercentage = inputTokens / availableTokens; | |
| 532 | + return { | |
| 533 | + compiledChatMessages: reassembled, | |
| 534 | + didPrune, | |
| 535 | + contextPercentage, | |
| 536 | + }; | |
| 542 | 537 | } |
| 543 | 538 | |
| 544 | 539 | export { |
modified core/llm/index.ts +28 −1
| @@ -28,6 +28,7 @@ | ||
| 28 | 28 | RequestOptions, |
| 29 | 29 | TabAutocompleteOptions, |
| 30 | 30 | TemplateType, |
| 31 | + Usage, | |
| 31 | 32 | } from "../index.js"; |
| 32 | 33 | import mergeJson from "../util/merge.js"; |
| 33 | 34 | import { renderChatMessage } from "../util/messageContent.js"; |
| @@ -327,6 +328,7 @@ | ||
| 327 | 328 | completion: string, |
| 328 | 329 | thinking: string | undefined, |
| 329 | 330 | interaction: ILLMInteractionLog | undefined, |
| 331 | + usage: Usage | undefined, | |
| 330 | 332 | error?: any, |
| 331 | 333 | ): InteractionStatus { |
| 332 | 334 | let promptTokens = this.countTokens(prompt); |
| @@ -368,6 +370,7 @@ | ||
| 368 | 370 | promptTokens, |
| 369 | 371 | generatedTokens, |
| 370 | 372 | thinkingTokens, |
| 373 | + usage, | |
| 371 | 374 | }); |
| 372 | 375 | return "cancelled"; |
| 373 | 376 | } else { |
| @@ -379,6 +382,7 @@ | ||
| 379 | 382 | promptTokens, |
| 380 | 383 | generatedTokens, |
| 381 | 384 | thinkingTokens, |
| 385 | + usage, | |
| 382 | 386 | }); |
| 383 | 387 | return "error"; |
| 384 | 388 | } |
| @@ -388,6 +392,7 @@ | ||
| 388 | 392 | promptTokens, |
| 389 | 393 | generatedTokens, |
| 390 | 394 | thinkingTokens, |
| 395 | + usage, | |
| 391 | 396 | }); |
| 392 | 397 | return "success"; |
| 393 | 398 | } |
| @@ -574,6 +579,7 @@ | ||
| 574 | 579 | prefix, |
| 575 | 580 | suffix, |
| 576 | 581 | options: completionOptions, |
| 582 | + provider: this.providerName, | |
| 577 | 583 | }); |
| 578 | 584 | if (this.llmRequestHook) { |
| 579 | 585 | this.llmRequestHook(completionOptions.model, fimLog); |
| @@ -622,6 +628,7 @@ | ||
| 622 | 628 | completion, |
| 623 | 629 | undefined, |
| 624 | 630 | interaction, |
| 631 | + undefined, | |
| 625 | 632 | ); |
| 626 | 633 | } catch (e) { |
| 627 | 634 | status = this._logEnd( |
| @@ -630,6 +637,7 @@ | ||
| 630 | 637 | completion, |
| 631 | 638 | undefined, |
| 632 | 639 | interaction, |
| 640 | + undefined, | |
| 633 | 641 | e, |
| 634 | 642 | ); |
| 635 | 643 | throw e; |
| @@ -641,6 +649,7 @@ | ||
| 641 | 649 | completion, |
| 642 | 650 | undefined, |
| 643 | 651 | interaction, |
| 652 | + undefined, | |
| 644 | 653 | "cancel", |
| 645 | 654 | ); |
| 646 | 655 | } |
| @@ -681,6 +690,7 @@ | ||
| 681 | 690 | kind: "startComplete", |
| 682 | 691 | prompt, |
| 683 | 692 | options: completionOptions, |
| 693 | + provider: this.providerName, | |
| 684 | 694 | }); |
| 685 | 695 | if (this.llmRequestHook) { |
| 686 | 696 | this.llmRequestHook(completionOptions.model, prompt); |
| @@ -736,6 +746,7 @@ | ||
| 736 | 746 | completion, |
| 737 | 747 | undefined, |
| 738 | 748 | interaction, |
| 749 | + undefined, | |
| 739 | 750 | ); |
| 740 | 751 | } catch (e) { |
| 741 | 752 | status = this._logEnd( |
| @@ -744,6 +755,7 @@ | ||
| 744 | 755 | completion, |
| 745 | 756 | undefined, |
| 746 | 757 | interaction, |
| 758 | + undefined, | |
| 747 | 759 | e, |
| 748 | 760 | ); |
| 749 | 761 | throw e; |
| @@ -755,6 +767,7 @@ | ||
| 755 | 767 | completion, |
| 756 | 768 | undefined, |
| 757 | 769 | interaction, |
| 770 | + undefined, | |
| 758 | 771 | "cancel", |
| 759 | 772 | ); |
| 760 | 773 | } |
| @@ -796,6 +809,7 @@ | ||
| 796 | 809 | kind: "startComplete", |
| 797 | 810 | prompt: prompt, |
| 798 | 811 | options: completionOptions, |
| 812 | + provider: this.providerName, | |
| 799 | 813 | }); |
| 800 | 814 | if (this.llmRequestHook) { |
| 801 | 815 | this.llmRequestHook(completionOptions.model, prompt); |
| @@ -829,6 +843,7 @@ | ||
| 829 | 843 | completion, |
| 830 | 844 | undefined, |
| 831 | 845 | interaction, |
| 846 | + undefined, | |
| 832 | 847 | ); |
| 833 | 848 | } catch (e) { |
| 834 | 849 | status = this._logEnd( |
| @@ -837,6 +852,7 @@ | ||
| 837 | 852 | completion, |
| 838 | 853 | undefined, |
| 839 | 854 | interaction, |
| 855 | + undefined, | |
| 840 | 856 | e, |
| 841 | 857 | ); |
| 842 | 858 | throw e; |
| @@ -848,6 +864,7 @@ | ||
| 848 | 864 | completion, |
| 849 | 865 | undefined, |
| 850 | 866 | interaction, |
| 867 | + undefined, | |
| 851 | 868 | "cancel", |
| 852 | 869 | ); |
| 853 | 870 | } |
| @@ -923,7 +940,7 @@ | ||
| 923 | 940 | let messages = _messages; |
| 924 | 941 | |
| 925 | 942 | // If not precompiled, compile the chat messages |
| 926 | - if (!messageOptions || messageOptions.precompiled === false) { | |
| 943 | + if (!messageOptions?.precompiled) { | |
| 927 | 944 | const { compiledChatMessages } = compileChatMessages({ |
| 928 | 945 | modelName: completionOptions.model, |
| 929 | 946 | msgs: _messages, |
| @@ -944,6 +961,7 @@ | ||
| 944 | 961 | kind: "startChat", |
| 945 | 962 | messages, |
| 946 | 963 | options: completionOptions, |
| 964 | + provider: this.providerName, | |
| 947 | 965 | }); |
| 948 | 966 | if (this.llmRequestHook) { |
| 949 | 967 | this.llmRequestHook(completionOptions.model, prompt); |
| @@ -952,6 +970,7 @@ | ||
| 952 | 970 | |
| 953 | 971 | let thinking = ""; |
| 954 | 972 | let completion = ""; |
| 973 | + let usage: Usage | undefined = undefined; | |
| 955 | 974 | |
| 956 | 975 | try { |
| 957 | 976 | if (this.templateMessages) { |
| @@ -1018,6 +1037,11 @@ | ||
| 1018 | 1037 | kind: "message", |
| 1019 | 1038 | message: chunk, |
| 1020 | 1039 | }); |
| 1040 | + | |
| 1041 | + if (chunk.role === "assistant" && chunk.usage) { | |
| 1042 | + usage = chunk.usage; | |
| 1043 | + } | |
| 1044 | + | |
| 1021 | 1045 | yield chunk; |
| 1022 | 1046 | } |
| 1023 | 1047 | } |
| @@ -1028,6 +1052,7 @@ | ||
| 1028 | 1052 | completion, |
| 1029 | 1053 | thinking, |
| 1030 | 1054 | interaction, |
| 1055 | + usage, | |
| 1031 | 1056 | ); |
| 1032 | 1057 | } catch (e) { |
| 1033 | 1058 | status = this._logEnd( |
| @@ -1036,6 +1061,7 @@ | ||
| 1036 | 1061 | completion, |
| 1037 | 1062 | thinking, |
| 1038 | 1063 | interaction, |
| 1064 | + usage, | |
| 1039 | 1065 | e, |
| 1040 | 1066 | ); |
| 1041 | 1067 | throw e; |
| @@ -1047,6 +1073,7 @@ | ||
| 1047 | 1073 | completion, |
| 1048 | 1074 | undefined, |
| 1049 | 1075 | interaction, |
| 1076 | + usage, | |
| 1050 | 1077 | "cancel", |
| 1051 | 1078 | ); |
| 1052 | 1079 | } |
modified core/llm/llms/Anthropic.ts +47 −3
| @@ -1,5 +1,10 @@ | ||
| 1 | 1 | import { streamSse } from "@continuedev/fetch"; |
| 2 | -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; | |
| 2 | +import { | |
| 3 | + ChatMessage, | |
| 4 | + CompletionOptions, | |
| 5 | + LLMOptions, | |
| 6 | + Usage, | |
| 7 | +} from "../../index.js"; | |
| 3 | 8 | import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; |
| 4 | 9 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 5 | 10 | import { BaseLLM } from "../index.js"; |
| @@ -234,15 +239,49 @@ | ||
| 234 | 239 | |
| 235 | 240 | if (options.stream === false) { |
| 236 | 241 | const data = await response.json(); |
| 237 | - yield { role: "assistant", content: data.content[0].text }; | |
| 242 | + const cost = data.usage | |
| 243 | + ? { | |
| 244 | + inputTokens: data.usage.input_tokens, | |
| 245 | + outputTokens: data.usage.output_tokens, | |
| 246 | + totalTokens: data.usage.input_tokens + data.usage.output_tokens, | |
| 247 | + } | |
| 248 | + : {}; | |
| 249 | + yield { | |
| 250 | + role: "assistant", | |
| 251 | + content: data.content[0].text, | |
| 252 | + ...(Object.keys(cost).length > 0 ? { cost } : {}), | |
| 253 | + }; | |
| 238 | 254 | return; |
| 239 | 255 | } |
| 240 | 256 | |
| 241 | 257 | let lastToolUseId: string | undefined; |
| 242 | 258 | let lastToolUseName: string | undefined; |
| 259 | + let usage: Usage = { | |
| 260 | + promptTokens: 0, | |
| 261 | + completionTokens: 0, | |
| 262 | + promptTokensDetails: { | |
| 263 | + cachedTokens: 0, | |
| 264 | + cacheWriteTokens: 0, | |
| 265 | + }, | |
| 266 | + }; | |
| 267 | + | |
| 243 | 268 | for await (const value of streamSse(response)) { |
| 244 | 269 | // https://docs.anthropic.com/en/api/messages-streaming#event-types |
| 245 | 270 | switch (value.type) { |
| 271 | + case "message_start": | |
| 272 | + // Capture initial usage information | |
| 273 | + usage.promptTokens = value.message.usage.input_tokens; | |
| 274 | + usage.promptTokensDetails!.cachedTokens = | |
| 275 | + value.message.usage.cache_read_input_tokens; | |
| 276 | + usage.promptTokensDetails!.cacheWriteTokens = | |
| 277 | + value.message.usage.cache_creation_input_tokens; | |
| 278 | + break; | |
| 279 | + case "message_delta": | |
| 280 | + // Update usage information during streaming | |
| 281 | + if (value.usage) { | |
| 282 | + usage.completionTokens = value.usage.output_tokens; | |
| 283 | + } | |
| 284 | + break; | |
| 246 | 285 | case "content_block_start": |
| 247 | 286 | if (value.content_block.type === "tool_use") { |
| 248 | 287 | lastToolUseId = value.content_block.id; |
| @@ -250,7 +289,6 @@ | ||
| 250 | 289 | } |
| 251 | 290 | // handle redacted thinking |
| 252 | 291 | if (value.content_block.type === "redacted_thinking") { |
| 253 | - console.log("redacted thinking", value.content_block.data); | |
| 254 | 292 | yield { |
| 255 | 293 | role: "thinking", |
| 256 | 294 | content: "", |
| @@ -303,6 +341,12 @@ | ||
| 303 | 341 | break; |
| 304 | 342 | } |
| 305 | 343 | } |
| 344 | + | |
| 345 | + yield { | |
| 346 | + role: "assistant", | |
| 347 | + content: "", | |
| 348 | + usage, | |
| 349 | + }; | |
| 306 | 350 | } |
| 307 | 351 | } |
| 308 | 352 |
added core/llm/llms/Anthropic.vitest.ts +495 −0
| @@ -0,0 +1,495 @@ | ||
| 1 | +import { afterEach, describe, expect, test, vi } from "vitest"; | |
| 2 | +import { ILLM } from "../../index.js"; | |
| 3 | +import Anthropic from "./Anthropic.js"; | |
| 4 | + | |
| 5 | +interface LlmTestCase { | |
| 6 | + llm: ILLM; | |
| 7 | + methodToTest: keyof ILLM; | |
| 8 | + params: any[]; | |
| 9 | + expectedRequest: { | |
| 10 | + url: string; | |
| 11 | + method: string; | |
| 12 | + headers?: Record<string, string>; | |
| 13 | + body?: Record<string, any>; | |
| 14 | + }; | |
| 15 | + mockResponse?: any; | |
| 16 | + mockStream?: any[]; | |
| 17 | +} | |
| 18 | + | |
| 19 | +function createMockStream(mockStream: any[]) { | |
| 20 | + const encoder = new TextEncoder(); | |
| 21 | + return new ReadableStream({ | |
| 22 | + start(controller) { | |
| 23 | + for (const chunk of mockStream) { | |
| 24 | + controller.enqueue( | |
| 25 | + encoder.encode( | |
| 26 | + `data: ${ | |
| 27 | + typeof chunk === "string" ? chunk : JSON.stringify(chunk) | |
| 28 | + }\n\n`, | |
| 29 | + ), | |
| 30 | + ); | |
| 31 | + } | |
| 32 | + controller.close(); | |
| 33 | + }, | |
| 34 | + }); | |
| 35 | +} | |
| 36 | + | |
| 37 | +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { | |
| 38 | + const mockFetch = vi.fn(); | |
| 39 | + | |
| 40 | + if (mockStream) { | |
| 41 | + const stream = createMockStream(mockStream); | |
| 42 | + mockFetch.mockResolvedValue( | |
| 43 | + new Response(stream, { | |
| 44 | + headers: { | |
| 45 | + "Content-Type": "text/event-stream", | |
| 46 | + }, | |
| 47 | + }), | |
| 48 | + ); | |
| 49 | + } else { | |
| 50 | + mockFetch.mockResolvedValue( | |
| 51 | + new Response(JSON.stringify(mockResponse), { | |
| 52 | + headers: { "Content-Type": "application/json" }, | |
| 53 | + }), | |
| 54 | + ); | |
| 55 | + } | |
| 56 | + | |
| 57 | + return mockFetch; | |
| 58 | +} | |
| 59 | + | |
| 60 | +function setupReadableStreamPolyfill() { | |
| 61 | + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved | |
| 62 | + // @ts-ignore | |
| 63 | + const originalFrom = ReadableStream.from; | |
| 64 | + // @ts-ignore | |
| 65 | + ReadableStream.from = (body) => { | |
| 66 | + if (body?.source) { | |
| 67 | + return body; | |
| 68 | + } | |
| 69 | + return originalFrom(body); | |
| 70 | + }; | |
| 71 | +} | |
| 72 | + | |
| 73 | +async function executeLlmMethod( | |
| 74 | + llm: ILLM, | |
| 75 | + methodToTest: keyof ILLM, | |
| 76 | + params: any[], | |
| 77 | +) { | |
| 78 | + if (typeof (llm as any)[methodToTest] !== "function") { | |
| 79 | + throw new Error( | |
| 80 | + `Method ${String(methodToTest)} does not exist on the LLM instance.`, | |
| 81 | + ); | |
| 82 | + } | |
| 83 | + | |
| 84 | + const result = await (llm as any)[methodToTest](...params); | |
| 85 | + if (result?.next) { | |
| 86 | + for await (const _ of result) { | |
| 87 | + } | |
| 88 | + } | |
| 89 | +} | |
| 90 | + | |
| 91 | +function assertFetchCall(mockFetch: any, expectedRequest: any) { | |
| 92 | + expect(mockFetch).toHaveBeenCalledTimes(1); | |
| 93 | + const [url, options] = mockFetch.mock.calls[0]; | |
| 94 | + | |
| 95 | + expect(url.toString()).toBe(expectedRequest.url); | |
| 96 | + expect(options.method).toBe(expectedRequest.method); | |
| 97 | + | |
| 98 | + if (expectedRequest.headers) { | |
| 99 | + expect(options.headers).toEqual( | |
| 100 | + expect.objectContaining(expectedRequest.headers), | |
| 101 | + ); | |
| 102 | + } | |
| 103 | + | |
| 104 | + if (expectedRequest.body) { | |
| 105 | + const actualBody = JSON.parse(options.body as string); | |
| 106 | + expect(actualBody).toEqual(expectedRequest.body); | |
| 107 | + } | |
| 108 | +} | |
| 109 | + | |
| 110 | +async function runLlmTest(testCase: LlmTestCase) { | |
| 111 | + const { | |
| 112 | + llm, | |
| 113 | + methodToTest, | |
| 114 | + params, | |
| 115 | + expectedRequest, | |
| 116 | + mockResponse, | |
| 117 | + mockStream, | |
| 118 | + } = testCase; | |
| 119 | + | |
| 120 | + const mockFetch = setupMockFetch(mockResponse, mockStream); | |
| 121 | + setupReadableStreamPolyfill(); | |
| 122 | + | |
| 123 | + (llm as any).fetch = mockFetch; | |
| 124 | + | |
| 125 | + await executeLlmMethod(llm, methodToTest, params); | |
| 126 | + assertFetchCall(mockFetch, expectedRequest); | |
| 127 | +} | |
| 128 | + | |
| 129 | +describe("Anthropic", () => { | |
| 130 | + afterEach(() => { | |
| 131 | + vi.clearAllMocks(); | |
| 132 | + }); | |
| 133 | + | |
| 134 | + test("streamChat should send a valid request", async () => { | |
| 135 | + const anthropic = new Anthropic({ | |
| 136 | + apiKey: "test-api-key", | |
| 137 | + model: "claude-3-5-sonnet-latest", | |
| 138 | + apiBase: "https://api.anthropic.com/v1/", | |
| 139 | + }); | |
| 140 | + | |
| 141 | + await runLlmTest({ | |
| 142 | + llm: anthropic, | |
| 143 | + methodToTest: "streamChat", | |
| 144 | + params: [ | |
| 145 | + [{ role: "user", content: "hello" }], | |
| 146 | + new AbortController().signal, | |
| 147 | + ], | |
| 148 | + expectedRequest: { | |
| 149 | + url: "https://api.anthropic.com/v1/messages", | |
| 150 | + method: "POST", | |
| 151 | + headers: { | |
| 152 | + "Content-Type": "application/json", | |
| 153 | + Accept: "application/json", | |
| 154 | + "anthropic-version": "2023-06-01", | |
| 155 | + "x-api-key": "test-api-key", | |
| 156 | + }, | |
| 157 | + body: { | |
| 158 | + model: "claude-3-5-sonnet-latest", | |
| 159 | + max_tokens: 8192, | |
| 160 | + stream: true, | |
| 161 | + messages: [ | |
| 162 | + { | |
| 163 | + role: "user", | |
| 164 | + content: [{ type: "text", text: "hello" }], | |
| 165 | + }, | |
| 166 | + ], | |
| 167 | + system: "", | |
| 168 | + }, | |
| 169 | + }, | |
| 170 | + mockStream: [ | |
| 171 | + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}', | |
| 172 | + '{"type": "content_block_stop"}', | |
| 173 | + ], | |
| 174 | + }); | |
| 175 | + }); | |
| 176 | + | |
| 177 | + test("chat should send a valid request", async () => { | |
| 178 | + const anthropic = new Anthropic({ | |
| 179 | + apiKey: "test-api-key", | |
| 180 | + model: "claude-3-5-sonnet-latest", | |
| 181 | + apiBase: "https://api.anthropic.com/v1/", | |
| 182 | + }); | |
| 183 | + | |
| 184 | + await runLlmTest({ | |
| 185 | + llm: anthropic, | |
| 186 | + methodToTest: "chat", | |
| 187 | + params: [ | |
| 188 | + [{ role: "user", content: "hello" }], | |
| 189 | + new AbortController().signal, | |
| 190 | + ], | |
| 191 | + expectedRequest: { | |
| 192 | + url: "https://api.anthropic.com/v1/messages", | |
| 193 | + method: "POST", | |
| 194 | + headers: { | |
| 195 | + "Content-Type": "application/json", | |
| 196 | + Accept: "application/json", | |
| 197 | + "anthropic-version": "2023-06-01", | |
| 198 | + "x-api-key": "test-api-key", | |
| 199 | + }, | |
| 200 | + body: { | |
| 201 | + model: "claude-3-5-sonnet-latest", | |
| 202 | + max_tokens: 8192, | |
| 203 | + stream: true, | |
| 204 | + messages: [ | |
| 205 | + { | |
| 206 | + role: "user", | |
| 207 | + content: [{ type: "text", text: "hello" }], | |
| 208 | + }, | |
| 209 | + ], | |
| 210 | + system: "", | |
| 211 | + }, | |
| 212 | + }, | |
| 213 | + mockStream: [ | |
| 214 | + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}', | |
| 215 | + '{"type": "content_block_stop"}', | |
| 216 | + ], | |
| 217 | + }); | |
| 218 | + }); | |
| 219 | + | |
| 220 | + test("streamComplete should send a valid request", async () => { | |
| 221 | + const anthropic = new Anthropic({ | |
| 222 | + apiKey: "test-api-key", | |
| 223 | + model: "claude-3-5-sonnet-latest", | |
| 224 | + apiBase: "https://api.anthropic.com/v1/", | |
| 225 | + }); | |
| 226 | + | |
| 227 | + await runLlmTest({ | |
| 228 | + llm: anthropic, | |
| 229 | + methodToTest: "streamComplete", | |
| 230 | + params: ["Complete this: Hello", new AbortController().signal], | |
| 231 | + expectedRequest: { | |
| 232 | + url: "https://api.anthropic.com/v1/messages", | |
| 233 | + method: "POST", | |
| 234 | + headers: { | |
| 235 | + "Content-Type": "application/json", | |
| 236 | + Accept: "application/json", | |
| 237 | + "anthropic-version": "2023-06-01", | |
| 238 | + "x-api-key": "test-api-key", | |
| 239 | + }, | |
| 240 | + body: { | |
| 241 | + model: "claude-3-5-sonnet-latest", | |
| 242 | + max_tokens: 8192, | |
| 243 | + stream: true, | |
| 244 | + messages: [ | |
| 245 | + { | |
| 246 | + role: "user", | |
| 247 | + content: [{ type: "text", text: "Complete this: Hello" }], | |
| 248 | + }, | |
| 249 | + ], | |
| 250 | + system: "", | |
| 251 | + }, | |
| 252 | + }, | |
| 253 | + mockStream: [ | |
| 254 | + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}', | |
| 255 | + '{"type": "content_block_stop"}', | |
| 256 | + ], | |
| 257 | + }); | |
| 258 | + }); | |
| 259 | + | |
| 260 | + test("complete should send a valid request", async () => { | |
| 261 | + const anthropic = new Anthropic({ | |
| 262 | + apiKey: "test-api-key", | |
| 263 | + model: "claude-3-5-sonnet-latest", | |
| 264 | + apiBase: "https://api.anthropic.com/v1/", | |
| 265 | + }); | |
| 266 | + | |
| 267 | + await runLlmTest({ | |
| 268 | + llm: anthropic, | |
| 269 | + methodToTest: "complete", | |
| 270 | + params: ["Complete this: Hello", new AbortController().signal], | |
| 271 | + expectedRequest: { | |
| 272 | + url: "https://api.anthropic.com/v1/messages", | |
| 273 | + method: "POST", | |
| 274 | + headers: { | |
| 275 | + "Content-Type": "application/json", | |
| 276 | + Accept: "application/json", | |
| 277 | + "anthropic-version": "2023-06-01", | |
| 278 | + "x-api-key": "test-api-key", | |
| 279 | + }, | |
| 280 | + body: { | |
| 281 | + model: "claude-3-5-sonnet-latest", | |
| 282 | + max_tokens: 8192, | |
| 283 | + stream: true, | |
| 284 | + messages: [ | |
| 285 | + { | |
| 286 | + role: "user", | |
| 287 | + content: [{ type: "text", text: "Complete this: Hello" }], | |
| 288 | + }, | |
| 289 | + ], | |
| 290 | + system: "", | |
| 291 | + }, | |
| 292 | + }, | |
| 293 | + mockStream: [ | |
| 294 | + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}', | |
| 295 | + '{"type": "content_block_stop"}', | |
| 296 | + ], | |
| 297 | + }); | |
| 298 | + }); | |
| 299 | + | |
| 300 | + describe("Different configurations", () => { | |
| 301 | + test("should handle system message", async () => { | |
| 302 | + const anthropic = new Anthropic({ | |
| 303 | + apiKey: "test-api-key", | |
| 304 | + model: "claude-3-5-sonnet-latest", | |
| 305 | + apiBase: "https://api.anthropic.com/v1/", | |
| 306 | + }); | |
| 307 | + | |
| 308 | + await runLlmTest({ | |
| 309 | + llm: anthropic, | |
| 310 | + methodToTest: "streamChat", | |
| 311 | + params: [ | |
| 312 | + [ | |
| 313 | + { role: "system", content: "You are a helpful assistant." }, | |
| 314 | + { role: "user", content: "Hello!" }, | |
| 315 | + ], | |
| 316 | + new AbortController().signal, | |
| 317 | + ], | |
| 318 | + expectedRequest: { | |
| 319 | + url: "https://api.anthropic.com/v1/messages", | |
| 320 | + method: "POST", | |
| 321 | + headers: { | |
| 322 | + "Content-Type": "application/json", | |
| 323 | + Accept: "application/json", | |
| 324 | + "anthropic-version": "2023-06-01", | |
| 325 | + "x-api-key": "test-api-key", | |
| 326 | + }, | |
| 327 | + body: { | |
| 328 | + model: "claude-3-5-sonnet-latest", | |
| 329 | + max_tokens: 8192, | |
| 330 | + stream: true, | |
| 331 | + messages: [ | |
| 332 | + { | |
| 333 | + role: "user", | |
| 334 | + content: [{ type: "text", text: "Hello!" }], | |
| 335 | + }, | |
| 336 | + ], | |
| 337 | + system: "You are a helpful assistant.", | |
| 338 | + }, | |
| 339 | + }, | |
| 340 | + mockStream: [ | |
| 341 | + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}', | |
| 342 | + '{"type": "content_block_stop"}', | |
| 343 | + ], | |
| 344 | + }); | |
| 345 | + }); | |
| 346 | + | |
| 347 | + test("should handle tool calls", async () => { | |
| 348 | + const anthropic = new Anthropic({ | |
| 349 | + apiKey: "test-api-key", | |
| 350 | + model: "claude-3-5-sonnet-latest", | |
| 351 | + apiBase: "https://api.anthropic.com/v1/", | |
| 352 | + }); | |
| 353 | + | |
| 354 | + const tools = [ | |
| 355 | + { | |
| 356 | + type: "function" as const, | |
| 357 | + function: { | |
| 358 | + name: "get_weather", | |
| 359 | + description: "Get the current weather", | |
| 360 | + parameters: { | |
| 361 | + type: "object", | |
| 362 | + properties: { | |
| 363 | + location: { type: "string" }, | |
| 364 | + }, | |
| 365 | + required: ["location"], | |
| 366 | + }, | |
| 367 | + }, | |
| 368 | + }, | |
| 369 | + ]; | |
| 370 | + | |
| 371 | + await runLlmTest({ | |
| 372 | + llm: anthropic, | |
| 373 | + methodToTest: "streamChat", | |
| 374 | + params: [ | |
| 375 | + [{ role: "user", content: "What's the weather in New York?" }], | |
| 376 | + new AbortController().signal, | |
| 377 | + { tools }, | |
| 378 | + ], | |
| 379 | + expectedRequest: { | |
| 380 | + url: "https://api.anthropic.com/v1/messages", | |
| 381 | + method: "POST", | |
| 382 | + headers: { | |
| 383 | + "Content-Type": "application/json", | |
| 384 | + Accept: "application/json", | |
| 385 | + "anthropic-version": "2023-06-01", | |
| 386 | + "x-api-key": "test-api-key", | |
| 387 | + }, | |
| 388 | + body: { | |
| 389 | + model: "claude-3-5-sonnet-latest", | |
| 390 | + max_tokens: 8192, | |
| 391 | + stream: true, | |
| 392 | + messages: [ | |
| 393 | + { | |
| 394 | + role: "user", | |
| 395 | + content: [ | |
| 396 | + { type: "text", text: "What's the weather in New York?" }, | |
| 397 | + ], | |
| 398 | + }, | |
| 399 | + ], | |
| 400 | + tools: [ | |
| 401 | + { | |
| 402 | + name: "get_weather", | |
| 403 | + description: "Get the current weather", | |
| 404 | + input_schema: { | |
| 405 | + type: "object", | |
| 406 | + properties: { | |
| 407 | + location: { type: "string" }, | |
| 408 | + }, | |
| 409 | + required: ["location"], | |
| 410 | + }, | |
| 411 | + }, | |
| 412 | + ], | |
| 413 | + system: "", | |
| 414 | + }, | |
| 415 | + }, | |
| 416 | + mockStream: [ | |
| 417 | + '{"type": "content_block_start", "content_block": {"type": "tool_use", "id": "toolu_123", "name": "get_weather"}}', | |
| 418 | + '{"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": "{\\"location\\": \\"New York\\""}}', | |
| 419 | + '{"type": "content_block_stop"}', | |
| 420 | + ], | |
| 421 | + }); | |
| 422 | + }); | |
| 423 | + | |
| 424 | + test("should handle custom max tokens", async () => { | |
| 425 | + const anthropic = new Anthropic({ | |
| 426 | + apiKey: "test-api-key", | |
| 427 | + model: "claude-3-5-sonnet-latest", | |
| 428 | + apiBase: "https://api.anthropic.com/v1/", | |
| 429 | + }); | |
| 430 | + | |
| 431 | + await runLlmTest({ | |
| 432 | + llm: anthropic, | |
| 433 | + methodToTest: "streamChat", | |
| 434 | + params: [ | |
| 435 | + [{ role: "user", content: "hello" }], | |
| 436 | + new AbortController().signal, | |
| 437 | + { maxTokens: 1000 }, | |
| 438 | + ], | |
| 439 | + expectedRequest: { | |
| 440 | + url: "https://api.anthropic.com/v1/messages", | |
| 441 | + method: "POST", | |
| 442 | + headers: { | |
| 443 | + "Content-Type": "application/json", | |
| 444 | + Accept: "application/json", | |
| 445 | + "anthropic-version": "2023-06-01", | |
| 446 | + "x-api-key": "test-api-key", | |
| 447 | + }, | |
| 448 | + body: { | |
| 449 | + model: "claude-3-5-sonnet-latest", | |
| 450 | + max_tokens: 1000, | |
| 451 | + stream: true, | |
| 452 | + messages: [ | |
| 453 | + { | |
| 454 | + role: "user", | |
| 455 | + content: [{ type: "text", text: "hello" }], | |
| 456 | + }, | |
| 457 | + ], | |
| 458 | + system: "", | |
| 459 | + }, | |
| 460 | + }, | |
| 461 | + mockStream: [ | |
| 462 | + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello!"}}', | |
| 463 | + '{"type": "content_block_stop"}', | |
| 464 | + ], | |
| 465 | + }); | |
| 466 | + }); | |
| 467 | + }); | |
| 468 | + | |
| 469 | + describe("Error handling", () => { | |
| 470 | + test("should throw error when API key is missing", async () => { | |
| 471 | + const anthropic = new Anthropic({ | |
| 472 | + apiKey: "", | |
| 473 | + model: "claude-3-5-sonnet-latest", | |
| 474 | + apiBase: "https://api.anthropic.com/v1/", | |
| 475 | + }); | |
| 476 | + | |
| 477 | + await expect( | |
| 478 | + runLlmTest({ | |
| 479 | + llm: anthropic, | |
| 480 | + methodToTest: "streamChat", | |
| 481 | + params: [ | |
| 482 | + [{ role: "user", content: "hello" }], | |
| 483 | + new AbortController().signal, | |
| 484 | + ], | |
| 485 | + expectedRequest: { | |
| 486 | + url: "https://api.anthropic.com/v1/messages", | |
| 487 | + method: "POST", | |
| 488 | + }, | |
| 489 | + }), | |
| 490 | + ).rejects.toThrow( | |
| 491 | + "Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.", | |
| 492 | + ); | |
| 493 | + }); | |
| 494 | + }); | |
| 495 | +}); |
modified core/llm/llms/Docker.ts +1 −1
| @@ -17,7 +17,7 @@ | ||
| 17 | 17 | class Docker extends OpenAI implements ModelInstaller { |
| 18 | 18 | static providerName = "docker"; |
| 19 | 19 | static defaultOptions: Partial<LLMOptions> = { |
| 20 | - apiBase: "http://localhost:12434/engines/v1", | |
| 20 | + apiBase: "http://localhost:12434/engines/v1/", | |
| 21 | 21 | model: "gemma3-4B-F4", // Default model |
| 22 | 22 | }; |
| 23 | 23 |
modified core/llm/llms/Fireworks.ts +1 −1
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | class Fireworks extends OpenAI { |
| 6 | 6 | static providerName = "fireworks"; |
| 7 | 7 | static defaultOptions: Partial<LLMOptions> = { |
| 8 | - apiBase: "https://api.fireworks.ai/inference/v1", | |
| 8 | + apiBase: "https://api.fireworks.ai/inference/v1/", | |
| 9 | 9 | }; |
| 10 | 10 | |
| 11 | 11 | private static modelConversion: { [key: string]: string } = { |
added core/llm/llms/Fireworks.vitest.ts +12 −0
| @@ -0,0 +1,12 @@ | ||
| 1 | +import Fireworks from "./Fireworks.js"; | |
| 2 | +import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js"; | |
| 3 | + | |
| 4 | +createOpenAISubclassTests(Fireworks, { | |
| 5 | + providerName: "fireworks", | |
| 6 | + defaultApiBase: "https://api.fireworks.ai/inference/v1/", | |
| 7 | + modelConversions: { | |
| 8 | + "starcoder-7b": "accounts/fireworks/models/starcoder-7b", | |
| 9 | + }, | |
| 10 | + modelConversionContent: | |
| 11 | + "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n", | |
| 12 | +}); |
added core/llm/llms/Groq.vitest.ts +12 −0
| @@ -0,0 +1,12 @@ | ||
| 1 | +import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js"; | |
| 2 | +import Groq from "./Groq.js"; | |
| 3 | + | |
| 4 | +createOpenAISubclassTests(Groq, { | |
| 5 | + providerName: "groq", | |
| 6 | + defaultApiBase: "https://api.groq.com/openai/v1/", | |
| 7 | + modelConversions: { | |
| 8 | + "mistral-8x7b": "mixtral-8x7b-32768", | |
| 9 | + "llama3-8b": "llama3-8b-8192", | |
| 10 | + "llama3-70b": "llama3-70b-8192", | |
| 11 | + }, | |
| 12 | +}); |
modified core/llm/llms/Kindo.ts +1 −1
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | class Kindo extends OpenAI { |
| 6 | 6 | static providerName = "kindo"; |
| 7 | 7 | static defaultOptions: Partial<LLMOptions> = { |
| 8 | - apiBase: "https://llm.kindo.ai/v1", | |
| 8 | + apiBase: "https://llm.kindo.ai/v1/", | |
| 9 | 9 | requestOptions: { |
| 10 | 10 | headers: { |
| 11 | 11 | "kindo-token-transaction-type": "CONTINUE", |
modified core/llm/llms/NCompass.ts +2 −2
| @@ -6,9 +6,9 @@ | ||
| 6 | 6 | class NCompass extends OpenAI { |
| 7 | 7 | static providerName = "ncompass"; |
| 8 | 8 | static defaultOptions: Partial<LLMOptions> = { |
| 9 | - apiBase: "https://api.ncompass.tech/v1", | |
| 9 | + apiBase: "https://api.ncompass.tech/v1/", | |
| 10 | 10 | }; |
| 11 | - static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings"; | |
| 11 | + static embeddingsApiEndpoint = "https://api.gcp.ncompass.tech/v1/embeddings"; | |
| 12 | 12 | |
| 13 | 13 | private static modelConversion: { [key: string]: string } = { |
| 14 | 14 | "qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct", |
added core/llm/llms/OpenAI-compatible-core.vitest.ts +294 −0
| @@ -0,0 +1,294 @@ | ||
| 1 | +import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js"; | |
| 2 | + | |
| 3 | +// Import core OpenAI-compatible providers | |
| 4 | +import OpenAI from "./OpenAI.js"; | |
| 5 | +import Groq from "./Groq.js"; | |
| 6 | +import Fireworks from "./Fireworks.js"; | |
| 7 | +import Together from "./Together.js"; | |
| 8 | +import Deepseek from "./Deepseek.js"; | |
| 9 | +import OpenRouter from "./OpenRouter.js"; | |
| 10 | +import xAI from "./xAI.js"; | |
| 11 | +import Mistral from "./Mistral.js"; | |
| 12 | +import LMStudio from "./LMStudio.js"; | |
| 13 | +import Cerebras from "./Cerebras.js"; | |
| 14 | +import DeepInfra from "./DeepInfra.js"; | |
| 15 | +import Nvidia from "./Nvidia.js"; | |
| 16 | + | |
| 17 | +// Base OpenAI tests | |
| 18 | +import { afterEach, describe, expect, test, vi } from "vitest"; | |
| 19 | +import { ILLM } from "../../index.js"; | |
| 20 | + | |
| 21 | +interface LlmTestCase { | |
| 22 | + llm: ILLM; | |
| 23 | + methodToTest: keyof ILLM; | |
| 24 | + params: any[]; | |
| 25 | + expectedRequest: { | |
| 26 | + url: string; | |
| 27 | + method: string; | |
| 28 | + headers?: Record<string, string>; | |
| 29 | + body?: Record<string, any>; | |
| 30 | + }; | |
| 31 | + mockResponse?: any; | |
| 32 | + mockStream?: any[]; | |
| 33 | +} | |
| 34 | + | |
| 35 | +function createMockStream(mockStream: any[]) { | |
| 36 | + const encoder = new TextEncoder(); | |
| 37 | + return new ReadableStream({ | |
| 38 | + start(controller) { | |
| 39 | + for (const chunk of mockStream) { | |
| 40 | + controller.enqueue( | |
| 41 | + encoder.encode( | |
| 42 | + `data: ${ | |
| 43 | + typeof chunk === "string" ? chunk : JSON.stringify(chunk) | |
| 44 | + }\n\n`, | |
| 45 | + ), | |
| 46 | + ); | |
| 47 | + } | |
| 48 | + controller.close(); | |
| 49 | + }, | |
| 50 | + }); | |
| 51 | +} | |
| 52 | + | |
| 53 | +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { | |
| 54 | + const mockFetch = vi.fn(); | |
| 55 | + | |
| 56 | + if (mockStream) { | |
| 57 | + const stream = createMockStream(mockStream); | |
| 58 | + mockFetch.mockResolvedValue( | |
| 59 | + new Response(stream, { | |
| 60 | + headers: { | |
| 61 | + "Content-Type": "text/event-stream", | |
| 62 | + }, | |
| 63 | + }), | |
| 64 | + ); | |
| 65 | + } else { | |
| 66 | + mockFetch.mockResolvedValue( | |
| 67 | + new Response(JSON.stringify(mockResponse), { | |
| 68 | + headers: { "Content-Type": "application/json" }, | |
| 69 | + }), | |
| 70 | + ); | |
| 71 | + } | |
| 72 | + | |
| 73 | + return mockFetch; | |
| 74 | +} | |
| 75 | + | |
| 76 | +function setupReadableStreamPolyfill() { | |
| 77 | + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved | |
| 78 | + // @ts-ignore | |
| 79 | + const originalFrom = ReadableStream.from; | |
| 80 | + // @ts-ignore | |
| 81 | + ReadableStream.from = (body) => { | |
| 82 | + if (body?.source) { | |
| 83 | + return body; | |
| 84 | + } | |
| 85 | + return originalFrom(body); | |
| 86 | + }; | |
| 87 | +} | |
| 88 | + | |
| 89 | +async function executeLlmMethod( | |
| 90 | + llm: ILLM, | |
| 91 | + methodToTest: keyof ILLM, | |
| 92 | + params: any[], | |
| 93 | +) { | |
| 94 | + if (typeof (llm as any)[methodToTest] !== "function") { | |
| 95 | + throw new Error( | |
| 96 | + `Method ${String(methodToTest)} does not exist on the LLM instance.`, | |
| 97 | + ); | |
| 98 | + } | |
| 99 | + | |
| 100 | + const result = await (llm as any)[methodToTest](...params); | |
| 101 | + if (result?.next) { | |
| 102 | + for await (const _ of result) { | |
| 103 | + } | |
| 104 | + } | |
| 105 | +} | |
| 106 | + | |
| 107 | +function assertFetchCall(mockFetch: any, expectedRequest: any) { | |
| 108 | + expect(mockFetch).toHaveBeenCalledTimes(1); | |
| 109 | + const [url, options] = mockFetch.mock.calls[0]; | |
| 110 | + | |
| 111 | + expect(url.toString()).toBe(expectedRequest.url); | |
| 112 | + expect(options.method).toBe(expectedRequest.method); | |
| 113 | + | |
| 114 | + if (expectedRequest.headers) { | |
| 115 | + expect(options.headers).toEqual( | |
| 116 | + expect.objectContaining(expectedRequest.headers), | |
| 117 | + ); | |
| 118 | + } | |
| 119 | + | |
| 120 | + if (expectedRequest.body) { | |
| 121 | + const actualBody = JSON.parse(options.body as string); | |
| 122 | + expect(actualBody).toEqual(expectedRequest.body); | |
| 123 | + } | |
| 124 | +} | |
| 125 | + | |
| 126 | +async function runLlmTest(testCase: LlmTestCase) { | |
| 127 | + const { | |
| 128 | + llm, | |
| 129 | + methodToTest, | |
| 130 | + params, | |
| 131 | + expectedRequest, | |
| 132 | + mockResponse, | |
| 133 | + mockStream, | |
| 134 | + } = testCase; | |
| 135 | + | |
| 136 | + const mockFetch = setupMockFetch(mockResponse, mockStream); | |
| 137 | + setupReadableStreamPolyfill(); | |
| 138 | + | |
| 139 | + (llm as any).fetch = mockFetch; | |
| 140 | + | |
| 141 | + // Disable OpenAI adapter to use our custom fetch mock | |
| 142 | + (llm as any).useOpenAIAdapterFor = []; | |
| 143 | + | |
| 144 | + await executeLlmMethod(llm, methodToTest, params); | |
| 145 | + assertFetchCall(mockFetch, expectedRequest); | |
| 146 | +} | |
| 147 | + | |
| 148 | +describe("OpenAI", () => { | |
| 149 | + afterEach(() => { | |
| 150 | + vi.clearAllMocks(); | |
| 151 | + }); | |
| 152 | + | |
| 153 | + test("streamChat should send a valid request", async () => { | |
| 154 | + const openai = new OpenAI({ | |
| 155 | + apiKey: "test-api-key", | |
| 156 | + model: "gpt-4", | |
| 157 | + apiBase: "https://api.openai.com/v1/", | |
| 158 | + }); | |
| 159 | + | |
| 160 | + await runLlmTest({ | |
| 161 | + llm: openai, | |
| 162 | + methodToTest: "streamChat", | |
| 163 | + params: [ | |
| 164 | + [{ role: "user", content: "hello" }], | |
| 165 | + new AbortController().signal, | |
| 166 | + ], | |
| 167 | + expectedRequest: { | |
| 168 | + url: "https://api.openai.com/v1/chat/completions", | |
| 169 | + method: "POST", | |
| 170 | + headers: { | |
| 171 | + "Content-Type": "application/json", | |
| 172 | + Authorization: "Bearer test-api-key", | |
| 173 | + "api-key": "test-api-key", | |
| 174 | + }, | |
| 175 | + body: { | |
| 176 | + model: "gpt-4", | |
| 177 | + messages: [{ role: "user", content: "hello" }], | |
| 178 | + stream: true, | |
| 179 | + max_tokens: 2048, | |
| 180 | + }, | |
| 181 | + }, | |
| 182 | + mockStream: [ | |
| 183 | + { choices: [{ delta: { content: "Hello" } }] }, | |
| 184 | + { choices: [{ delta: { content: " world" } }] }, | |
| 185 | + ], | |
| 186 | + }); | |
| 187 | + }); | |
| 188 | +}); | |
| 189 | + | |
| 190 | +// Core OpenAI-compatible providers | |
| 191 | +createOpenAISubclassTests(Groq, { | |
| 192 | + providerName: "groq", | |
| 193 | + defaultApiBase: "https://api.groq.com/openai/v1/", | |
| 194 | + modelConversions: { | |
| 195 | + "mistral-8x7b": "mistral-8x7b", | |
| 196 | + "llama3-8b": "llama3-8b-8192", | |
| 197 | + }, | |
| 198 | + modelConversionContent: "[INST] hello [/INST]", | |
| 199 | + modelConversionMaxTokens: 4096, | |
| 200 | +}); | |
| 201 | + | |
| 202 | +createOpenAISubclassTests(Fireworks, { | |
| 203 | + providerName: "fireworks", | |
| 204 | + defaultApiBase: "https://api.fireworks.ai/inference/v1/", | |
| 205 | + modelConversions: { | |
| 206 | + "starcoder-7b": "starcoder-7b", | |
| 207 | + }, | |
| 208 | + modelConversionContent: | |
| 209 | + "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n", | |
| 210 | +}); | |
| 211 | + | |
| 212 | +createOpenAISubclassTests(Together, { | |
| 213 | + providerName: "together", | |
| 214 | + defaultApiBase: "https://api.together.xyz/v1/", | |
| 215 | + modelConversions: { | |
| 216 | + "codellama-7b": "codellama-7b", | |
| 217 | + "llama3-8b": "meta-llama/Llama-3-8b-chat-hf", | |
| 218 | + }, | |
| 219 | + modelConversionContent: "hello", | |
| 220 | + customStreamCompleteEndpoint: "completions", | |
| 221 | +}); | |
| 222 | + | |
| 223 | +createOpenAISubclassTests(Deepseek, { | |
| 224 | + providerName: "deepseek", | |
| 225 | + defaultApiBase: "https://api.deepseek.com/", | |
| 226 | +}); | |
| 227 | + | |
| 228 | +createOpenAISubclassTests(OpenRouter, { | |
| 229 | + providerName: "openrouter", | |
| 230 | + defaultApiBase: "https://openrouter.ai/api/v1/", | |
| 231 | +}); | |
| 232 | + | |
| 233 | +createOpenAISubclassTests(xAI, { | |
| 234 | + providerName: "xAI", | |
| 235 | + defaultApiBase: "https://api.x.ai/v1/", | |
| 236 | + modelConversions: { | |
| 237 | + "grok-beta": "grok-beta", | |
| 238 | + }, | |
| 239 | + modelConversionContent: "hello", | |
| 240 | +}); | |
| 241 | + | |
| 242 | +createOpenAISubclassTests(Mistral, { | |
| 243 | + providerName: "mistral", | |
| 244 | + defaultApiBase: "https://api.mistral.ai/v1/", | |
| 245 | + modelConversions: { | |
| 246 | + "mistral-7b": "mistral-7b", | |
| 247 | + "mistral-8x7b": "open-mixtral-8x7b", | |
| 248 | + }, | |
| 249 | + modelConversionContent: "hello", | |
| 250 | +}); | |
| 251 | + | |
| 252 | +createOpenAISubclassTests(LMStudio, { | |
| 253 | + providerName: "lmstudio", | |
| 254 | + defaultApiBase: "http://localhost:1234/v1/", | |
| 255 | +}); | |
| 256 | + | |
| 257 | +createOpenAISubclassTests(Cerebras, { | |
| 258 | + providerName: "cerebras", | |
| 259 | + defaultApiBase: "https://api.cerebras.ai/v1/", | |
| 260 | + modelConversions: { | |
| 261 | + "llama3.1-8b": "llama3.1-8b", | |
| 262 | + "llama3.1-70b": "llama3.1-70b", | |
| 263 | + }, | |
| 264 | + modelConversionContent: | |
| 265 | + "<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n", | |
| 266 | +}); | |
| 267 | + | |
| 268 | +createOpenAISubclassTests(DeepInfra, { | |
| 269 | + providerName: "deepinfra", | |
| 270 | + defaultApiBase: "https://api.deepinfra.com/v1/openai/", | |
| 271 | + customEmbeddingsUrl: | |
| 272 | + "https://api.deepinfra.com/v1/inference/text-embedding-ada-002", | |
| 273 | + customEmbeddingsHeaders: { | |
| 274 | + Authorization: "bearer test-api-key", | |
| 275 | + }, | |
| 276 | + customEmbeddingsBody: { | |
| 277 | + inputs: ["Hello", "World"], | |
| 278 | + }, | |
| 279 | +}); | |
| 280 | + | |
| 281 | +createOpenAISubclassTests(Nvidia, { | |
| 282 | + providerName: "nvidia", | |
| 283 | + defaultApiBase: "https://integrate.api.nvidia.com/v1/", | |
| 284 | + customEmbeddingsHeaders: { | |
| 285 | + Authorization: "Bearer test-api-key", | |
| 286 | + "Content-Type": "application/json", | |
| 287 | + }, | |
| 288 | + customEmbeddingsBody: { | |
| 289 | + input: ["Hello", "World"], | |
| 290 | + model: "text-embedding-ada-002", | |
| 291 | + input_type: "passage", | |
| 292 | + truncate: "END", | |
| 293 | + }, | |
| 294 | +}); |
added core/llm/llms/OpenAI-compatible.vitest.ts +453 −0
| @@ -0,0 +1,453 @@ | ||
| 1 | +import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js"; | |
| 2 | + | |
| 3 | +// Import all OpenAI-compatible providers | |
| 4 | +import OpenAI from "./OpenAI.js"; | |
| 5 | +import Groq from "./Groq.js"; | |
| 6 | +import Fireworks from "./Fireworks.js"; | |
| 7 | +import Together from "./Together.js"; | |
| 8 | +import Deepseek from "./Deepseek.js"; | |
| 9 | +import OpenRouter from "./OpenRouter.js"; | |
| 10 | +import xAI from "./xAI.js"; | |
| 11 | +import Mistral from "./Mistral.js"; | |
| 12 | +import LMStudio from "./LMStudio.js"; | |
| 13 | +import Cerebras from "./Cerebras.js"; | |
| 14 | +import DeepInfra from "./DeepInfra.js"; | |
| 15 | +import Nvidia from "./Nvidia.js"; | |
| 16 | +import SambaNova from "./SambaNova.js"; | |
| 17 | +import Scaleway from "./Scaleway.js"; | |
| 18 | +import Venice from "./Venice.js"; | |
| 19 | +import Moonshot from "./Moonshot.js"; | |
| 20 | +import Novita from "./Novita.js"; | |
| 21 | +import SiliconFlow from "./SiliconFlow.js"; | |
| 22 | +import Kindo from "./Kindo.js"; | |
| 23 | +import Azure from "./Azure.js"; | |
| 24 | +import Inception from "./Inception.js"; | |
| 25 | +import Docker from "./Docker.js"; | |
| 26 | +import Voyage from "./Voyage.js"; | |
| 27 | +import Vllm from "./Vllm.js"; | |
| 28 | +import TextGenWebUI from "./TextGenWebUI.js"; | |
| 29 | +// import Relace from "./Relace.js"; // Skip - causing import issues | |
| 30 | +import FunctionNetwork from "./FunctionNetwork.js"; | |
| 31 | +import NCompass from "./NCompass.js"; | |
| 32 | +import LlamaStack from "./LlamaStack.js"; | |
| 33 | +import Nebius from "./Nebius.js"; | |
| 34 | +import OVHcloud from "./OVHcloud.js"; | |
| 35 | + | |
| 36 | +// Base OpenAI tests | |
| 37 | +import { afterEach, describe, expect, test, vi } from "vitest"; | |
| 38 | +import { ILLM } from "../../index.js"; | |
| 39 | + | |
| 40 | +interface LlmTestCase { | |
| 41 | + llm: ILLM; | |
| 42 | + methodToTest: keyof ILLM; | |
| 43 | + params: any[]; | |
| 44 | + expectedRequest: { | |
| 45 | + url: string; | |
| 46 | + method: string; | |
| 47 | + headers?: Record<string, string>; | |
| 48 | + body?: Record<string, any>; | |
| 49 | + }; | |
| 50 | + mockResponse?: any; | |
| 51 | + mockStream?: any[]; | |
| 52 | +} | |
| 53 | + | |
| 54 | +function createMockStream(mockStream: any[]) { | |
| 55 | + const encoder = new TextEncoder(); | |
| 56 | + return new ReadableStream({ | |
| 57 | + start(controller) { | |
| 58 | + for (const chunk of mockStream) { | |
| 59 | + controller.enqueue( | |
| 60 | + encoder.encode( | |
| 61 | + `data: ${ | |
| 62 | + typeof chunk === "string" ? chunk : JSON.stringify(chunk) | |
| 63 | + }\n\n`, | |
| 64 | + ), | |
| 65 | + ); | |
| 66 | + } | |
| 67 | + controller.close(); | |
| 68 | + }, | |
| 69 | + }); | |
| 70 | +} | |
| 71 | + | |
| 72 | +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { | |
| 73 | + const mockFetch = vi.fn(); | |
| 74 | + | |
| 75 | + if (mockStream) { | |
| 76 | + const stream = createMockStream(mockStream); | |
| 77 | + mockFetch.mockResolvedValue( | |
| 78 | + new Response(stream, { | |
| 79 | + headers: { | |
| 80 | + "Content-Type": "text/event-stream", | |
| 81 | + }, | |
| 82 | + }), | |
| 83 | + ); | |
| 84 | + } else { | |
| 85 | + mockFetch.mockResolvedValue( | |
| 86 | + new Response(JSON.stringify(mockResponse), { | |
| 87 | + headers: { "Content-Type": "application/json" }, | |
| 88 | + }), | |
| 89 | + ); | |
| 90 | + } | |
| 91 | + | |
| 92 | + return mockFetch; | |
| 93 | +} | |
| 94 | + | |
| 95 | +function setupReadableStreamPolyfill() { | |
| 96 | + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved | |
| 97 | + // @ts-ignore | |
| 98 | + const originalFrom = ReadableStream.from; | |
| 99 | + // @ts-ignore | |
| 100 | + ReadableStream.from = (body) => { | |
| 101 | + if (body?.source) { | |
| 102 | + return body; | |
| 103 | + } | |
| 104 | + return originalFrom(body); | |
| 105 | + }; | |
| 106 | +} | |
| 107 | + | |
| 108 | +async function executeLlmMethod( | |
| 109 | + llm: ILLM, | |
| 110 | + methodToTest: keyof ILLM, | |
| 111 | + params: any[], | |
| 112 | +) { | |
| 113 | + if (typeof (llm as any)[methodToTest] !== "function") { | |
| 114 | + throw new Error( | |
| 115 | + `Method ${String(methodToTest)} does not exist on the LLM instance.`, | |
| 116 | + ); | |
| 117 | + } | |
| 118 | + | |
| 119 | + const result = await (llm as any)[methodToTest](...params); | |
| 120 | + if (result?.next) { | |
| 121 | + for await (const _ of result) { | |
| 122 | + } | |
| 123 | + } | |
| 124 | +} | |
| 125 | + | |
| 126 | +function assertFetchCall(mockFetch: any, expectedRequest: any) { | |
| 127 | + expect(mockFetch).toHaveBeenCalledTimes(1); | |
| 128 | + const [url, options] = mockFetch.mock.calls[0]; | |
| 129 | + | |
| 130 | + expect(url.toString()).toBe(expectedRequest.url); | |
| 131 | + expect(options.method).toBe(expectedRequest.method); | |
| 132 | + | |
| 133 | + if (expectedRequest.headers) { | |
| 134 | + expect(options.headers).toEqual( | |
| 135 | + expect.objectContaining(expectedRequest.headers), | |
| 136 | + ); | |
| 137 | + } | |
| 138 | + | |
| 139 | + if (expectedRequest.body) { | |
| 140 | + const actualBody = JSON.parse(options.body as string); | |
| 141 | + expect(actualBody).toEqual(expectedRequest.body); | |
| 142 | + } | |
| 143 | +} | |
| 144 | + | |
| 145 | +async function runLlmTest(testCase: LlmTestCase) { | |
| 146 | + const { | |
| 147 | + llm, | |
| 148 | + methodToTest, | |
| 149 | + params, | |
| 150 | + expectedRequest, | |
| 151 | + mockResponse, | |
| 152 | + mockStream, | |
| 153 | + } = testCase; | |
| 154 | + | |
| 155 | + const mockFetch = setupMockFetch(mockResponse, mockStream); | |
| 156 | + setupReadableStreamPolyfill(); | |
| 157 | + | |
| 158 | + (llm as any).fetch = mockFetch; | |
| 159 | + | |
| 160 | + // Disable OpenAI adapter to use our custom fetch mock | |
| 161 | + (llm as any).useOpenAIAdapterFor = []; | |
| 162 | + | |
| 163 | + await executeLlmMethod(llm, methodToTest, params); | |
| 164 | + assertFetchCall(mockFetch, expectedRequest); | |
| 165 | +} | |
| 166 | + | |
| 167 | +describe("OpenAI", () => { | |
| 168 | + afterEach(() => { | |
| 169 | + vi.clearAllMocks(); | |
| 170 | + }); | |
| 171 | + | |
| 172 | + test("streamChat should send a valid request", async () => { | |
| 173 | + const openai = new OpenAI({ | |
| 174 | + apiKey: "test-api-key", | |
| 175 | + model: "gpt-4", | |
| 176 | + apiBase: "https://api.openai.com/v1/", | |
| 177 | + }); | |
| 178 | + | |
| 179 | + await runLlmTest({ | |
| 180 | + llm: openai, | |
| 181 | + methodToTest: "streamChat", | |
| 182 | + params: [ | |
| 183 | + [{ role: "user", content: "hello" }], | |
| 184 | + new AbortController().signal, | |
| 185 | + ], | |
| 186 | + expectedRequest: { | |
| 187 | + url: "https://api.openai.com/v1/chat/completions", | |
| 188 | + method: "POST", | |
| 189 | + headers: { | |
| 190 | + "Content-Type": "application/json", | |
| 191 | + Authorization: "Bearer test-api-key", | |
| 192 | + "api-key": "test-api-key", | |
| 193 | + }, | |
| 194 | + body: { | |
| 195 | + model: "gpt-4", | |
| 196 | + messages: [{ role: "user", content: "hello" }], | |
| 197 | + stream: true, | |
| 198 | + max_tokens: 2048, | |
| 199 | + }, | |
| 200 | + }, | |
| 201 | + mockStream: [ | |
| 202 | + { choices: [{ delta: { content: "Hello" } }] }, | |
| 203 | + { choices: [{ delta: { content: " world" } }] }, | |
| 204 | + ], | |
| 205 | + }); | |
| 206 | + }); | |
| 207 | + | |
| 208 | + test("should handle embeddings", async () => { | |
| 209 | + const openai = new OpenAI({ | |
| 210 | + apiKey: "test-api-key", | |
| 211 | + model: "text-embedding-ada-002", | |
| 212 | + apiBase: "https://api.openai.com/v1/", | |
| 213 | + }); | |
| 214 | + | |
| 215 | + await runLlmTest({ | |
| 216 | + llm: openai, | |
| 217 | + methodToTest: "embed", | |
| 218 | + params: [["Hello", "World"]], | |
| 219 | + expectedRequest: { | |
| 220 | + url: "https://api.openai.com/v1/embeddings", | |
| 221 | + method: "POST", | |
| 222 | + headers: { | |
| 223 | + Authorization: "Bearer test-api-key", | |
| 224 | + "Content-Type": "application/json", | |
| 225 | + "api-key": "test-api-key", | |
| 226 | + }, | |
| 227 | + body: { | |
| 228 | + input: ["Hello", "World"], | |
| 229 | + model: "text-embedding-ada-002", | |
| 230 | + }, | |
| 231 | + }, | |
| 232 | + mockResponse: { | |
| 233 | + data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }], | |
| 234 | + }, | |
| 235 | + }); | |
| 236 | + }); | |
| 237 | +}); | |
| 238 | + | |
| 239 | +// OpenAI-compatible providers | |
| 240 | +createOpenAISubclassTests(Groq, { | |
| 241 | + providerName: "groq", | |
| 242 | + defaultApiBase: "https://api.groq.com/openai/v1/", | |
| 243 | + modelConversions: { | |
| 244 | + "mistral-8x7b": "mixtral-8x7b-32768", | |
| 245 | + "llama3-8b": "llama3-8b-8192", | |
| 246 | + "llama3-70b": "llama3-70b-8192", | |
| 247 | + }, | |
| 248 | + modelConversionContent: "[INST] hello [/INST]", | |
| 249 | + modelConversionMaxTokens: 4096, | |
| 250 | +}); | |
| 251 | + | |
| 252 | +createOpenAISubclassTests(Fireworks, { | |
| 253 | + providerName: "fireworks", | |
| 254 | + defaultApiBase: "https://api.fireworks.ai/inference/v1/", | |
| 255 | + modelConversions: { | |
| 256 | + "starcoder-7b": "accounts/fireworks/models/starcoder-7b", | |
| 257 | + }, | |
| 258 | + modelConversionContent: | |
| 259 | + "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n", | |
| 260 | +}); | |
| 261 | + | |
| 262 | +createOpenAISubclassTests(Together, { | |
| 263 | + providerName: "together", | |
| 264 | + defaultApiBase: "https://api.together.xyz/v1/", | |
| 265 | + modelConversions: { | |
| 266 | + "codellama-7b": "codellama-7b", | |
| 267 | + "llama3-8b": "meta-llama/Llama-3-8b-chat-hf", | |
| 268 | + "mistral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1", | |
| 269 | + }, | |
| 270 | + modelConversionContent: "hello", | |
| 271 | + customStreamCompleteEndpoint: "completions", | |
| 272 | +}); | |
| 273 | + | |
| 274 | +createOpenAISubclassTests(Deepseek, { | |
| 275 | + providerName: "deepseek", | |
| 276 | + defaultApiBase: "https://api.deepseek.com/", | |
| 277 | +}); | |
| 278 | + | |
| 279 | +createOpenAISubclassTests(OpenRouter, { | |
| 280 | + providerName: "openrouter", | |
| 281 | + defaultApiBase: "https://openrouter.ai/api/v1/", | |
| 282 | +}); | |
| 283 | + | |
| 284 | +createOpenAISubclassTests(xAI, { | |
| 285 | + providerName: "xAI", | |
| 286 | + defaultApiBase: "https://api.x.ai/v1/", | |
| 287 | + modelConversions: { | |
| 288 | + "grok-beta": "grok-beta", | |
| 289 | + }, | |
| 290 | + modelConversionContent: "hello", | |
| 291 | +}); | |
| 292 | + | |
| 293 | +createOpenAISubclassTests(Mistral, { | |
| 294 | + providerName: "mistral", | |
| 295 | + defaultApiBase: "https://api.mistral.ai/v1/", | |
| 296 | + modelConversions: { | |
| 297 | + "mistral-7b": "mistral-7b", | |
| 298 | + "mistral-8x7b": "open-mixtral-8x7b", | |
| 299 | + }, | |
| 300 | + modelConversionContent: "hello", | |
| 301 | +}); | |
| 302 | + | |
| 303 | +createOpenAISubclassTests(LMStudio, { | |
| 304 | + providerName: "lmstudio", | |
| 305 | + defaultApiBase: "http://localhost:1234/v1/", | |
| 306 | +}); | |
| 307 | + | |
| 308 | +createOpenAISubclassTests(Cerebras, { | |
| 309 | + providerName: "cerebras", | |
| 310 | + defaultApiBase: "https://api.cerebras.ai/v1/", | |
| 311 | + modelConversions: { | |
| 312 | + "llama3.1-8b": "llama3.1-8b", | |
| 313 | + "llama3.1-70b": "llama3.1-70b", | |
| 314 | + }, | |
| 315 | + modelConversionContent: | |
| 316 | + "<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n", | |
| 317 | +}); | |
| 318 | + | |
| 319 | +createOpenAISubclassTests(DeepInfra, { | |
| 320 | + providerName: "deepinfra", | |
| 321 | + defaultApiBase: "https://api.deepinfra.com/v1/openai/", | |
| 322 | + customEmbeddingsUrl: | |
| 323 | + "https://api.deepinfra.com/v1/inference/text-embedding-ada-002", | |
| 324 | + customEmbeddingsHeaders: { | |
| 325 | + Authorization: "bearer test-api-key", | |
| 326 | + }, | |
| 327 | + customEmbeddingsBody: { | |
| 328 | + inputs: ["Hello", "World"], | |
| 329 | + }, | |
| 330 | +}); | |
| 331 | + | |
| 332 | +createOpenAISubclassTests(Nvidia, { | |
| 333 | + providerName: "nvidia", | |
| 334 | + defaultApiBase: "https://integrate.api.nvidia.com/v1/", | |
| 335 | + customEmbeddingsHeaders: { | |
| 336 | + Authorization: "Bearer test-api-key", | |
| 337 | + "Content-Type": "application/json", | |
| 338 | + }, | |
| 339 | + customEmbeddingsBody: { | |
| 340 | + input: ["Hello", "World"], | |
| 341 | + model: "text-embedding-ada-002", | |
| 342 | + input_type: "passage", | |
| 343 | + truncate: "END", | |
| 344 | + }, | |
| 345 | +}); | |
| 346 | + | |
| 347 | +createOpenAISubclassTests(SambaNova, { | |
| 348 | + providerName: "sambanova", | |
| 349 | + defaultApiBase: "https://api.sambanova.ai/v1/", | |
| 350 | +}); | |
| 351 | + | |
| 352 | +createOpenAISubclassTests(Scaleway, { | |
| 353 | + providerName: "scaleway", | |
| 354 | + defaultApiBase: "https://api.scaleway.ai/v1/", | |
| 355 | +}); | |
| 356 | + | |
| 357 | +createOpenAISubclassTests(Venice, { | |
| 358 | + providerName: "venice", | |
| 359 | + defaultApiBase: "https://api.venice.ai/api/v1/", | |
| 360 | +}); | |
| 361 | + | |
| 362 | +createOpenAISubclassTests(Moonshot, { | |
| 363 | + providerName: "moonshot", | |
| 364 | + defaultApiBase: "https://api.moonshot.cn/v1/", | |
| 365 | +}); | |
| 366 | + | |
| 367 | +createOpenAISubclassTests(Novita, { | |
| 368 | + providerName: "novita", | |
| 369 | + defaultApiBase: "https://api.novita.ai/v3/openai/", | |
| 370 | + customStreamCompleteEndpoint: "completions", | |
| 371 | +}); | |
| 372 | + | |
| 373 | +createOpenAISubclassTests(SiliconFlow, { | |
| 374 | + providerName: "siliconflow", | |
| 375 | + defaultApiBase: "https://api.siliconflow.cn/v1/", | |
| 376 | +}); | |
| 377 | + | |
| 378 | +createOpenAISubclassTests(Kindo, { | |
| 379 | + providerName: "kindo", | |
| 380 | + defaultApiBase: "https://llm.kindo.ai/v1/", | |
| 381 | +}); | |
| 382 | + | |
| 383 | +createOpenAISubclassTests(Azure, { | |
| 384 | + providerName: "azure", | |
| 385 | +}); | |
| 386 | + | |
| 387 | +createOpenAISubclassTests(Inception, { | |
| 388 | + providerName: "inception", | |
| 389 | + defaultApiBase: "https://api.inceptionlabs.ai/v1/", | |
| 390 | + customBodyOptions: { | |
| 391 | + temperature: 0.0, | |
| 392 | + presence_penalty: 1.5, | |
| 393 | + stop: ["<|endoftext|>"], | |
| 394 | + }, | |
| 395 | +}); | |
| 396 | + | |
| 397 | +createOpenAISubclassTests(Docker, { | |
| 398 | + providerName: "docker", | |
| 399 | + defaultApiBase: "http://localhost:12434/engines/v1/", | |
| 400 | +}); | |
| 401 | + | |
| 402 | +createOpenAISubclassTests(Voyage, { | |
| 403 | + providerName: "voyage", | |
| 404 | + defaultApiBase: "https://api.voyageai.com/v1/", | |
| 405 | +}); | |
| 406 | + | |
| 407 | +createOpenAISubclassTests(Vllm, { | |
| 408 | + providerName: "vllm", | |
| 409 | + defaultApiBase: "https://api.openai.com/v1/", | |
| 410 | +}); | |
| 411 | + | |
| 412 | +createOpenAISubclassTests(TextGenWebUI, { | |
| 413 | + providerName: "text-gen-webui", | |
| 414 | + defaultApiBase: "http://localhost:5000/v1/", | |
| 415 | +}); | |
| 416 | + | |
| 417 | +createOpenAISubclassTests(FunctionNetwork, { | |
| 418 | + providerName: "function-network", | |
| 419 | + defaultApiBase: "https://api.function.network/v1/", | |
| 420 | + customEmbeddingsHeaders: { | |
| 421 | + Authorization: "Bearer test-api-key", | |
| 422 | + "Content-Type": "application/json", | |
| 423 | + }, | |
| 424 | +}); | |
| 425 | + | |
| 426 | +createOpenAISubclassTests(NCompass, { | |
| 427 | + providerName: "ncompass", | |
| 428 | + defaultApiBase: "https://api.ncompass.tech/v1/", | |
| 429 | + customEmbeddingsUrl: "https://api.gcp.ncompass.tech/v1/embeddings", | |
| 430 | + customEmbeddingsHeaders: { | |
| 431 | + Authorization: "Bearer test-api-key", | |
| 432 | + "Content-Type": "application/json", | |
| 433 | + }, | |
| 434 | + customEmbeddingsBody: { | |
| 435 | + input: ["Hello", "World"], | |
| 436 | + model: "text-embedding-ada-002", | |
| 437 | + }, | |
| 438 | +}); | |
| 439 | + | |
| 440 | +createOpenAISubclassTests(LlamaStack, { | |
| 441 | + providerName: "llamastack", | |
| 442 | + defaultApiBase: "http://localhost:8321/v1/openai/v1/", | |
| 443 | +}); | |
| 444 | + | |
| 445 | +createOpenAISubclassTests(Nebius, { | |
| 446 | + providerName: "nebius", | |
| 447 | + defaultApiBase: "https://api.studio.nebius.ai/v1/", | |
| 448 | +}); | |
| 449 | + | |
| 450 | +createOpenAISubclassTests(OVHcloud, { | |
| 451 | + providerName: "ovhcloud", | |
| 452 | + defaultApiBase: "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/", | |
| 453 | +}); |
added core/llm/llms/OpenAI.vitest.ts +427 −0
| @@ -0,0 +1,427 @@ | ||
| 1 | +import { afterEach, describe, expect, test, vi } from "vitest"; | |
| 2 | +import { ILLM } from "../../index.js"; | |
| 3 | +import OpenAI from "./OpenAI.js"; | |
| 4 | + | |
| 5 | +interface LlmTestCase { | |
| 6 | + llm: ILLM; | |
| 7 | + methodToTest: keyof ILLM; | |
| 8 | + params: any[]; | |
| 9 | + expectedRequest: { | |
| 10 | + url: string; | |
| 11 | + method: string; | |
| 12 | + headers?: Record<string, string>; | |
| 13 | + body?: Record<string, any>; | |
| 14 | + }; | |
| 15 | + mockResponse?: any; | |
| 16 | + mockStream?: any[]; | |
| 17 | +} | |
| 18 | + | |
| 19 | +function createMockStream(mockStream: any[]) { | |
| 20 | + const encoder = new TextEncoder(); | |
| 21 | + return new ReadableStream({ | |
| 22 | + start(controller) { | |
| 23 | + for (const chunk of mockStream) { | |
| 24 | + controller.enqueue( | |
| 25 | + encoder.encode( | |
| 26 | + `data: ${ | |
| 27 | + typeof chunk === "string" ? chunk : JSON.stringify(chunk) | |
| 28 | + }\n\n`, | |
| 29 | + ), | |
| 30 | + ); | |
| 31 | + } | |
| 32 | + controller.close(); | |
| 33 | + }, | |
| 34 | + }); | |
| 35 | +} | |
| 36 | + | |
| 37 | +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { | |
| 38 | + const mockFetch = vi.fn(); | |
| 39 | + | |
| 40 | + if (mockStream) { | |
| 41 | + const stream = createMockStream(mockStream); | |
| 42 | + mockFetch.mockResolvedValue( | |
| 43 | + new Response(stream, { | |
| 44 | + headers: { | |
| 45 | + "Content-Type": "text/event-stream", | |
| 46 | + }, | |
| 47 | + }), | |
| 48 | + ); | |
| 49 | + } else { | |
| 50 | + mockFetch.mockResolvedValue( | |
| 51 | + new Response(JSON.stringify(mockResponse), { | |
| 52 | + headers: { "Content-Type": "application/json" }, | |
| 53 | + }), | |
| 54 | + ); | |
| 55 | + } | |
| 56 | + | |
| 57 | + return mockFetch; | |
| 58 | +} | |
| 59 | + | |
| 60 | +function setupReadableStreamPolyfill() { | |
| 61 | + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved | |
| 62 | + // @ts-ignore | |
| 63 | + const originalFrom = ReadableStream.from; | |
| 64 | + // @ts-ignore | |
| 65 | + ReadableStream.from = (body) => { | |
| 66 | + if (body?.source) { | |
| 67 | + return body; | |
| 68 | + } | |
| 69 | + return originalFrom(body); | |
| 70 | + }; | |
| 71 | +} | |
| 72 | + | |
| 73 | +async function executeLlmMethod( | |
| 74 | + llm: ILLM, | |
| 75 | + methodToTest: keyof ILLM, | |
| 76 | + params: any[], | |
| 77 | +) { | |
| 78 | + if (typeof (llm as any)[methodToTest] !== "function") { | |
| 79 | + throw new Error( | |
| 80 | + `Method ${String(methodToTest)} does not exist on the LLM instance.`, | |
| 81 | + ); | |
| 82 | + } | |
| 83 | + | |
| 84 | + const result = await (llm as any)[methodToTest](...params); | |
| 85 | + if (result?.next) { | |
| 86 | + for await (const _ of result) { | |
| 87 | + } | |
| 88 | + } | |
| 89 | +} | |
| 90 | + | |
| 91 | +function assertFetchCall(mockFetch: any, expectedRequest: any) { | |
| 92 | + expect(mockFetch).toHaveBeenCalledTimes(1); | |
| 93 | + const [url, options] = mockFetch.mock.calls[0]; | |
| 94 | + | |
| 95 | + expect(url.toString()).toBe(expectedRequest.url); | |
| 96 | + expect(options.method).toBe(expectedRequest.method); | |
| 97 | + | |
| 98 | + if (expectedRequest.headers) { | |
| 99 | + expect(options.headers).toEqual( | |
| 100 | + expect.objectContaining(expectedRequest.headers), | |
| 101 | + ); | |
| 102 | + } | |
| 103 | + | |
| 104 | + if (expectedRequest.body) { | |
| 105 | + const actualBody = JSON.parse(options.body as string); | |
| 106 | + expect(actualBody).toEqual(expectedRequest.body); | |
| 107 | + } | |
| 108 | +} | |
| 109 | + | |
| 110 | +async function runLlmTest(testCase: LlmTestCase) { | |
| 111 | + const { | |
| 112 | + llm, | |
| 113 | + methodToTest, | |
| 114 | + params, | |
| 115 | + expectedRequest, | |
| 116 | + mockResponse, | |
| 117 | + mockStream, | |
| 118 | + } = testCase; | |
| 119 | + | |
| 120 | + const mockFetch = setupMockFetch(mockResponse, mockStream); | |
| 121 | + setupReadableStreamPolyfill(); | |
| 122 | + | |
| 123 | + (llm as any).fetch = mockFetch; | |
| 124 | + | |
| 125 | + // Disable OpenAI adapter to use our custom fetch mock | |
| 126 | + (llm as any).useOpenAIAdapterFor = []; | |
| 127 | + | |
| 128 | + await executeLlmMethod(llm, methodToTest, params); | |
| 129 | + assertFetchCall(mockFetch, expectedRequest); | |
| 130 | +} | |
| 131 | + | |
| 132 | +describe("OpenAI", () => { | |
| 133 | + afterEach(() => { | |
| 134 | + vi.clearAllMocks(); | |
| 135 | + }); | |
| 136 | + | |
| 137 | + test("streamChat should send a valid request", async () => { | |
| 138 | + const openai = new OpenAI({ | |
| 139 | + apiKey: "test-api-key", | |
| 140 | + model: "gpt-4", | |
| 141 | + apiBase: "https://api.openai.com/v1/", | |
| 142 | + }); | |
| 143 | + | |
| 144 | + await runLlmTest({ | |
| 145 | + llm: openai, | |
| 146 | + methodToTest: "streamChat", | |
| 147 | + params: [ | |
| 148 | + [{ role: "user", content: "hello" }], | |
| 149 | + new AbortController().signal, | |
| 150 | + ], | |
| 151 | + expectedRequest: { | |
| 152 | + url: "https://api.openai.com/v1/chat/completions", | |
| 153 | + method: "POST", | |
| 154 | + headers: { | |
| 155 | + "Content-Type": "application/json", | |
| 156 | + Authorization: "Bearer test-api-key", | |
| 157 | + "api-key": "test-api-key", | |
| 158 | + }, | |
| 159 | + body: { | |
| 160 | + model: "gpt-4", | |
| 161 | + messages: [{ role: "user", content: "hello" }], | |
| 162 | + stream: true, | |
| 163 | + max_tokens: 2048, | |
| 164 | + }, | |
| 165 | + }, | |
| 166 | + mockStream: [ | |
| 167 | + { choices: [{ delta: { content: "Hello" } }] }, | |
| 168 | + { choices: [{ delta: { content: " world" } }] }, | |
| 169 | + ], | |
| 170 | + }); | |
| 171 | + }); | |
| 172 | + | |
| 173 | + test("chat should send a valid request", async () => { | |
| 174 | + const openai = new OpenAI({ | |
| 175 | + apiKey: "test-api-key", | |
| 176 | + model: "gpt-4", | |
| 177 | + apiBase: "https://api.openai.com/v1/", | |
| 178 | + }); | |
| 179 | + | |
| 180 | + await runLlmTest({ | |
| 181 | + llm: openai, | |
| 182 | + methodToTest: "chat", | |
| 183 | + params: [ | |
| 184 | + [{ role: "user", content: "hello" }], | |
| 185 | + new AbortController().signal, | |
| 186 | + ], | |
| 187 | + expectedRequest: { | |
| 188 | + url: "https://api.openai.com/v1/chat/completions", | |
| 189 | + method: "POST", | |
| 190 | + headers: { | |
| 191 | + "Content-Type": "application/json", | |
| 192 | + Authorization: "Bearer test-api-key", | |
| 193 | + "api-key": "test-api-key", | |
| 194 | + }, | |
| 195 | + body: { | |
| 196 | + model: "gpt-4", | |
| 197 | + messages: [{ role: "user", content: "hello" }], | |
| 198 | + stream: true, | |
| 199 | + max_tokens: 2048, | |
| 200 | + }, | |
| 201 | + }, | |
| 202 | + mockStream: [ | |
| 203 | + { choices: [{ delta: { content: "Hello" } }] }, | |
| 204 | + { choices: [{ delta: { content: " world" } }] }, | |
| 205 | + ], | |
| 206 | + }); | |
| 207 | + }); | |
| 208 | + | |
| 209 | + test("streamComplete should send a valid request", async () => { | |
| 210 | + const openai = new OpenAI({ | |
| 211 | + apiKey: "test-api-key", | |
| 212 | + model: "gpt-4", | |
| 213 | + apiBase: "https://api.openai.com/v1/", | |
| 214 | + }); | |
| 215 | + | |
| 216 | + await runLlmTest({ | |
| 217 | + llm: openai, | |
| 218 | + methodToTest: "streamComplete", | |
| 219 | + params: ["Hello", new AbortController().signal], | |
| 220 | + expectedRequest: { | |
| 221 | + url: "https://api.openai.com/v1/chat/completions", | |
| 222 | + method: "POST", | |
| 223 | + headers: { | |
| 224 | + "Content-Type": "application/json", | |
| 225 | + Authorization: "Bearer test-api-key", | |
| 226 | + "api-key": "test-api-key", | |
| 227 | + }, | |
| 228 | + body: { | |
| 229 | + model: "gpt-4", | |
| 230 | + messages: [{ role: "user", content: "Hello" }], | |
| 231 | + stream: true, | |
| 232 | + max_tokens: 2048, | |
| 233 | + }, | |
| 234 | + }, | |
| 235 | + mockStream: [ | |
| 236 | + { choices: [{ delta: { content: "Hello" } }] }, | |
| 237 | + { choices: [{ delta: { content: " world" } }] }, | |
| 238 | + ], | |
| 239 | + }); | |
| 240 | + }); | |
| 241 | + | |
| 242 | + test("complete should send a valid request", async () => { | |
| 243 | + const openai = new OpenAI({ | |
| 244 | + apiKey: "test-api-key", | |
| 245 | + model: "gpt-4", | |
| 246 | + apiBase: "https://api.openai.com/v1/", | |
| 247 | + }); | |
| 248 | + | |
| 249 | + await runLlmTest({ | |
| 250 | + llm: openai, | |
| 251 | + methodToTest: "complete", | |
| 252 | + params: ["Hello", new AbortController().signal], | |
| 253 | + expectedRequest: { | |
| 254 | + url: "https://api.openai.com/v1/chat/completions", | |
| 255 | + method: "POST", | |
| 256 | + headers: { | |
| 257 | + "Content-Type": "application/json", | |
| 258 | + Authorization: "Bearer test-api-key", | |
| 259 | + "api-key": "test-api-key", | |
| 260 | + }, | |
| 261 | + body: { | |
| 262 | + model: "gpt-4", | |
| 263 | + messages: [{ role: "user", content: "Hello" }], | |
| 264 | + stream: true, | |
| 265 | + max_tokens: 2048, | |
| 266 | + }, | |
| 267 | + }, | |
| 268 | + mockStream: [ | |
| 269 | + { choices: [{ delta: { content: "Hello" } }] }, | |
| 270 | + { choices: [{ delta: { content: " world" } }] }, | |
| 271 | + ], | |
| 272 | + }); | |
| 273 | + }); | |
| 274 | + | |
| 275 | + test("should handle O1 models correctly", async () => { | |
| 276 | + const openai = new OpenAI({ | |
| 277 | + apiKey: "test-api-key", | |
| 278 | + model: "o1-preview", | |
| 279 | + apiBase: "https://api.openai.com/v1/", | |
| 280 | + }); | |
| 281 | + | |
| 282 | + await runLlmTest({ | |
| 283 | + llm: openai, | |
| 284 | + methodToTest: "chat", | |
| 285 | + params: [ | |
| 286 | + [{ role: "user", content: "hello" }], | |
| 287 | + new AbortController().signal, | |
| 288 | + { maxTokens: 100 }, | |
| 289 | + ], | |
| 290 | + expectedRequest: { | |
| 291 | + url: "https://api.openai.com/v1/chat/completions", | |
| 292 | + method: "POST", | |
| 293 | + headers: { | |
| 294 | + "Content-Type": "application/json", | |
| 295 | + Authorization: "Bearer test-api-key", | |
| 296 | + "api-key": "test-api-key", | |
| 297 | + }, | |
| 298 | + body: { | |
| 299 | + model: "o1-preview", | |
| 300 | + messages: [{ role: "user", content: "hello" }], | |
| 301 | + stream: true, | |
| 302 | + max_completion_tokens: 100, | |
| 303 | + }, | |
| 304 | + }, | |
| 305 | + mockStream: [{ choices: [{ delta: { content: "Hello world" } }] }], | |
| 306 | + }); | |
| 307 | + }); | |
| 308 | + | |
| 309 | + test("should handle tools", async () => { | |
| 310 | + const openai = new OpenAI({ | |
| 311 | + apiKey: "test-api-key", | |
| 312 | + model: "gpt-4", | |
| 313 | + apiBase: "https://api.openai.com/v1/", | |
| 314 | + }); | |
| 315 | + | |
| 316 | + const tools = [ | |
| 317 | + { | |
| 318 | + type: "function" as const, | |
| 319 | + function: { | |
| 320 | + name: "test_function", | |
| 321 | + description: "Test function", | |
| 322 | + parameters: { type: "object", properties: {} }, | |
| 323 | + }, | |
| 324 | + }, | |
| 325 | + ]; | |
| 326 | + | |
| 327 | + await runLlmTest({ | |
| 328 | + llm: openai, | |
| 329 | + methodToTest: "chat", | |
| 330 | + params: [ | |
| 331 | + [{ role: "user", content: "hello" }], | |
| 332 | + new AbortController().signal, | |
| 333 | + { tools }, | |
| 334 | + ], | |
| 335 | + expectedRequest: { | |
| 336 | + url: "https://api.openai.com/v1/chat/completions", | |
| 337 | + method: "POST", | |
| 338 | + headers: { | |
| 339 | + "Content-Type": "application/json", | |
| 340 | + Authorization: "Bearer test-api-key", | |
| 341 | + "api-key": "test-api-key", | |
| 342 | + }, | |
| 343 | + body: { | |
| 344 | + model: "gpt-4", | |
| 345 | + messages: [{ role: "user", content: "hello" }], | |
| 346 | + stream: true, | |
| 347 | + max_tokens: 2048, | |
| 348 | + tools: [ | |
| 349 | + { | |
| 350 | + type: "function", | |
| 351 | + function: { | |
| 352 | + name: "test_function", | |
| 353 | + description: "Test function", | |
| 354 | + parameters: { type: "object", properties: {} }, | |
| 355 | + }, | |
| 356 | + }, | |
| 357 | + ], | |
| 358 | + }, | |
| 359 | + }, | |
| 360 | + mockStream: [{ choices: [{ delta: { content: "I'll help you" } }] }], | |
| 361 | + }); | |
| 362 | + }); | |
| 363 | + | |
| 364 | + test("should handle custom max tokens", async () => { | |
| 365 | + const openai = new OpenAI({ | |
| 366 | + apiKey: "test-api-key", | |
| 367 | + model: "gpt-4", | |
| 368 | + apiBase: "https://api.openai.com/v1/", | |
| 369 | + }); | |
| 370 | + | |
| 371 | + await runLlmTest({ | |
| 372 | + llm: openai, | |
| 373 | + methodToTest: "chat", | |
| 374 | + params: [ | |
| 375 | + [{ role: "user", content: "hello" }], | |
| 376 | + new AbortController().signal, | |
| 377 | + { maxTokens: 500 }, | |
| 378 | + ], | |
| 379 | + expectedRequest: { | |
| 380 | + url: "https://api.openai.com/v1/chat/completions", | |
| 381 | + method: "POST", | |
| 382 | + headers: { | |
| 383 | + "Content-Type": "application/json", | |
| 384 | + Authorization: "Bearer test-api-key", | |
| 385 | + "api-key": "test-api-key", | |
| 386 | + }, | |
| 387 | + body: { | |
| 388 | + model: "gpt-4", | |
| 389 | + messages: [{ role: "user", content: "hello" }], | |
| 390 | + stream: true, | |
| 391 | + max_tokens: 500, | |
| 392 | + }, | |
| 393 | + }, | |
| 394 | + mockStream: [{ choices: [{ delta: { content: "Hello" } }] }], | |
| 395 | + }); | |
| 396 | + }); | |
| 397 | + | |
| 398 | + test("should handle embeddings", async () => { | |
| 399 | + const openai = new OpenAI({ | |
| 400 | + apiKey: "test-api-key", | |
| 401 | + model: "text-embedding-ada-002", | |
| 402 | + apiBase: "https://api.openai.com/v1/", | |
| 403 | + }); | |
| 404 | + | |
| 405 | + await runLlmTest({ | |
| 406 | + llm: openai, | |
| 407 | + methodToTest: "embed", | |
| 408 | + params: [["Hello", "World"]], | |
| 409 | + expectedRequest: { | |
| 410 | + url: "https://api.openai.com/v1/embeddings", | |
| 411 | + method: "POST", | |
| 412 | + headers: { | |
| 413 | + Authorization: "Bearer test-api-key", | |
| 414 | + "Content-Type": "application/json", | |
| 415 | + "api-key": "test-api-key", | |
| 416 | + }, | |
| 417 | + body: { | |
| 418 | + input: ["Hello", "World"], | |
| 419 | + model: "text-embedding-ada-002", | |
| 420 | + }, | |
| 421 | + }, | |
| 422 | + mockResponse: { | |
| 423 | + data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }], | |
| 424 | + }, | |
| 425 | + }); | |
| 426 | + }); | |
| 427 | +}); |
modified core/llm/llms/Venice.ts +1 −1
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | class Venice extends OpenAI { |
| 7 | 7 | static providerName = "venice"; |
| 8 | 8 | static defaultOptions: Partial<LLMOptions> = { |
| 9 | - apiBase: "https://api.venice.ai/api/v1", | |
| 9 | + apiBase: "https://api.venice.ai/api/v1/", | |
| 10 | 10 | }; |
| 11 | 11 | |
| 12 | 12 | protected _convertArgs( |
added core/llm/llms/llmTestHarness.ts +93 −0
| @@ -0,0 +1,93 @@ | ||
| 1 | +import { expect, jest } from "@jest/globals"; | |
| 2 | +import { ILLM } from "../../index.js"; | |
| 3 | + | |
| 4 | +export interface LlmTestCase { | |
| 5 | + llm: ILLM; | |
| 6 | + methodToTest: keyof ILLM; | |
| 7 | + params: any[]; | |
| 8 | + expectedRequest: { | |
| 9 | + url: string; | |
| 10 | + method: string; | |
| 11 | + headers?: Record<string, string>; | |
| 12 | + body?: Record<string, any>; | |
| 13 | + }; | |
| 14 | + mockResponse?: any; | |
| 15 | + mockStream?: string[]; // array of string chunks for SSE | |
| 16 | +} | |
| 17 | + | |
| 18 | +export async function runLlmTest(testCase: LlmTestCase) { | |
| 19 | + const { | |
| 20 | + llm, | |
| 21 | + methodToTest, | |
| 22 | + params, | |
| 23 | + expectedRequest, | |
| 24 | + mockResponse, | |
| 25 | + mockStream, | |
| 26 | + } = testCase; | |
| 27 | + | |
| 28 | + const mockFetch = jest.fn<any>(); | |
| 29 | + | |
| 30 | + if (mockStream) { | |
| 31 | + const encoder = new TextEncoder(); | |
| 32 | + let streamIndex = 0; | |
| 33 | + mockFetch.mockResolvedValue( | |
| 34 | + new Response( | |
| 35 | + new ReadableStream({ | |
| 36 | + start(controller) { | |
| 37 | + mockStream.forEach((chunk) => { | |
| 38 | + controller.enqueue(new TextEncoder().encode(chunk)); | |
| 39 | + }); | |
| 40 | + controller.close(); | |
| 41 | + }, | |
| 42 | + }), | |
| 43 | + { | |
| 44 | + headers: { | |
| 45 | + "Content-Type": "text/event-stream", | |
| 46 | + }, | |
| 47 | + }, | |
| 48 | + ), | |
| 49 | + ); | |
| 50 | + } else { | |
| 51 | + mockFetch.mockResolvedValue( | |
| 52 | + new Response(JSON.stringify(mockResponse), { | |
| 53 | + headers: { | |
| 54 | + "Content-Type": "application/json", | |
| 55 | + }, | |
| 56 | + }), | |
| 57 | + ); | |
| 58 | + } | |
| 59 | + | |
| 60 | + // @ts-ignore | |
| 61 | + llm.fetch = mockFetch; | |
| 62 | + | |
| 63 | + // @ts-ignore | |
| 64 | + if (typeof llm[methodToTest] !== "function") { | |
| 65 | + throw new Error( | |
| 66 | + `Method ${String(methodToTest)} does not exist on the LLM instance.`, | |
| 67 | + ); | |
| 68 | + } | |
| 69 | + | |
| 70 | + // @ts-ignore | |
| 71 | + const result = await llm[methodToTest](...params); | |
| 72 | + | |
| 73 | + if (mockStream) { | |
| 74 | + // Consume the stream to ensure it's processed correctly | |
| 75 | + for await (const _ of result) { | |
| 76 | + } | |
| 77 | + } | |
| 78 | + | |
| 79 | + expect(mockFetch).toHaveBeenCalledTimes(1); | |
| 80 | + const [url, options] = mockFetch.mock.calls[0] as [string, RequestInit]; | |
| 81 | + | |
| 82 | + expect(url.toString()).toBe(expectedRequest.url); | |
| 83 | + expect(options.method).toBe(expectedRequest.method); | |
| 84 | + | |
| 85 | + if (expectedRequest.headers) { | |
| 86 | + expect(options.headers).toEqual(expectedRequest.headers); | |
| 87 | + } | |
| 88 | + | |
| 89 | + if (expectedRequest.body) { | |
| 90 | + const actualBody = JSON.parse(options.body as string); | |
| 91 | + expect(actualBody).toEqual(expectedRequest.body); | |
| 92 | + } | |
| 93 | +} |
added core/llm/llms/stubs/ContinueProxy.vitest.ts +758 −0
| @@ -0,0 +1,758 @@ | ||
| 1 | +import { afterEach, describe, expect, test, vi } from "vitest"; | |
| 2 | +import { ILLM } from "../../../index.js"; | |
| 3 | +import ContinueProxy from "./ContinueProxy.js"; | |
| 4 | + | |
| 5 | +vi.mock("@continuedev/config-yaml", async (importOriginal) => { | |
| 6 | + const mod = (await importOriginal()) as any; | |
| 7 | + return { | |
| 8 | + ...mod, | |
| 9 | + parseProxyModelName: vi.fn(() => ({ | |
| 10 | + provider: "test-provider", | |
| 11 | + model: "test-model", | |
| 12 | + ownerSlug: "test-owner", | |
| 13 | + packageSlug: "test-package", | |
| 14 | + })), | |
| 15 | + }; | |
| 16 | +}); | |
| 17 | + | |
| 18 | +interface LlmTestCase { | |
| 19 | + llm: ILLM; | |
| 20 | + methodToTest: keyof ILLM; | |
| 21 | + params: any[]; | |
| 22 | + expectedRequest: { | |
| 23 | + url: string; | |
| 24 | + method: string; | |
| 25 | + headers?: Record<string, string>; | |
| 26 | + body?: Record<string, any>; | |
| 27 | + }; | |
| 28 | + mockResponse?: any; | |
| 29 | + mockStream?: any[]; | |
| 30 | +} | |
| 31 | + | |
| 32 | +function createMockStream(mockStream: any[]) { | |
| 33 | + const encoder = new TextEncoder(); | |
| 34 | + return new ReadableStream({ | |
| 35 | + start(controller) { | |
| 36 | + for (const chunk of mockStream) { | |
| 37 | + controller.enqueue( | |
| 38 | + encoder.encode( | |
| 39 | + `data: ${ | |
| 40 | + typeof chunk === "string" ? chunk : JSON.stringify(chunk) | |
| 41 | + }\n\n`, | |
| 42 | + ), | |
| 43 | + ); | |
| 44 | + } | |
| 45 | + controller.close(); | |
| 46 | + }, | |
| 47 | + }); | |
| 48 | +} | |
| 49 | + | |
| 50 | +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { | |
| 51 | + const mockFetch = vi.fn(); | |
| 52 | + | |
| 53 | + if (mockStream) { | |
| 54 | + const stream = createMockStream(mockStream); | |
| 55 | + mockFetch.mockResolvedValue( | |
| 56 | + new Response(stream, { | |
| 57 | + headers: { | |
| 58 | + "Content-Type": "text/event-stream", | |
| 59 | + }, | |
| 60 | + }), | |
| 61 | + ); | |
| 62 | + } else { | |
| 63 | + mockFetch.mockResolvedValue( | |
| 64 | + new Response(JSON.stringify(mockResponse), { | |
| 65 | + headers: { "Content-Type": "application/json" }, | |
| 66 | + }), | |
| 67 | + ); | |
| 68 | + } | |
| 69 | + | |
| 70 | + return mockFetch; | |
| 71 | +} | |
| 72 | + | |
| 73 | +function setupReadableStreamPolyfill() { | |
| 74 | + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved | |
| 75 | + // @ts-ignore | |
| 76 | + const originalFrom = ReadableStream.from; | |
| 77 | + // @ts-ignore | |
| 78 | + ReadableStream.from = (body) => { | |
| 79 | + if (body?.source) { | |
| 80 | + return body; | |
| 81 | + } | |
| 82 | + return originalFrom(body); | |
| 83 | + }; | |
| 84 | +} | |
| 85 | + | |
| 86 | +async function executeLlmMethod( | |
| 87 | + llm: ILLM, | |
| 88 | + methodToTest: keyof ILLM, | |
| 89 | + params: any[], | |
| 90 | +) { | |
| 91 | + if (typeof (llm as any)[methodToTest] !== "function") { | |
| 92 | + throw new Error( | |
| 93 | + `Method ${String(methodToTest)} does not exist on the LLM instance.`, | |
| 94 | + ); | |
| 95 | + } | |
| 96 | + | |
| 97 | + const result = await (llm as any)[methodToTest](...params); | |
| 98 | + if (result?.next) { | |
| 99 | + for await (const _ of result) { | |
| 100 | + } | |
| 101 | + } | |
| 102 | +} | |
| 103 | + | |
| 104 | +function assertFetchCall(mockFetch: any, expectedRequest: any) { | |
| 105 | + expect(mockFetch).toHaveBeenCalledTimes(1); | |
| 106 | + const [url, options] = mockFetch.mock.calls[0]; | |
| 107 | + | |
| 108 | + expect(url.toString()).toBe(expectedRequest.url); | |
| 109 | + expect(options.method).toBe(expectedRequest.method); | |
| 110 | + | |
| 111 | + if (expectedRequest.headers) { | |
| 112 | + expect(options.headers).toEqual( | |
| 113 | + expect.objectContaining(expectedRequest.headers), | |
| 114 | + ); | |
| 115 | + } | |
| 116 | + | |
| 117 | + if (expectedRequest.body) { | |
| 118 | + const actualBody = JSON.parse(options.body as string); | |
| 119 | + expect(actualBody).toEqual(expectedRequest.body); | |
| 120 | + } | |
| 121 | +} | |
| 122 | + | |
| 123 | +async function runLlmTest(testCase: LlmTestCase) { | |
| 124 | + const { | |
| 125 | + llm, | |
| 126 | + methodToTest, | |
| 127 | + params, | |
| 128 | + expectedRequest, | |
| 129 | + mockResponse, | |
| 130 | + mockStream, | |
| 131 | + } = testCase; | |
| 132 | + | |
| 133 | + const mockFetch = setupMockFetch(mockResponse, mockStream); | |
| 134 | + setupReadableStreamPolyfill(); | |
| 135 | + | |
| 136 | + (llm as any).fetch = mockFetch; | |
| 137 | + | |
| 138 | + await executeLlmMethod(llm, methodToTest, params); | |
| 139 | + assertFetchCall(mockFetch, expectedRequest); | |
| 140 | +} | |
| 141 | + | |
| 142 | +describe("ContinueProxy", () => { | |
| 143 | + afterEach(() => { | |
| 144 | + vi.clearAllMocks(); | |
| 145 | + }); | |
| 146 | + | |
| 147 | + test("rerank should send a valid request", async () => { | |
| 148 | + const proxy = new ContinueProxy({ | |
| 149 | + apiKey: "test-api-key", | |
| 150 | + model: "test-model", | |
| 151 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 152 | + }); | |
| 153 | + | |
| 154 | + await runLlmTest({ | |
| 155 | + llm: proxy, | |
| 156 | + methodToTest: "rerank", | |
| 157 | + params: [ | |
| 158 | + "test query", | |
| 159 | + [{ content: "document1" }, { content: "document2" }], | |
| 160 | + ], | |
| 161 | + expectedRequest: { | |
| 162 | + url: "https://proxy.continue.dev/model-proxy/v1/rerank", | |
| 163 | + method: "POST", | |
| 164 | + headers: { | |
| 165 | + "Content-Type": "application/json", | |
| 166 | + Authorization: "Bearer test-api-key", | |
| 167 | + }, | |
| 168 | + body: { | |
| 169 | + query: "test query", | |
| 170 | + documents: ["document1", "document2"], | |
| 171 | + model: "test-model", | |
| 172 | + continueProperties: { | |
| 173 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 174 | + orgScopeId: null, | |
| 175 | + }, | |
| 176 | + }, | |
| 177 | + }, | |
| 178 | + mockResponse: { | |
| 179 | + data: [ | |
| 180 | + { index: 0, relevance_score: 0.9 }, | |
| 181 | + { index: 1, relevance_score: 0.1 }, | |
| 182 | + ], | |
| 183 | + }, | |
| 184 | + }); | |
| 185 | + }); | |
| 186 | + | |
| 187 | + test("streamChat should send a valid request", async () => { | |
| 188 | + const proxy = new ContinueProxy({ | |
| 189 | + apiKey: "test-api-key", | |
| 190 | + model: "test-model", | |
| 191 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 192 | + }); | |
| 193 | + | |
| 194 | + await runLlmTest({ | |
| 195 | + llm: proxy, | |
| 196 | + methodToTest: "streamChat", | |
| 197 | + params: [[{ role: "user", content: "hello" }]], | |
| 198 | + expectedRequest: { | |
| 199 | + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", | |
| 200 | + method: "POST", | |
| 201 | + headers: { | |
| 202 | + "Content-Type": "application/json", | |
| 203 | + Authorization: "Bearer test-api-key", | |
| 204 | + "api-key": "test-api-key", | |
| 205 | + "x-continue-unique-id": "NOT_UNIQUE", | |
| 206 | + }, | |
| 207 | + body: { | |
| 208 | + model: "test-model", | |
| 209 | + messages: [{ role: "user", content: "hello" }], | |
| 210 | + max_tokens: 4096, | |
| 211 | + stream: true, | |
| 212 | + continueProperties: { | |
| 213 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 214 | + orgScopeId: null, | |
| 215 | + }, | |
| 216 | + }, | |
| 217 | + }, | |
| 218 | + mockStream: [ | |
| 219 | + '{"choices": [{"delta": {"content": "response"}}]}', | |
| 220 | + "[DONE]", | |
| 221 | + ], | |
| 222 | + }); | |
| 223 | + }); | |
| 224 | + | |
| 225 | + test("chat should send a valid request", async () => { | |
| 226 | + const proxy = new ContinueProxy({ | |
| 227 | + apiKey: "test-api-key", | |
| 228 | + model: "test-model", | |
| 229 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 230 | + }); | |
| 231 | + | |
| 232 | + await runLlmTest({ | |
| 233 | + llm: proxy, | |
| 234 | + methodToTest: "chat", | |
| 235 | + params: [[{ role: "user", content: "hello" }]], | |
| 236 | + expectedRequest: { | |
| 237 | + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", | |
| 238 | + method: "POST", | |
| 239 | + headers: { | |
| 240 | + "Content-Type": "application/json", | |
| 241 | + Authorization: "Bearer test-api-key", | |
| 242 | + "api-key": "test-api-key", | |
| 243 | + "x-continue-unique-id": "NOT_UNIQUE", | |
| 244 | + }, | |
| 245 | + body: { | |
| 246 | + model: "test-model", | |
| 247 | + messages: [{ role: "user", content: "hello" }], | |
| 248 | + max_tokens: 4096, | |
| 249 | + stream: true, | |
| 250 | + continueProperties: { | |
| 251 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 252 | + orgScopeId: null, | |
| 253 | + }, | |
| 254 | + }, | |
| 255 | + }, | |
| 256 | + mockStream: [ | |
| 257 | + '{"choices": [{"delta": {"content": "Hello! How can I help you today?"}}]}', | |
| 258 | + "[DONE]", | |
| 259 | + ], | |
| 260 | + }); | |
| 261 | + }); | |
| 262 | + | |
| 263 | + test("streamComplete should send a valid request", async () => { | |
| 264 | + const proxy = new ContinueProxy({ | |
| 265 | + apiKey: "test-api-key", | |
| 266 | + model: "test-model", | |
| 267 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 268 | + }); | |
| 269 | + | |
| 270 | + await runLlmTest({ | |
| 271 | + llm: proxy, | |
| 272 | + methodToTest: "streamComplete", | |
| 273 | + params: ["Complete this: Hello"], | |
| 274 | + expectedRequest: { | |
| 275 | + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", | |
| 276 | + method: "POST", | |
| 277 | + headers: { | |
| 278 | + "Content-Type": "application/json", | |
| 279 | + Authorization: "Bearer test-api-key", | |
| 280 | + "api-key": "test-api-key", | |
| 281 | + "x-continue-unique-id": "NOT_UNIQUE", | |
| 282 | + }, | |
| 283 | + body: { | |
| 284 | + model: "test-model", | |
| 285 | + messages: [{ role: "user", content: "Complete this: Hello" }], | |
| 286 | + max_tokens: 4096, | |
| 287 | + stream: true, | |
| 288 | + continueProperties: { | |
| 289 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 290 | + orgScopeId: null, | |
| 291 | + }, | |
| 292 | + }, | |
| 293 | + }, | |
| 294 | + mockStream: [ | |
| 295 | + '{"choices": [{"delta": {"content": " world!"}}]}', | |
| 296 | + "[DONE]", | |
| 297 | + ], | |
| 298 | + }); | |
| 299 | + }); | |
| 300 | + | |
| 301 | + test("complete should send a valid request", async () => { | |
| 302 | + const proxy = new ContinueProxy({ | |
| 303 | + apiKey: "test-api-key", | |
| 304 | + model: "test-model", | |
| 305 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 306 | + }); | |
| 307 | + | |
| 308 | + await runLlmTest({ | |
| 309 | + llm: proxy, | |
| 310 | + methodToTest: "complete", | |
| 311 | + params: ["Complete this: Hello"], | |
| 312 | + expectedRequest: { | |
| 313 | + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", | |
| 314 | + method: "POST", | |
| 315 | + headers: { | |
| 316 | + "Content-Type": "application/json", | |
| 317 | + Authorization: "Bearer test-api-key", | |
| 318 | + "api-key": "test-api-key", | |
| 319 | + "x-continue-unique-id": "NOT_UNIQUE", | |
| 320 | + }, | |
| 321 | + body: { | |
| 322 | + model: "test-model", | |
| 323 | + messages: [{ role: "user", content: "Complete this: Hello" }], | |
| 324 | + max_tokens: 4096, | |
| 325 | + stream: true, | |
| 326 | + continueProperties: { | |
| 327 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 328 | + orgScopeId: null, | |
| 329 | + }, | |
| 330 | + }, | |
| 331 | + }, | |
| 332 | + mockStream: [ | |
| 333 | + '{"choices": [{"delta": {"content": " world!"}}]}', | |
| 334 | + "[DONE]", | |
| 335 | + ], | |
| 336 | + }); | |
| 337 | + }); | |
| 338 | + | |
| 339 | + test("streamFim should send a valid request", async () => { | |
| 340 | + const proxy = new ContinueProxy({ | |
| 341 | + apiKey: "test-api-key", | |
| 342 | + model: "test-model", | |
| 343 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 344 | + }); | |
| 345 | + | |
| 346 | + await runLlmTest({ | |
| 347 | + llm: proxy, | |
| 348 | + methodToTest: "streamFim", | |
| 349 | + params: ["function test() {\n ", "\n}"], | |
| 350 | + expectedRequest: { | |
| 351 | + url: "https://proxy.continue.dev/model-proxy/v1/fim/completions", | |
| 352 | + method: "POST", | |
| 353 | + headers: { | |
| 354 | + "Content-Type": "application/json", | |
| 355 | + Accept: "application/json", | |
| 356 | + "x-api-key": "test-api-key", | |
| 357 | + Authorization: "Bearer test-api-key", | |
| 358 | + }, | |
| 359 | + body: { | |
| 360 | + model: "test-model", | |
| 361 | + prompt: "function test() {\n ", | |
| 362 | + suffix: "\n}", | |
| 363 | + max_tokens: 4096, | |
| 364 | + stream: true, | |
| 365 | + continueProperties: { | |
| 366 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 367 | + orgScopeId: null, | |
| 368 | + }, | |
| 369 | + }, | |
| 370 | + }, | |
| 371 | + mockStream: [ | |
| 372 | + '{"choices": [{"delta": {"content": "console.log("Hello");"}}]}', | |
| 373 | + "[DONE]", | |
| 374 | + ], | |
| 375 | + }); | |
| 376 | + }); | |
| 377 | + | |
| 378 | + test("embed should send a valid request", async () => { | |
| 379 | + const proxy = new ContinueProxy({ | |
| 380 | + apiKey: "test-api-key", | |
| 381 | + model: "test-model", | |
| 382 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 383 | + }); | |
| 384 | + | |
| 385 | + await runLlmTest({ | |
| 386 | + llm: proxy, | |
| 387 | + methodToTest: "embed", | |
| 388 | + params: [["text to embed", "another text"]], | |
| 389 | + expectedRequest: { | |
| 390 | + url: "https://proxy.continue.dev/model-proxy/v1/embeddings", | |
| 391 | + method: "POST", | |
| 392 | + headers: { | |
| 393 | + "Content-Type": "application/json", | |
| 394 | + Authorization: "Bearer test-api-key", | |
| 395 | + "api-key": "test-api-key", | |
| 396 | + }, | |
| 397 | + body: { | |
| 398 | + input: ["text to embed", "another text"], | |
| 399 | + model: "test-model", | |
| 400 | + continueProperties: { | |
| 401 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 402 | + orgScopeId: null, | |
| 403 | + }, | |
| 404 | + }, | |
| 405 | + }, | |
| 406 | + mockResponse: { | |
| 407 | + data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }], | |
| 408 | + }, | |
| 409 | + }); | |
| 410 | + }); | |
| 411 | + | |
| 412 | + test("listModels should send a valid request", async () => { | |
| 413 | + const proxy = new ContinueProxy({ | |
| 414 | + apiKey: "test-api-key", | |
| 415 | + model: "test-model", | |
| 416 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 417 | + }); | |
| 418 | + | |
| 419 | + await runLlmTest({ | |
| 420 | + llm: proxy, | |
| 421 | + methodToTest: "listModels", | |
| 422 | + params: [], | |
| 423 | + expectedRequest: { | |
| 424 | + url: "https://proxy.continue.dev/model-proxy/v1/models", | |
| 425 | + method: "GET", | |
| 426 | + headers: { | |
| 427 | + "Content-Type": "application/json", | |
| 428 | + Authorization: "Bearer test-api-key", | |
| 429 | + "api-key": "test-api-key", | |
| 430 | + }, | |
| 431 | + }, | |
| 432 | + mockResponse: { | |
| 433 | + data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }], | |
| 434 | + }, | |
| 435 | + }); | |
| 436 | + }); | |
| 437 | + | |
| 438 | + describe("Different provider configurations", () => { | |
| 439 | + test("should handle on-prem proxy URL", async () => { | |
| 440 | + const proxy = new ContinueProxy({ | |
| 441 | + apiKey: "test-api-key", | |
| 442 | + model: "test-model", | |
| 443 | + onPremProxyUrl: "https://my-proxy.company.com/", | |
| 444 | + }); | |
| 445 | + | |
| 446 | + await runLlmTest({ | |
| 447 | + llm: proxy, | |
| 448 | + methodToTest: "rerank", | |
| 449 | + params: [ | |
| 450 | + "test query", | |
| 451 | + [{ content: "document1" }, { content: "document2" }], | |
| 452 | + ], | |
| 453 | + expectedRequest: { | |
| 454 | + url: "https://my-proxy.company.com/model-proxy/v1/rerank", | |
| 455 | + method: "POST", | |
| 456 | + headers: { | |
| 457 | + "Content-Type": "application/json", | |
| 458 | + Authorization: "Bearer test-api-key", | |
| 459 | + }, | |
| 460 | + body: { | |
| 461 | + query: "test query", | |
| 462 | + documents: ["document1", "document2"], | |
| 463 | + model: "test-model", | |
| 464 | + continueProperties: { | |
| 465 | + apiBase: undefined, | |
| 466 | + apiKeyLocation: undefined, | |
| 467 | + env: undefined, | |
| 468 | + envSecretLocations: undefined, | |
| 469 | + orgScopeId: null, | |
| 470 | + }, | |
| 471 | + }, | |
| 472 | + }, | |
| 473 | + mockResponse: { | |
| 474 | + data: [ | |
| 475 | + { index: 0, relevance_score: 0.9 }, | |
| 476 | + { index: 1, relevance_score: 0.1 }, | |
| 477 | + ], | |
| 478 | + }, | |
| 479 | + }); | |
| 480 | + }); | |
| 481 | + | |
| 482 | + test("should handle environment variables", async () => { | |
| 483 | + const proxy = new ContinueProxy({ | |
| 484 | + apiKey: "test-api-key", | |
| 485 | + model: "test-model", | |
| 486 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 487 | + env: { | |
| 488 | + CUSTOM_VAR: "custom-value", | |
| 489 | + ANOTHER_VAR: "another-value", | |
| 490 | + }, | |
| 491 | + }); | |
| 492 | + | |
| 493 | + await runLlmTest({ | |
| 494 | + llm: proxy, | |
| 495 | + methodToTest: "streamChat", | |
| 496 | + params: [[{ role: "user", content: "hello" }]], | |
| 497 | + expectedRequest: { | |
| 498 | + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", | |
| 499 | + method: "POST", | |
| 500 | + headers: { | |
| 501 | + "Content-Type": "application/json", | |
| 502 | + Authorization: "Bearer test-api-key", | |
| 503 | + "api-key": "test-api-key", | |
| 504 | + "x-continue-unique-id": "NOT_UNIQUE", | |
| 505 | + }, | |
| 506 | + body: { | |
| 507 | + model: "test-model", | |
| 508 | + messages: [{ role: "user", content: "hello" }], | |
| 509 | + max_tokens: 4096, | |
| 510 | + stream: true, | |
| 511 | + continueProperties: { | |
| 512 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 513 | + env: { | |
| 514 | + CUSTOM_VAR: "custom-value", | |
| 515 | + ANOTHER_VAR: "another-value", | |
| 516 | + }, | |
| 517 | + orgScopeId: null, | |
| 518 | + }, | |
| 519 | + }, | |
| 520 | + }, | |
| 521 | + mockStream: [ | |
| 522 | + '{"choices": [{"delta": {"content": "response"}}]}', | |
| 523 | + "[DONE]", | |
| 524 | + ], | |
| 525 | + }); | |
| 526 | + }); | |
| 527 | + | |
| 528 | + test("should handle API key location", async () => { | |
| 529 | + const proxy = new ContinueProxy({ | |
| 530 | + apiKey: "test-api-key", | |
| 531 | + model: "test-model", | |
| 532 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 533 | + apiKeyLocation: "env:OPENAI_API_KEY", | |
| 534 | + }); | |
| 535 | + | |
| 536 | + await runLlmTest({ | |
| 537 | + llm: proxy, | |
| 538 | + methodToTest: "embed", | |
| 539 | + params: [["test text"]], | |
| 540 | + expectedRequest: { | |
| 541 | + url: "https://proxy.continue.dev/model-proxy/v1/embeddings", | |
| 542 | + method: "POST", | |
| 543 | + headers: { | |
| 544 | + "Content-Type": "application/json", | |
| 545 | + Authorization: "Bearer test-api-key", | |
| 546 | + "api-key": "test-api-key", | |
| 547 | + }, | |
| 548 | + body: { | |
| 549 | + input: ["test text"], | |
| 550 | + model: "test-model", | |
| 551 | + continueProperties: { | |
| 552 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 553 | + apiKeyLocation: "env:OPENAI_API_KEY", | |
| 554 | + env: undefined, | |
| 555 | + envSecretLocations: undefined, | |
| 556 | + orgScopeId: null, | |
| 557 | + }, | |
| 558 | + }, | |
| 559 | + }, | |
| 560 | + mockResponse: { | |
| 561 | + data: [{ embedding: [0.1, 0.2, 0.3] }], | |
| 562 | + }, | |
| 563 | + }); | |
| 564 | + }); | |
| 565 | + | |
| 566 | + test("should handle env secret locations", async () => { | |
| 567 | + const proxy = new ContinueProxy({ | |
| 568 | + apiKey: "test-api-key", | |
| 569 | + model: "test-model", | |
| 570 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 571 | + envSecretLocations: { | |
| 572 | + AZURE_API_KEY: "env:AZURE_API_KEY", | |
| 573 | + AZURE_ENDPOINT: "env:AZURE_ENDPOINT", | |
| 574 | + }, | |
| 575 | + }); | |
| 576 | + | |
| 577 | + await runLlmTest({ | |
| 578 | + llm: proxy, | |
| 579 | + methodToTest: "streamFim", | |
| 580 | + params: ["const x = ", ";"], | |
| 581 | + expectedRequest: { | |
| 582 | + url: "https://proxy.continue.dev/model-proxy/v1/fim/completions", | |
| 583 | + method: "POST", | |
| 584 | + headers: { | |
| 585 | + "Content-Type": "application/json", | |
| 586 | + Accept: "application/json", | |
| 587 | + "x-api-key": "test-api-key", | |
| 588 | + Authorization: "Bearer test-api-key", | |
| 589 | + }, | |
| 590 | + body: { | |
| 591 | + model: "test-model", | |
| 592 | + prompt: "const x = ", | |
| 593 | + suffix: ";", | |
| 594 | + max_tokens: 4096, | |
| 595 | + stream: true, | |
| 596 | + continueProperties: { | |
| 597 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 598 | + envSecretLocations: { | |
| 599 | + AZURE_API_KEY: "env:AZURE_API_KEY", | |
| 600 | + AZURE_ENDPOINT: "env:AZURE_ENDPOINT", | |
| 601 | + }, | |
| 602 | + orgScopeId: null, | |
| 603 | + }, | |
| 604 | + }, | |
| 605 | + }, | |
| 606 | + mockStream: ['{"choices": [{"delta": {"content": "42"}}]}', "[DONE]"], | |
| 607 | + }); | |
| 608 | + }); | |
| 609 | + | |
| 610 | + test("should handle organization scope ID", async () => { | |
| 611 | + const proxy = new ContinueProxy({ | |
| 612 | + apiKey: "test-api-key", | |
| 613 | + model: "test-model", | |
| 614 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 615 | + orgScopeId: "org_12345", | |
| 616 | + }); | |
| 617 | + | |
| 618 | + await runLlmTest({ | |
| 619 | + llm: proxy, | |
| 620 | + methodToTest: "listModels", | |
| 621 | + params: [], | |
| 622 | + expectedRequest: { | |
| 623 | + url: "https://proxy.continue.dev/model-proxy/v1/models", | |
| 624 | + method: "GET", | |
| 625 | + headers: { | |
| 626 | + "Content-Type": "application/json", | |
| 627 | + Authorization: "Bearer test-api-key", | |
| 628 | + "api-key": "test-api-key", | |
| 629 | + }, | |
| 630 | + }, | |
| 631 | + mockResponse: { | |
| 632 | + data: [{ id: "gpt-4" }], | |
| 633 | + }, | |
| 634 | + }); | |
| 635 | + }); | |
| 636 | + }); | |
| 637 | + | |
| 638 | + describe("Edge cases", () => { | |
| 639 | + test("should handle empty chunks array for rerank", async () => { | |
| 640 | + const proxy = new ContinueProxy({ | |
| 641 | + apiKey: "test-api-key", | |
| 642 | + model: "test-model", | |
| 643 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 644 | + }); | |
| 645 | + | |
| 646 | + await runLlmTest({ | |
| 647 | + llm: proxy, | |
| 648 | + methodToTest: "rerank", | |
| 649 | + params: ["test query", []], | |
| 650 | + expectedRequest: { | |
| 651 | + url: "https://proxy.continue.dev/model-proxy/v1/rerank", | |
| 652 | + method: "POST", | |
| 653 | + headers: { | |
| 654 | + "Content-Type": "application/json", | |
| 655 | + Authorization: "Bearer test-api-key", | |
| 656 | + }, | |
| 657 | + body: { | |
| 658 | + query: "test query", | |
| 659 | + documents: [], | |
| 660 | + model: "test-model", | |
| 661 | + continueProperties: { | |
| 662 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 663 | + apiKeyLocation: undefined, | |
| 664 | + env: undefined, | |
| 665 | + envSecretLocations: undefined, | |
| 666 | + orgScopeId: null, | |
| 667 | + }, | |
| 668 | + }, | |
| 669 | + }, | |
| 670 | + mockResponse: { | |
| 671 | + data: [], | |
| 672 | + }, | |
| 673 | + }); | |
| 674 | + }); | |
| 675 | + | |
| 676 | + test("should handle complex chat messages", async () => { | |
| 677 | + const proxy = new ContinueProxy({ | |
| 678 | + apiKey: "test-api-key", | |
| 679 | + model: "test-model", | |
| 680 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 681 | + }); | |
| 682 | + | |
| 683 | + const complexMessages = [ | |
| 684 | + { role: "system", content: "You are a helpful assistant." }, | |
| 685 | + { role: "user", content: "Hello!" }, | |
| 686 | + { role: "assistant", content: "Hi there! How can I help you today?" }, | |
| 687 | + { role: "user", content: "What's the weather like?" }, | |
| 688 | + ]; | |
| 689 | + | |
| 690 | + await runLlmTest({ | |
| 691 | + llm: proxy, | |
| 692 | + methodToTest: "streamChat", | |
| 693 | + params: [complexMessages], | |
| 694 | + expectedRequest: { | |
| 695 | + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", | |
| 696 | + method: "POST", | |
| 697 | + headers: { | |
| 698 | + "Content-Type": "application/json", | |
| 699 | + Authorization: "Bearer test-api-key", | |
| 700 | + "api-key": "test-api-key", | |
| 701 | + "x-continue-unique-id": "NOT_UNIQUE", | |
| 702 | + }, | |
| 703 | + body: { | |
| 704 | + model: "test-model", | |
| 705 | + messages: complexMessages, | |
| 706 | + max_tokens: 4096, | |
| 707 | + stream: true, | |
| 708 | + continueProperties: { | |
| 709 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 710 | + orgScopeId: null, | |
| 711 | + }, | |
| 712 | + }, | |
| 713 | + }, | |
| 714 | + mockStream: [ | |
| 715 | + '{"choices": [{"delta": {"content": "I don\'t have access to current weather data."}}]}', | |
| 716 | + "[DONE]", | |
| 717 | + ], | |
| 718 | + }); | |
| 719 | + }); | |
| 720 | + | |
| 721 | + test("should handle single embedding chunk", async () => { | |
| 722 | + const proxy = new ContinueProxy({ | |
| 723 | + apiKey: "test-api-key", | |
| 724 | + model: "test-model", | |
| 725 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 726 | + }); | |
| 727 | + | |
| 728 | + await runLlmTest({ | |
| 729 | + llm: proxy, | |
| 730 | + methodToTest: "embed", | |
| 731 | + params: [["single text"]], | |
| 732 | + expectedRequest: { | |
| 733 | + url: "https://proxy.continue.dev/model-proxy/v1/embeddings", | |
| 734 | + method: "POST", | |
| 735 | + headers: { | |
| 736 | + "Content-Type": "application/json", | |
| 737 | + Authorization: "Bearer test-api-key", | |
| 738 | + "api-key": "test-api-key", | |
| 739 | + }, | |
| 740 | + body: { | |
| 741 | + input: ["single text"], | |
| 742 | + model: "test-model", | |
| 743 | + continueProperties: { | |
| 744 | + apiBase: "https://proxy.continue.dev/model-proxy/v1/", | |
| 745 | + apiKeyLocation: undefined, | |
| 746 | + env: undefined, | |
| 747 | + envSecretLocations: undefined, | |
| 748 | + orgScopeId: null, | |
| 749 | + }, | |
| 750 | + }, | |
| 751 | + }, | |
| 752 | + mockResponse: { | |
| 753 | + data: [{ embedding: [0.1, 0.2, 0.3] }], | |
| 754 | + }, | |
| 755 | + }); | |
| 756 | + }); | |
| 757 | + }); | |
| 758 | +}); |
added core/llm/llms/test-utils/openai-test-utils.ts +375 −0
| @@ -0,0 +1,375 @@ | ||
| 1 | +import { afterEach, describe, expect, test, vi } from "vitest"; | |
| 2 | +import { ILLM } from "../../../index.js"; | |
| 3 | +import OpenAI from "../OpenAI.js"; | |
| 4 | + | |
| 5 | +interface LlmTestCase { | |
| 6 | + llm: ILLM; | |
| 7 | + methodToTest: keyof ILLM; | |
| 8 | + params: any[]; | |
| 9 | + expectedRequest: { | |
| 10 | + url: string; | |
| 11 | + method: string; | |
| 12 | + headers?: Record<string, string>; | |
| 13 | + body?: Record<string, any>; | |
| 14 | + }; | |
| 15 | + mockResponse?: any; | |
| 16 | + mockStream?: any[]; | |
| 17 | +} | |
| 18 | + | |
| 19 | +function createMockStream(mockStream: any[]) { | |
| 20 | + const encoder = new TextEncoder(); | |
| 21 | + return new ReadableStream({ | |
| 22 | + start(controller) { | |
| 23 | + for (const chunk of mockStream) { | |
| 24 | + controller.enqueue( | |
| 25 | + encoder.encode( | |
| 26 | + `data: ${ | |
| 27 | + typeof chunk === "string" ? chunk : JSON.stringify(chunk) | |
| 28 | + }\n\n`, | |
| 29 | + ), | |
| 30 | + ); | |
| 31 | + } | |
| 32 | + controller.close(); | |
| 33 | + }, | |
| 34 | + }); | |
| 35 | +} | |
| 36 | + | |
| 37 | +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { | |
| 38 | + const mockFetch = vi.fn(); | |
| 39 | + | |
| 40 | + if (mockStream) { | |
| 41 | + const stream = createMockStream(mockStream); | |
| 42 | + mockFetch.mockResolvedValue( | |
| 43 | + new Response(stream, { | |
| 44 | + headers: { | |
| 45 | + "Content-Type": "text/event-stream", | |
| 46 | + }, | |
| 47 | + }), | |
| 48 | + ); | |
| 49 | + } else { | |
| 50 | + mockFetch.mockResolvedValue( | |
| 51 | + new Response(JSON.stringify(mockResponse), { | |
| 52 | + headers: { "Content-Type": "application/json" }, | |
| 53 | + }), | |
| 54 | + ); | |
| 55 | + } | |
| 56 | + | |
| 57 | + return mockFetch; | |
| 58 | +} | |
| 59 | + | |
| 60 | +function setupReadableStreamPolyfill() { | |
| 61 | + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved | |
| 62 | + // @ts-ignore | |
| 63 | + const originalFrom = ReadableStream.from; | |
| 64 | + // @ts-ignore | |
| 65 | + ReadableStream.from = (body) => { | |
| 66 | + if (body?.source) { | |
| 67 | + return body; | |
| 68 | + } | |
| 69 | + return originalFrom(body); | |
| 70 | + }; | |
| 71 | +} | |
| 72 | + | |
| 73 | +async function executeLlmMethod( | |
| 74 | + llm: ILLM, | |
| 75 | + methodToTest: keyof ILLM, | |
| 76 | + params: any[], | |
| 77 | +) { | |
| 78 | + if (typeof (llm as any)[methodToTest] !== "function") { | |
| 79 | + throw new Error( | |
| 80 | + `Method ${String(methodToTest)} does not exist on the LLM instance.`, | |
| 81 | + ); | |
| 82 | + } | |
| 83 | + | |
| 84 | + const result = await (llm as any)[methodToTest](...params); | |
| 85 | + if (result?.next) { | |
| 86 | + for await (const _ of result) { | |
| 87 | + } | |
| 88 | + } | |
| 89 | +} | |
| 90 | + | |
| 91 | +function assertFetchCall(mockFetch: any, expectedRequest: any) { | |
| 92 | + expect(mockFetch).toHaveBeenCalledTimes(1); | |
| 93 | + const [url, options] = mockFetch.mock.calls[0]; | |
| 94 | + | |
| 95 | + expect(url.toString()).toBe(expectedRequest.url); | |
| 96 | + expect(options.method).toBe(expectedRequest.method); | |
| 97 | + | |
| 98 | + if (expectedRequest.headers) { | |
| 99 | + expect(options.headers).toEqual( | |
| 100 | + expect.objectContaining(expectedRequest.headers), | |
| 101 | + ); | |
| 102 | + } | |
| 103 | + | |
| 104 | + if (expectedRequest.body) { | |
| 105 | + const actualBody = JSON.parse(options.body as string); | |
| 106 | + expect(actualBody).toEqual(expectedRequest.body); | |
| 107 | + } | |
| 108 | +} | |
| 109 | + | |
| 110 | +async function runLlmTest(testCase: LlmTestCase) { | |
| 111 | + const { | |
| 112 | + llm, | |
| 113 | + methodToTest, | |
| 114 | + params, | |
| 115 | + expectedRequest, | |
| 116 | + mockResponse, | |
| 117 | + mockStream, | |
| 118 | + } = testCase; | |
| 119 | + | |
| 120 | + const mockFetch = setupMockFetch(mockResponse, mockStream); | |
| 121 | + setupReadableStreamPolyfill(); | |
| 122 | + | |
| 123 | + (llm as any).fetch = mockFetch; | |
| 124 | + | |
| 125 | + // Disable OpenAI adapter to use our custom fetch mock | |
| 126 | + (llm as any).useOpenAIAdapterFor = []; | |
| 127 | + | |
| 128 | + await executeLlmMethod(llm, methodToTest, params); | |
| 129 | + assertFetchCall(mockFetch, expectedRequest); | |
| 130 | +} | |
| 131 | + | |
| 132 | +export interface OpenAISubclassConfig { | |
| 133 | + providerName: string; | |
| 134 | + defaultApiBase?: string; | |
| 135 | + modelConversions?: { [key: string]: string }; | |
| 136 | + customOptions?: any; | |
| 137 | + modelConversionContent?: string; | |
| 138 | + modelConversionMaxTokens?: number; | |
| 139 | + customStreamCompleteEndpoint?: string; | |
| 140 | + customEmbeddingsUrl?: string; | |
| 141 | + customEmbeddingsHeaders?: { [key: string]: string }; | |
| 142 | + customEmbeddingsBody?: any; | |
| 143 | + customBodyOptions?: any; | |
| 144 | +} | |
| 145 | + | |
| 146 | +function getExpectedUrl( | |
| 147 | + config: OpenAISubclassConfig, | |
| 148 | + endpoint: string, | |
| 149 | + model: string = "gpt-4", | |
| 150 | +) { | |
| 151 | + let baseUrl = config.defaultApiBase || "https://api.openai.com/v1/"; | |
| 152 | + if (config.providerName === "azure") { | |
| 153 | + return `${baseUrl}openai/deployments/${model}/${endpoint}?api-version=2023-07-01-preview`; | |
| 154 | + } else if (config.providerName === "ncompass") { | |
| 155 | + return `${baseUrl}${endpoint}`; | |
| 156 | + } | |
| 157 | + return `${baseUrl}${endpoint}`; | |
| 158 | +} | |
| 159 | + | |
| 160 | +export const createOpenAISubclassTests = ( | |
| 161 | + ProviderClass: typeof OpenAI, | |
| 162 | + config: OpenAISubclassConfig, | |
| 163 | +) => { | |
| 164 | + describe(config.providerName, () => { | |
| 165 | + afterEach(() => { | |
| 166 | + vi.clearAllMocks(); | |
| 167 | + }); | |
| 168 | + | |
| 169 | + test("should have correct provider name", () => { | |
| 170 | + expect(ProviderClass.providerName).toBe(config.providerName); | |
| 171 | + }); | |
| 172 | + | |
| 173 | + if (config.defaultApiBase) { | |
| 174 | + test("should have correct default API base", () => { | |
| 175 | + expect(ProviderClass.defaultOptions?.apiBase).toBe( | |
| 176 | + config.defaultApiBase, | |
| 177 | + ); | |
| 178 | + }); | |
| 179 | + } | |
| 180 | + | |
| 181 | + test("streamChat should send a valid request", async () => { | |
| 182 | + const provider = new ProviderClass({ | |
| 183 | + apiKey: "test-api-key", | |
| 184 | + model: "gpt-4", | |
| 185 | + apiBase: config.defaultApiBase || "https://api.openai.com/v1/", | |
| 186 | + }); | |
| 187 | + | |
| 188 | + await runLlmTest({ | |
| 189 | + llm: provider, | |
| 190 | + methodToTest: "streamChat", | |
| 191 | + params: [ | |
| 192 | + [{ role: "user", content: "hello" }], | |
| 193 | + new AbortController().signal, | |
| 194 | + ], | |
| 195 | + expectedRequest: { | |
| 196 | + url: getExpectedUrl(config, "chat/completions"), | |
| 197 | + method: "POST", | |
| 198 | + headers: { | |
| 199 | + "Content-Type": "application/json", | |
| 200 | + Authorization: "Bearer test-api-key", | |
| 201 | + "api-key": "test-api-key", | |
| 202 | + }, | |
| 203 | + body: { | |
| 204 | + model: "gpt-4", | |
| 205 | + messages: [{ role: "user", content: "hello" }], | |
| 206 | + stream: true, | |
| 207 | + max_tokens: 2048, | |
| 208 | + ...config.customBodyOptions, | |
| 209 | + }, | |
| 210 | + }, | |
| 211 | + mockStream: [ | |
| 212 | + { choices: [{ delta: { content: "Hello" } }] }, | |
| 213 | + { choices: [{ delta: { content: " world" } }] }, | |
| 214 | + ], | |
| 215 | + }); | |
| 216 | + }); | |
| 217 | + | |
| 218 | + test("chat should send a valid request", async () => { | |
| 219 | + const provider = new ProviderClass({ | |
| 220 | + apiKey: "test-api-key", | |
| 221 | + model: "gpt-4", | |
| 222 | + apiBase: config.defaultApiBase || "https://api.openai.com/v1/", | |
| 223 | + }); | |
| 224 | + | |
| 225 | + await runLlmTest({ | |
| 226 | + llm: provider, | |
| 227 | + methodToTest: "chat", | |
| 228 | + params: [ | |
| 229 | + [{ role: "user", content: "hello" }], | |
| 230 | + new AbortController().signal, | |
| 231 | + ], | |
| 232 | + expectedRequest: { | |
| 233 | + url: getExpectedUrl(config, "chat/completions"), | |
| 234 | + method: "POST", | |
| 235 | + headers: { | |
| 236 | + "Content-Type": "application/json", | |
| 237 | + Authorization: "Bearer test-api-key", | |
| 238 | + "api-key": "test-api-key", | |
| 239 | + }, | |
| 240 | + body: { | |
| 241 | + model: "gpt-4", | |
| 242 | + messages: [{ role: "user", content: "hello" }], | |
| 243 | + stream: true, | |
| 244 | + max_tokens: 2048, | |
| 245 | + ...config.customBodyOptions, | |
| 246 | + }, | |
| 247 | + }, | |
| 248 | + mockStream: [ | |
| 249 | + { choices: [{ delta: { content: "Hello" } }] }, | |
| 250 | + { choices: [{ delta: { content: " world" } }] }, | |
| 251 | + ], | |
| 252 | + }); | |
| 253 | + }); | |
| 254 | + | |
| 255 | + test("streamComplete should send a valid request", async () => { | |
| 256 | + const provider = new ProviderClass({ | |
| 257 | + apiKey: "test-api-key", | |
| 258 | + model: "gpt-4", | |
| 259 | + apiBase: config.defaultApiBase || "https://api.openai.com/v1/", | |
| 260 | + }); | |
| 261 | + | |
| 262 | + await runLlmTest({ | |
| 263 | + llm: provider, | |
| 264 | + methodToTest: "streamComplete", | |
| 265 | + params: ["Hello", new AbortController().signal], | |
| 266 | + expectedRequest: { | |
| 267 | + url: getExpectedUrl( | |
| 268 | + config, | |
| 269 | + config.customStreamCompleteEndpoint || "chat/completions", | |
| 270 | + ), | |
| 271 | + method: "POST", | |
| 272 | + headers: { | |
| 273 | + "Content-Type": "application/json", | |
| 274 | + Authorization: "Bearer test-api-key", | |
| 275 | + "api-key": "test-api-key", | |
| 276 | + }, | |
| 277 | + body: | |
| 278 | + config.customStreamCompleteEndpoint === "completions" | |
| 279 | + ? { | |
| 280 | + model: "gpt-4", | |
| 281 | + prompt: "Hello", | |
| 282 | + stream: true, | |
| 283 | + max_tokens: 2048, | |
| 284 | + ...config.customBodyOptions, | |
| 285 | + } | |
| 286 | + : { | |
| 287 | + model: "gpt-4", | |
| 288 | + messages: [{ role: "user", content: "Hello" }], | |
| 289 | + stream: true, | |
| 290 | + max_tokens: 2048, | |
| 291 | + ...config.customBodyOptions, | |
| 292 | + }, | |
| 293 | + }, | |
| 294 | + mockStream: [ | |
| 295 | + { choices: [{ delta: { content: "Hello" } }] }, | |
| 296 | + { choices: [{ delta: { content: " world" } }] }, | |
| 297 | + ], | |
| 298 | + }); | |
| 299 | + }); | |
| 300 | + | |
| 301 | + test("complete should send a valid request", async () => { | |
| 302 | + const provider = new ProviderClass({ | |
| 303 | + apiKey: "test-api-key", | |
| 304 | + model: "gpt-4", | |
| 305 | + apiBase: config.defaultApiBase || "https://api.openai.com/v1/", | |
| 306 | + }); | |
| 307 | + | |
| 308 | + await runLlmTest({ | |
| 309 | + llm: provider, | |
| 310 | + methodToTest: "complete", | |
| 311 | + params: ["Hello", new AbortController().signal], | |
| 312 | + expectedRequest: { | |
| 313 | + url: getExpectedUrl(config, "chat/completions"), | |
| 314 | + method: "POST", | |
| 315 | + headers: { | |
| 316 | + "Content-Type": "application/json", | |
| 317 | + Authorization: "Bearer test-api-key", | |
| 318 | + "api-key": "test-api-key", | |
| 319 | + }, | |
| 320 | + body: { | |
| 321 | + model: "gpt-4", | |
| 322 | + messages: [{ role: "user", content: "Hello" }], | |
| 323 | + stream: true, | |
| 324 | + max_tokens: 2048, | |
| 325 | + ...config.customBodyOptions, | |
| 326 | + }, | |
| 327 | + }, | |
| 328 | + mockStream: [ | |
| 329 | + { choices: [{ delta: { content: "Hello" } }] }, | |
| 330 | + { choices: [{ delta: { content: " world" } }] }, | |
| 331 | + ], | |
| 332 | + }); | |
| 333 | + }); | |
| 334 | + | |
| 335 | + test("should handle embeddings", async () => { | |
| 336 | + const provider = new ProviderClass({ | |
| 337 | + apiKey: "test-api-key", | |
| 338 | + model: "text-embedding-ada-002", | |
| 339 | + apiBase: config.defaultApiBase || "https://api.openai.com/v1/", | |
| 340 | + }); | |
| 341 | + | |
| 342 | + // Skip test if provider doesn't support embeddings (e.g., ncompass with undefined endpoint) | |
| 343 | + if (config.providerName === "ncompass" && !config.customEmbeddingsUrl) { | |
| 344 | + return; | |
| 345 | + } | |
| 346 | + | |
| 347 | + await runLlmTest({ | |
| 348 | + llm: provider, | |
| 349 | + methodToTest: "embed", | |
| 350 | + params: [["Hello", "World"]], | |
| 351 | + expectedRequest: { | |
| 352 | + url: | |
| 353 | + config.customEmbeddingsUrl || | |
| 354 | + `${config.defaultApiBase || "https://api.openai.com/v1/"}embeddings`, | |
| 355 | + method: "POST", | |
| 356 | + headers: config.customEmbeddingsHeaders || { | |
| 357 | + Authorization: "Bearer test-api-key", | |
| 358 | + "Content-Type": "application/json", | |
| 359 | + "api-key": "test-api-key", | |
| 360 | + }, | |
| 361 | + body: config.customEmbeddingsBody || { | |
| 362 | + input: ["Hello", "World"], | |
| 363 | + model: "text-embedding-ada-002", | |
| 364 | + }, | |
| 365 | + }, | |
| 366 | + mockResponse: { | |
| 367 | + data: [ | |
| 368 | + { embedding: [0.1, 0.2, 0.3] }, | |
| 369 | + { embedding: [0.4, 0.5, 0.6] }, | |
| 370 | + ], | |
| 371 | + }, | |
| 372 | + }); | |
| 373 | + }); | |
| 374 | + }); | |
| 375 | +}; |
modified core/llm/logFormatter.test.ts +5 −0
| @@ -44,6 +44,7 @@ | ||
| 44 | 44 | content: "You are a helpful assistant", |
| 45 | 45 | }, |
| 46 | 46 | ], |
| 47 | + provider: "watsonx", | |
| 47 | 48 | }); |
| 48 | 49 | logger._logItem({ |
| 49 | 50 | interactionId: "1", |
| @@ -79,6 +80,7 @@ | ||
| 79 | 80 | promptTokens: 10, |
| 80 | 81 | generatedTokens: 20, |
| 81 | 82 | thinkingTokens: 0, |
| 83 | + usage: undefined, | |
| 82 | 84 | }); |
| 83 | 85 | |
| 84 | 86 | expect(output.getText()).toBe( |
| @@ -113,6 +115,7 @@ | ||
| 113 | 115 | model: "granite3.2-dense:8b", |
| 114 | 116 | }, |
| 115 | 117 | prompt: "A horse is a horse", |
| 118 | + provider: "watsonx", | |
| 116 | 119 | }); |
| 117 | 120 | logger._logItem({ |
| 118 | 121 | interactionId: "1", |
| @@ -149,6 +152,7 @@ | ||
| 149 | 152 | }, |
| 150 | 153 | prefix: "A\nB", |
| 151 | 154 | suffix: "D\nE", |
| 155 | + provider: "watsonx", | |
| 152 | 156 | }); |
| 153 | 157 | logger._logItem({ |
| 154 | 158 | interactionId: "1", |
| @@ -225,6 +229,7 @@ | ||
| 225 | 229 | promptTokens: 10, |
| 226 | 230 | generatedTokens: 20, |
| 227 | 231 | thinkingTokens: 0, |
| 232 | + usage: undefined, | |
| 228 | 233 | }); |
| 229 | 234 | logger._logItem({ |
| 230 | 235 | interactionId: "3", |
added core/llm/utils/calculateRequestCost.ts +181 −0
| @@ -0,0 +1,181 @@ | ||
| 1 | +import { Usage } from "../.."; | |
| 2 | + | |
| 3 | +export interface CostBreakdown { | |
| 4 | + cost: number; | |
| 5 | + breakdown: string; | |
| 6 | +} | |
| 7 | + | |
| 8 | +function calculateAnthropicCost( | |
| 9 | + model: string, | |
| 10 | + usage: Usage, | |
| 11 | +): CostBreakdown | null { | |
| 12 | + // Normalize model name to handle various formats | |
| 13 | + const normalizedModel = model.toLowerCase(); | |
| 14 | + | |
| 15 | + // Define pricing per million tokens (MTok) | |
| 16 | + const pricing: Record< | |
| 17 | + string, | |
| 18 | + { input: number; output: number; cacheWrite: number; cacheRead: number } | |
| 19 | + > = { | |
| 20 | + // Claude Opus 4 (most intelligent model) | |
| 21 | + "claude-3-opus": { | |
| 22 | + input: 15, | |
| 23 | + output: 75, | |
| 24 | + cacheWrite: 18.75, | |
| 25 | + cacheRead: 1.5, | |
| 26 | + }, | |
| 27 | + "claude-3-opus-20240229": { | |
| 28 | + input: 15, | |
| 29 | + output: 75, | |
| 30 | + cacheWrite: 18.75, | |
| 31 | + cacheRead: 1.5, | |
| 32 | + }, | |
| 33 | + | |
| 34 | + // Claude Sonnet 4 (optimal balance) | |
| 35 | + "claude-3-5-sonnet": { | |
| 36 | + input: 3, | |
| 37 | + output: 15, | |
| 38 | + cacheWrite: 3.75, | |
| 39 | + cacheRead: 0.3, | |
| 40 | + }, | |
| 41 | + "claude-3-5-sonnet-20241022": { | |
| 42 | + input: 3, | |
| 43 | + output: 15, | |
| 44 | + cacheWrite: 3.75, | |
| 45 | + cacheRead: 0.3, | |
| 46 | + }, | |
| 47 | + "claude-3-5-sonnet-20240620": { | |
| 48 | + input: 3, | |
| 49 | + output: 15, | |
| 50 | + cacheWrite: 3.75, | |
| 51 | + cacheRead: 0.3, | |
| 52 | + }, | |
| 53 | + | |
| 54 | + // Claude Haiku 3.5 (fastest, most cost-effective) | |
| 55 | + "claude-3-5-haiku": { | |
| 56 | + input: 0.8, | |
| 57 | + output: 4, | |
| 58 | + cacheWrite: 1, | |
| 59 | + cacheRead: 0.08, | |
| 60 | + }, | |
| 61 | + "claude-3-5-haiku-20241022": { | |
| 62 | + input: 0.8, | |
| 63 | + output: 4, | |
| 64 | + cacheWrite: 1, | |
| 65 | + cacheRead: 0.08, | |
| 66 | + }, | |
| 67 | + | |
| 68 | + // Legacy Claude 3 Haiku | |
| 69 | + "claude-3-haiku": { | |
| 70 | + input: 0.25, | |
| 71 | + output: 1.25, | |
| 72 | + cacheWrite: 0.3, | |
| 73 | + cacheRead: 0.03, | |
| 74 | + }, | |
| 75 | + "claude-3-haiku-20240307": { | |
| 76 | + input: 0.25, | |
| 77 | + output: 1.25, | |
| 78 | + cacheWrite: 0.3, | |
| 79 | + cacheRead: 0.03, | |
| 80 | + }, | |
| 81 | + }; | |
| 82 | + | |
| 83 | + // Find matching pricing model | |
| 84 | + let modelPricing = pricing[normalizedModel]; | |
| 85 | + | |
| 86 | + // If exact match not found, try to find by partial match | |
| 87 | + if (!modelPricing) { | |
| 88 | + for (const [key, value] of Object.entries(pricing)) { | |
| 89 | + if (normalizedModel.includes(key) || key.includes(normalizedModel)) { | |
| 90 | + modelPricing = value; | |
| 91 | + break; | |
| 92 | + } | |
| 93 | + } | |
| 94 | + } | |
| 95 | + | |
| 96 | + // If still no match, try common patterns | |
| 97 | + if (!modelPricing) { | |
| 98 | + if (normalizedModel.includes("opus")) { | |
| 99 | + modelPricing = pricing["claude-3-opus"]; | |
| 100 | + } else if (normalizedModel.includes("sonnet")) { | |
| 101 | + modelPricing = pricing["claude-3-5-sonnet"]; | |
| 102 | + } else if (normalizedModel.includes("haiku")) { | |
| 103 | + modelPricing = pricing["claude-3-5-haiku"]; | |
| 104 | + } | |
| 105 | + } | |
| 106 | + | |
| 107 | + if (!modelPricing) { | |
| 108 | + return null; // Unknown model | |
| 109 | + } | |
| 110 | + | |
| 111 | + // Calculate costs | |
| 112 | + const inputCost = (usage.promptTokens / 1_000_000) * modelPricing.input; | |
| 113 | + const outputCost = (usage.completionTokens / 1_000_000) * modelPricing.output; | |
| 114 | + | |
| 115 | + // Build breakdown components | |
| 116 | + const breakdownParts: string[] = []; | |
| 117 | + | |
| 118 | + // Input tokens breakdown | |
| 119 | + if (usage.promptTokens > 0) { | |
| 120 | + breakdownParts.push( | |
| 121 | + `Input: ${usage.promptTokens.toLocaleString()} tokens × $${modelPricing.input}/MTok = $${inputCost.toFixed(6)}`, | |
| 122 | + ); | |
| 123 | + } | |
| 124 | + | |
| 125 | + // Output tokens breakdown | |
| 126 | + if (usage.completionTokens > 0) { | |
| 127 | + breakdownParts.push( | |
| 128 | + `Output: ${usage.completionTokens.toLocaleString()} tokens × $${modelPricing.output}/MTok = $${outputCost.toFixed(6)}`, | |
| 129 | + ); | |
| 130 | + } | |
| 131 | + | |
| 132 | + // Handle prompt caching costs if available | |
| 133 | + let cacheCost = 0; | |
| 134 | + if (usage.promptTokensDetails) { | |
| 135 | + const { cachedTokens, cacheWriteTokens } = usage.promptTokensDetails; | |
| 136 | + | |
| 137 | + if (cacheWriteTokens && cacheWriteTokens > 0) { | |
| 138 | + const cacheWriteCost = | |
| 139 | + (cacheWriteTokens / 1_000_000) * modelPricing.cacheWrite; | |
| 140 | + cacheCost += cacheWriteCost; | |
| 141 | + breakdownParts.push( | |
| 142 | + `Cache Write: ${cacheWriteTokens.toLocaleString()} tokens × $${modelPricing.cacheWrite}/MTok = $${cacheWriteCost.toFixed(6)}`, | |
| 143 | + ); | |
| 144 | + } | |
| 145 | + | |
| 146 | + if (cachedTokens && cachedTokens > 0) { | |
| 147 | + const cacheReadCost = (cachedTokens / 1_000_000) * modelPricing.cacheRead; | |
| 148 | + cacheCost += cacheReadCost; | |
| 149 | + breakdownParts.push( | |
| 150 | + `Cache Read: ${cachedTokens.toLocaleString()} tokens × $${modelPricing.cacheRead}/MTok = $${cacheReadCost.toFixed(6)}`, | |
| 151 | + ); | |
| 152 | + } | |
| 153 | + } | |
| 154 | + | |
| 155 | + const totalCost = inputCost + outputCost + cacheCost; | |
| 156 | + | |
| 157 | + // Build final breakdown string | |
| 158 | + let breakdown = `Model: ${model}\n`; | |
| 159 | + breakdown += breakdownParts.join("\n"); | |
| 160 | + if (breakdownParts.length > 1) { | |
| 161 | + breakdown += `\nTotal: $${totalCost.toFixed(6)}`; | |
| 162 | + } | |
| 163 | + | |
| 164 | + return { | |
| 165 | + cost: totalCost, | |
| 166 | + breakdown, | |
| 167 | + }; | |
| 168 | +} | |
| 169 | + | |
| 170 | +export function calculateRequestCost( | |
| 171 | + provider: string, | |
| 172 | + model: string, | |
| 173 | + usage: Usage, | |
| 174 | +): CostBreakdown | null { | |
| 175 | + switch (provider) { | |
| 176 | + case "anthropic": | |
| 177 | + return calculateAnthropicCost(model, usage); | |
| 178 | + default: | |
| 179 | + return null; | |
| 180 | + } | |
| 181 | +} |
modified core/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified core/protocol/core.ts +7 −0
| @@ -186,6 +186,13 @@ | ||
| 186 | 186 | }, |
| 187 | 187 | string | undefined, |
| 188 | 188 | ]; |
| 189 | + "conversation/compact": [ | |
| 190 | + { | |
| 191 | + index: number; | |
| 192 | + sessionId: string; | |
| 193 | + }, | |
| 194 | + string | undefined, | |
| 195 | + ]; | |
| 189 | 196 | "stats/getTokensPerDay": [ |
| 190 | 197 | undefined, |
| 191 | 198 | { day: string; promptTokens: number; generatedTokens: number }[], |
modified core/protocol/passThrough.ts +1 −0
| @@ -47,6 +47,7 @@ | ||
| 47 | 47 | "llm/compileChat", |
| 48 | 48 | "streamDiffLines", |
| 49 | 49 | "chatDescriber/describe", |
| 50 | + "conversation/compact", | |
| 50 | 51 | "stats/getTokensPerDay", |
| 51 | 52 | "stats/getTokensPerModel", |
| 52 | 53 | // Codebase |
modified core/util/GlobalContext.test.ts +65 −9
| @@ -1,7 +1,6 @@ | ||
| 1 | 1 | // core/util/GlobalContext.test.ts |
| 2 | -import { GlobalContext, GlobalContextType } from "./GlobalContext"; | |
| 3 | 2 | import fs from "node:fs"; |
| 4 | -import path from "path"; | |
| 3 | +import { GlobalContext } from "./GlobalContext"; | |
| 5 | 4 | import { getGlobalContextFilePath } from "./paths"; |
| 6 | 5 | |
| 7 | 6 | describe("GlobalContext", () => { |
| @@ -69,13 +68,40 @@ | ||
| 69 | 68 | const value = globalContext.get("indexingPaused"); |
| 70 | 69 | expect(value).toBeUndefined(); |
| 71 | 70 | expect(consoleWarnMock).toHaveBeenCalledWith( |
| 72 | - expect.stringContaining("Error parsing global context"), | |
| 71 | + expect.stringContaining( | |
| 72 | + "Error parsing global context, deleting corrupted file", | |
| 73 | + ), | |
| 73 | 74 | ); |
| 74 | 75 | |
| 75 | 76 | // Clean up |
| 76 | 77 | consoleWarnMock.mockRestore(); |
| 77 | 78 | }); |
| 78 | 79 | |
| 80 | + it("should delete corrupted file on get and allow fresh start", () => { | |
| 81 | + // Write invalid JSON to the file | |
| 82 | + fs.writeFileSync(globalContextFilePath, "{ invalid json }"); | |
| 83 | + expect(fs.existsSync(globalContextFilePath)).toBe(true); | |
| 84 | + | |
| 85 | + const consoleWarnMock = jest | |
| 86 | + .spyOn(console, "warn") | |
| 87 | + .mockImplementation(() => {}); | |
| 88 | + | |
| 89 | + // Try to get a value - this should delete the corrupted file | |
| 90 | + const value = globalContext.get("indexingPaused"); | |
| 91 | + expect(value).toBeUndefined(); | |
| 92 | + | |
| 93 | + // File should be deleted after corruption is detected | |
| 94 | + expect(fs.existsSync(globalContextFilePath)).toBe(false); | |
| 95 | + | |
| 96 | + // Now we should be able to update and get values normally | |
| 97 | + globalContext.update("indexingPaused", true); | |
| 98 | + const newValue = globalContext.get("indexingPaused"); | |
| 99 | + expect(newValue).toBe(true); | |
| 100 | + | |
| 101 | + // Clean up | |
| 102 | + consoleWarnMock.mockRestore(); | |
| 103 | + }); | |
| 104 | + | |
| 79 | 105 | it("should handle JSON parsing errors gracefully on update", () => { |
| 80 | 106 | // Write invalid JSON to the file |
| 81 | 107 | fs.writeFileSync(globalContextFilePath, "{ invalid json }"); |
| @@ -87,15 +113,45 @@ | ||
| 87 | 113 | // Attempt to update |
| 88 | 114 | globalContext.update("indexingPaused", true); |
| 89 | 115 | |
| 90 | - // The update should have been skipped due to JSON parsing error | |
| 91 | - // So attempting to get the value should return undefined | |
| 92 | - const value = globalContext.get("indexingPaused"); | |
| 93 | - expect(value).toBeUndefined(); | |
| 94 | - | |
| 95 | 116 | expect(consoleWarnMock).toHaveBeenCalledWith( |
| 96 | - expect.stringContaining("Error updating global context"), | |
| 117 | + expect.stringContaining( | |
| 118 | + "Error updating global context, deleting corrupted file", | |
| 119 | + ), | |
| 97 | 120 | ); |
| 98 | 121 | |
| 122 | + // The update should have recreated the file with just the new value | |
| 123 | + const value = globalContext.get("indexingPaused"); | |
| 124 | + expect(value).toBe(true); | |
| 125 | + | |
| 126 | + // Clean up | |
| 127 | + consoleWarnMock.mockRestore(); | |
| 128 | + }); | |
| 129 | + | |
| 130 | + it("should delete and recreate corrupted file on update", () => { | |
| 131 | + // Write invalid JSON to the file | |
| 132 | + fs.writeFileSync(globalContextFilePath, "{ invalid json }"); | |
| 133 | + expect(fs.existsSync(globalContextFilePath)).toBe(true); | |
| 134 | + | |
| 135 | + const consoleWarnMock = jest | |
| 136 | + .spyOn(console, "warn") | |
| 137 | + .mockImplementation(() => {}); | |
| 138 | + | |
| 139 | + // Try to update - this should delete the corrupted file and recreate it | |
| 140 | + globalContext.update("indexingPaused", true); | |
| 141 | + | |
| 142 | + // File should still exist but with valid JSON now | |
| 143 | + expect(fs.existsSync(globalContextFilePath)).toBe(true); | |
| 144 | + | |
| 145 | + // Should be able to read the value | |
| 146 | + const value = globalContext.get("indexingPaused"); | |
| 147 | + expect(value).toBe(true); | |
| 148 | + | |
| 149 | + // Should be able to add more values | |
| 150 | + globalContext.update("hasAlreadyCreatedAPromptFile", false); | |
| 151 | + expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(false); | |
| 152 | + // Original value should still be there | |
| 153 | + expect(globalContext.get("indexingPaused")).toBe(true); | |
| 154 | + | |
| 99 | 155 | // Clean up |
| 100 | 156 | consoleWarnMock.mockRestore(); |
| 101 | 157 | }); |
modified core/util/GlobalContext.ts +33 −2
| @@ -68,7 +68,28 @@ | ||
| 68 | 68 | try { |
| 69 | 69 | parsed = JSON.parse(data); |
| 70 | 70 | } catch (e: any) { |
| 71 | - console.warn(`Error updating global context: ${e}`); | |
| 71 | + console.warn( | |
| 72 | + `Error updating global context, deleting corrupted file: ${e}`, | |
| 73 | + ); | |
| 74 | + // Delete the corrupted file and recreate it fresh | |
| 75 | + try { | |
| 76 | + fs.unlinkSync(filepath); | |
| 77 | + } catch (deleteError) { | |
| 78 | + console.warn( | |
| 79 | + `Error deleting corrupted global context file: ${deleteError}`, | |
| 80 | + ); | |
| 81 | + } | |
| 82 | + // Recreate the file with just the new value | |
| 83 | + fs.writeFileSync( | |
| 84 | + filepath, | |
| 85 | + JSON.stringify( | |
| 86 | + { | |
| 87 | + [key]: value, | |
| 88 | + }, | |
| 89 | + null, | |
| 90 | + 2, | |
| 91 | + ), | |
| 92 | + ); | |
| 72 | 93 | return; |
| 73 | 94 | } |
| 74 | 95 | |
| @@ -90,7 +111,17 @@ | ||
| 90 | 111 | const parsed = JSON.parse(data); |
| 91 | 112 | return parsed[key]; |
| 92 | 113 | } catch (e: any) { |
| 93 | - console.warn(`Error parsing global context: ${e}`); | |
| 114 | + console.warn( | |
| 115 | + `Error parsing global context, deleting corrupted file: ${e}`, | |
| 116 | + ); | |
| 117 | + // Delete the corrupted file so it can be recreated fresh | |
| 118 | + try { | |
| 119 | + fs.unlinkSync(filepath); | |
| 120 | + } catch (deleteError) { | |
| 121 | + console.warn( | |
| 122 | + `Error deleting corrupted global context file: ${deleteError}`, | |
| 123 | + ); | |
| 124 | + } | |
| 94 | 125 | return undefined; |
| 95 | 126 | } |
| 96 | 127 | } |
added core/util/conversationCompaction.ts +89 −0
| @@ -0,0 +1,89 @@ | ||
| 1 | +import { ILLM } from ".."; | |
| 2 | +import { HistoryManager } from "./history"; | |
| 3 | +import { stripImages } from "./messageContent"; | |
| 4 | + | |
| 5 | +export interface CompactionParams { | |
| 6 | + sessionId: string; | |
| 7 | + index: number; | |
| 8 | + historyManager: HistoryManager; | |
| 9 | + currentModel: ILLM; | |
| 10 | +} | |
| 11 | + | |
| 12 | +/** | |
| 13 | + * Compacts conversation history up to a specified index by generating a summary. | |
| 14 | + * This helper function extracts the compaction logic from the main core handler. | |
| 15 | + * | |
| 16 | + * @param params - Object containing sessionId, index, historyManager, and currentModel | |
| 17 | + * @returns Promise<void> - Updates the session with the conversation summary | |
| 18 | + */ | |
| 19 | +export async function compactConversation({ | |
| 20 | + sessionId, | |
| 21 | + index, | |
| 22 | + historyManager, | |
| 23 | + currentModel, | |
| 24 | +}: CompactionParams): Promise<void> { | |
| 25 | + // Get the current session | |
| 26 | + const session = historyManager.load(sessionId); | |
| 27 | + const historyUpToIndex = session.history.slice(0, index + 1); | |
| 28 | + | |
| 29 | + // Apply the same filtering logic as in constructMessages, but exclude the target message | |
| 30 | + // if it already has a summary (we're re-compacting) | |
| 31 | + let summaryContent = ""; | |
| 32 | + let filteredHistory = historyUpToIndex; | |
| 33 | + | |
| 34 | + // First, check if the target message already has a summary and ignore it | |
| 35 | + const targetMessageHasSummary = historyUpToIndex[index].conversationSummary; | |
| 36 | + const searchHistory = targetMessageHasSummary | |
| 37 | + ? historyUpToIndex.slice(0, index) | |
| 38 | + : historyUpToIndex; | |
| 39 | + | |
| 40 | + // Find the most recent conversation summary (excluding target if it has one) | |
| 41 | + for (let i = searchHistory.length - 1; i >= 0; i--) { | |
| 42 | + const summary = searchHistory[i].conversationSummary; | |
| 43 | + if (summary) { | |
| 44 | + summaryContent = summary; | |
| 45 | + // Only include messages that come AFTER the message with the summary | |
| 46 | + filteredHistory = historyUpToIndex.slice(i + 1); | |
| 47 | + break; | |
| 48 | + } | |
| 49 | + } | |
| 50 | + | |
| 51 | + // Create messages from filtered history | |
| 52 | + const messages = filteredHistory.map((item: any) => item.message); | |
| 53 | + | |
| 54 | + // If there's a previous summary, include it as a user message at the beginning | |
| 55 | + if (summaryContent) { | |
| 56 | + messages.unshift({ | |
| 57 | + role: "user", | |
| 58 | + content: `Previous conversation summary:\n\n${summaryContent}`, | |
| 59 | + }); | |
| 60 | + } | |
| 61 | + | |
| 62 | + const compactionPrompt = { | |
| 63 | + role: "user" as const, | |
| 64 | + content: | |
| 65 | + "Create a comprehensive summary of this conversation that captures all essential information needed to continue the work seamlessly. Structure your response to preserve technical accuracy and context continuity.\n\nYour summary should include:\n\n1. **Conversation Overview**: Describe the main topic and progression of the discussion, including any shifts in focus or direction.\n\n2. **Active Development**: Detail what was being implemented, modified, or debugged most recently. Include specific technical approaches and methodologies used.\n\n3. **Technical Stack**: List all relevant technologies, frameworks, libraries, coding patterns, and architectural decisions discussed.\n\n4. **File Operations**: Document all files that were created, modified, or referenced, including their purposes and key changes. Include important code snippets and their locations.\n\n5. **Solutions & Troubleshooting**: Summarize problems encountered and how they were resolved, including any debugging steps or workarounds applied.\n\n6. **Outstanding Work**: Clearly identify any incomplete tasks, pending implementations, or next steps that were discussed. Include direct references to user requests and current progress.\n\nIf there's a previous summary in the conversation, integrate its relevant information while removing outdated details. Focus on technical precision and include specific identifiers (file paths, function names, class names, etc.) that would be essential for continuation. Write in third person and maintain an objective, technical tone.", | |
| 66 | + }; | |
| 67 | + | |
| 68 | + // Generate the summary using the current model | |
| 69 | + const response = await currentModel.chat( | |
| 70 | + [...messages, compactionPrompt], | |
| 71 | + new AbortController().signal, | |
| 72 | + {}, | |
| 73 | + ); | |
| 74 | + | |
| 75 | + // Update the target message with the conversation summary | |
| 76 | + const updatedHistory = [...session.history]; | |
| 77 | + updatedHistory[index] = { | |
| 78 | + ...updatedHistory[index], | |
| 79 | + conversationSummary: stripImages(response.content), | |
| 80 | + }; | |
| 81 | + | |
| 82 | + // Update the session with the new history | |
| 83 | + const updatedSession = { | |
| 84 | + ...session, | |
| 85 | + history: updatedHistory, | |
| 86 | + }; | |
| 87 | + | |
| 88 | + historyManager.save(updatedSession); | |
| 89 | +} |
modified core/util/history.ts +1 −1
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | } |
| 22 | 22 | } |
| 23 | 23 | |
| 24 | -class HistoryManager { | |
| 24 | +export class HistoryManager { | |
| 25 | 25 | list(options: ListHistoryOptions): SessionMetadata[] { |
| 26 | 26 | const filepath = getSessionsListPath(); |
| 27 | 27 | if (!fs.existsSync(filepath)) { |
modified docs/customize/model-providers/top-level/bedrock.mdx +35 −0
| @@ -186,6 +186,41 @@ | ||
| 186 | 186 | aws_session_token = pqrstuvwxyz # Optional: means short term creds. |
| 187 | 187 | ``` |
| 188 | 188 | |
| 189 | +You can also use an AWS `accessKeyId` and `secretAccessKey` for authentication instead of a local credentials profile. | |
| 190 | + | |
| 191 | +<Tabs> | |
| 192 | + <Tab title="YAML"> | |
| 193 | + ```yaml title="config.yaml" | |
| 194 | + models: | |
| 195 | + - name: Claude 3.7 Sonnet | |
| 196 | + provider: bedrock | |
| 197 | + model: us.anthropic.claude-3-7-sonnet-20250219-v1:0 | |
| 198 | + env: | |
| 199 | + region: us-east-1 | |
| 200 | + accessKeyId: ${{ secrets.AWS_ACCESS_KEY_ID }} # can also enter key inline here for local assistants | |
| 201 | + secretAccessKey: ${{ secrets.AWS_SECRET_ACCESS_KEY }} # can also enter key inline here for local assistants | |
| 202 | + roles: | |
| 203 | + - chat | |
| 204 | + ``` | |
| 205 | + </Tab> | |
| 206 | + <Tab title="JSON"> | |
| 207 | + ```json title="config.json" | |
| 208 | + { | |
| 209 | + "models": [ | |
| 210 | + { | |
| 211 | + "title": "Claude 3.7 Sonnet", | |
| 212 | + "provider": "bedrock", | |
| 213 | + "model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0", | |
| 214 | + "region": "us-east-1", | |
| 215 | + "accessKeyId": "[YOUR_ACCESS_KEY_ID]", | |
| 216 | + "secretAccessKey": "[YOUR_SECRET_ACCESS_KEY]" | |
| 217 | + } | |
| 218 | + ] | |
| 219 | + } | |
| 220 | + ``` | |
| 221 | + </Tab> | |
| 222 | +</Tabs> | |
| 223 | + | |
| 189 | 224 | ## Custom Imported Models |
| 190 | 225 | |
| 191 | 226 | To setup Bedrock using custom imported models, add the following to your config file: |
modified docs/customize/model-providers/top-level/xAI.mdx +6 −6
| @@ -9,18 +9,18 @@ | ||
| 9 | 9 | |
| 10 | 10 | ## Chat model |
| 11 | 11 | |
| 12 | -We recommend configuring **grok-2-latest** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models). | |
| 12 | +We recommend configuring **grok-4** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models). | |
| 13 | 13 | |
| 14 | 14 | <Tabs> |
| 15 | 15 | <Tab title="Config"> |
| 16 | - Add the [xAI Grok 2 model block](https://hub.continue.dev/xai/grok-2) on the hub. | |
| 16 | + Add the [xAI Grok 4 model block](https://hub.continue.dev/xai/grok-4) on the hub. | |
| 17 | 17 | </Tab> |
| 18 | 18 | <Tab title="YAML"> |
| 19 | 19 | ```yaml title="config.yaml" |
| 20 | 20 | models: |
| 21 | - - name: Grok 2 | |
| 21 | + - name: Grok 4 | |
| 22 | 22 | provider: xAI |
| 23 | - model: grok-2-latest | |
| 23 | + model: grok-4 | |
| 24 | 24 | apiKey: <YOUR_XAI_API_KEY> |
| 25 | 25 | ``` |
| 26 | 26 | </Tab> |
| @@ -29,9 +29,9 @@ | ||
| 29 | 29 | { |
| 30 | 30 | "models": [ |
| 31 | 31 | { |
| 32 | - "title": "Grok 2", | |
| 32 | + "title": "Grok 4", | |
| 33 | 33 | "provider": "xAI", |
| 34 | - "model": "grok-2-latest", | |
| 34 | + "model": "grok-4", | |
| 35 | 35 | "apiKey": "<YOUR_XAI_API_KEY>" |
| 36 | 36 | } |
| 37 | 37 | ] |
modified extensions/intellij/gradle.properties +1 −1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | pluginName=continue-intellij-extension |
| 4 | 4 | pluginRepositoryUrl=https://github.com/continuedev/continue |
| 5 | 5 | # SemVer format -> https://semver.org |
| 6 | -pluginVersion=1.0.29 | |
| 6 | +pluginVersion=1.0.30 | |
| 7 | 7 | # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html |
| 8 | 8 | pluginSinceBuild=223 |
| 9 | 9 | # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension |
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +1 −0
| @@ -113,6 +113,7 @@ | ||
| 113 | 113 | "llm/compileChat", |
| 114 | 114 | "streamDiffLines", |
| 115 | 115 | "chatDescriber/describe", |
| 116 | + "conversation/compact", | |
| 116 | 117 | "stats/getTokensPerDay", |
| 117 | 118 | "stats/getTokensPerModel", |
| 118 | 119 | // Codebase |
modified extensions/vscode/e2e/README.md +1 −1
| @@ -38,4 +38,4 @@ | ||
| 38 | 38 | |
| 39 | 39 | ### Quirks |
| 40 | 40 | |
| 41 | -- For non-macOS systems, `codesign` is not available. You should run `npm run e2e:all-non-mac` instead of `npm run e2e:all`. | |
| No newline at the end of the file | ||
| 41 | +- For non-macOS systems, `codesign` is not available. You should run `npm run e2e:all-non-mac` instead of `npm run e2e:all`. |
modified extensions/vscode/e2e/TestUtils.ts +7 −3
| @@ -1,15 +1,19 @@ | ||
| 1 | 1 | import { expect } from "chai"; |
| 2 | 2 | import { Key } from "vscode-extension-tester"; |
| 3 | 3 | |
| 4 | -import { access, constants } from 'fs/promises'; | |
| 4 | +import { access, constants } from "fs/promises"; | |
| 5 | 5 | import * as path from "path"; |
| 6 | 6 | import { DEFAULT_TIMEOUT } from "./constants"; |
| 7 | 7 | |
| 8 | 8 | export class TestUtils { |
| 9 | 9 | public static CONTINUE_GLOBAL_DIR = process.env.CONTINUE_GLOBAL_DIR ?? ""; |
| 10 | - | |
| 10 | + | |
| 11 | 11 | public static getGlobalContextFilePath(): string { |
| 12 | - return path.join(TestUtils.CONTINUE_GLOBAL_DIR, "index", "globalContext.json"); | |
| 12 | + return path.join( | |
| 13 | + TestUtils.CONTINUE_GLOBAL_DIR, | |
| 14 | + "index", | |
| 15 | + "globalContext.json", | |
| 16 | + ); | |
| 13 | 17 | } |
| 14 | 18 | |
| 15 | 19 | public static async fileExists(path: string): Promise<boolean> { |
modified extensions/vscode/e2e/actions/NextEdit.actions.ts +11 −9
| @@ -12,12 +12,14 @@ | ||
| 12 | 12 | public static async acceptNextEditSuggestion(editor: TextEditor) { |
| 13 | 13 | const hasDecoration = await NextEditActions.forceNextEdit(editor); |
| 14 | 14 | expect(hasDecoration).to.be.true; |
| 15 | - | |
| 16 | - await new Workbench().executeCommand("Continue: Accept Next Edit Suggestion"); | |
| 15 | + | |
| 16 | + await new Workbench().executeCommand( | |
| 17 | + "Continue: Accept Next Edit Suggestion", | |
| 18 | + ); | |
| 17 | 19 | |
| 18 | 20 | // Check if HELLO is written into the editor. |
| 19 | 21 | const editorText = await editor.getTextAtLine(1); |
| 20 | - | |
| 22 | + | |
| 21 | 23 | return editorText === "HELLO"; |
| 22 | 24 | } |
| 23 | 25 | |
| @@ -27,12 +29,12 @@ | ||
| 27 | 29 | public static async rejectNextEditSuggestion(editor: TextEditor) { |
| 28 | 30 | const hasDecoration = await NextEditActions.forceNextEdit(editor); |
| 29 | 31 | expect(hasDecoration).to.be.true; |
| 30 | - | |
| 32 | + | |
| 31 | 33 | await new Workbench().executeCommand("Continue: Hide Next Edit Suggestion"); |
| 32 | 34 | |
| 33 | 35 | // Check if the editor text didn't change. |
| 34 | 36 | const editorText = await editor.getText(); |
| 35 | - | |
| 37 | + | |
| 36 | 38 | return editorText === "def main():\n "; |
| 37 | 39 | } |
| 38 | 40 | |
| @@ -45,16 +47,16 @@ | ||
| 45 | 47 | |
| 46 | 48 | await new Workbench().executeCommand("Continue: Force Next Edit"); |
| 47 | 49 | await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XL); |
| 48 | - | |
| 50 | + | |
| 49 | 51 | const svgDecoration = await TestUtils.waitForSuccess( |
| 50 | 52 | () => NextEditSelectors.getSvgDecoration(VSBrowser.instance.driver), |
| 51 | - DEFAULT_TIMEOUT.XL | |
| 53 | + DEFAULT_TIMEOUT.XL, | |
| 52 | 54 | ); |
| 53 | - | |
| 55 | + | |
| 54 | 56 | return svgDecoration !== null; |
| 55 | 57 | } |
| 56 | 58 | |
| 57 | 59 | public static async reload(): Promise<void> { |
| 58 | - await new Workbench().executeCommand('workbench.action.reloadWindow'); | |
| 60 | + await new Workbench().executeCommand("workbench.action.reloadWindow"); | |
| 59 | 61 | } |
| 60 | 62 | } |
modified extensions/vscode/e2e/selectors/GUI.selectors.ts +1 −4
| @@ -100,10 +100,7 @@ | ||
| 100 | 100 | } |
| 101 | 101 | |
| 102 | 102 | public static getNthMessageDeleteButton(view: WebView, index: number) { |
| 103 | - return SelectorUtils.getElementByDataTestId( | |
| 104 | - view, | |
| 105 | - `delete-button-${index}`, | |
| 106 | - ); | |
| 103 | + return SelectorUtils.getElementByDataTestId(view, `delete-button-${index}`); | |
| 107 | 104 | } |
| 108 | 105 | |
| 109 | 106 | public static getModelDropdownOption(view: WebView, option: string) { |
modified extensions/vscode/e2e/selectors/NextEdit.selectors.ts +2 −2
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | try { |
| 9 | 9 | const decorations = await driver.findElement( |
| 10 | 10 | // By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]") |
| 11 | - By.css("[class*='TextEditorDecorationType']") | |
| 11 | + By.css("[class*='TextEditorDecorationType']"), | |
| 12 | 12 | ); |
| 13 | 13 | return decorations ?? null; |
| 14 | 14 | } catch (error) { |
| @@ -16,4 +16,4 @@ | ||
| 16 | 16 | return null; |
| 17 | 17 | } |
| 18 | 18 | } |
| 19 | -} | |
| No newline at the end of the file | ||
| 19 | +} |
modified extensions/vscode/e2e/tests/GUI.test.ts +1 −1
| @@ -584,4 +584,4 @@ | ||
| 584 | 584 | ); |
| 585 | 585 | }).timeout(DEFAULT_TIMEOUT.XL); |
| 586 | 586 | }); |
| 587 | -}); | |
| No newline at the end of the file | ||
| 587 | +}); |
modified extensions/vscode/e2e/tests/NextEdit.test.ts +47 −37
| @@ -7,55 +7,59 @@ | ||
| 7 | 7 | import { DEFAULT_TIMEOUT } from "../constants"; |
| 8 | 8 | import { TestUtils } from "../TestUtils"; |
| 9 | 9 | |
| 10 | -describe("Next Edit", () => { | |
| 10 | +describe("Next Edit", () => { | |
| 11 | 11 | let editor: TextEditor; |
| 12 | 12 | |
| 13 | 13 | before(async function () { |
| 14 | 14 | // this.timeout(DEFAULT_TIMEOUT.XL); |
| 15 | 15 | |
| 16 | 16 | const globalContextPath = TestUtils.getGlobalContextFilePath(); |
| 17 | - | |
| 17 | + | |
| 18 | 18 | // Update config.json to add optInNextEditFeature. |
| 19 | 19 | // globalContext.json does not exist in CI before this test runs. |
| 20 | 20 | if (await TestUtils.fileExists(globalContextPath)) { |
| 21 | 21 | const globalContext = await fs.readFile(globalContextPath, "utf8"); |
| 22 | 22 | const sharedConfig = JSON.parse(globalContext).sharedConfig; |
| 23 | - | |
| 23 | + | |
| 24 | 24 | const sharedConfigWithNextEditEnabled = { |
| 25 | 25 | ...sharedConfig, |
| 26 | - "optInNextEditFeature": true | |
| 26 | + optInNextEditFeature: true, | |
| 27 | 27 | }; |
| 28 | - | |
| 28 | + | |
| 29 | 29 | const globalContextWithNextEditEnabled = { |
| 30 | 30 | ...JSON.parse(globalContext), |
| 31 | - "sharedConfig": sharedConfigWithNextEditEnabled | |
| 31 | + sharedConfig: sharedConfigWithNextEditEnabled, | |
| 32 | 32 | }; |
| 33 | - | |
| 34 | - await fs.writeFile(globalContextPath, JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8"); | |
| 33 | + | |
| 34 | + await fs.writeFile( | |
| 35 | + globalContextPath, | |
| 36 | + JSON.stringify(globalContextWithNextEditEnabled, null, 2), | |
| 37 | + "utf8", | |
| 38 | + ); | |
| 35 | 39 | } else { |
| 36 | 40 | await fs.writeFile( |
| 37 | - globalContextPath, | |
| 38 | - JSON.stringify( | |
| 39 | - { | |
| 40 | - sharedConfig: { | |
| 41 | - optInNextEditFeature: true | |
| 42 | - }, | |
| 43 | - selectedModelsByProfileId: { | |
| 44 | - local: { | |
| 45 | - chat: "TEST LLM", | |
| 46 | - edit: "TEST LLM", | |
| 47 | - apply: "TEST LLM", | |
| 48 | - embed: "Transformers.js (Built-In)", | |
| 49 | - autocomplete: "TEST LLM", | |
| 50 | - rerank: null, | |
| 51 | - summarize: null | |
| 52 | - } | |
| 53 | - } | |
| 54 | - }, | |
| 55 | - null, | |
| 56 | - 2, | |
| 57 | - ), | |
| 58 | - ); | |
| 41 | + globalContextPath, | |
| 42 | + JSON.stringify( | |
| 43 | + { | |
| 44 | + sharedConfig: { | |
| 45 | + optInNextEditFeature: true, | |
| 46 | + }, | |
| 47 | + selectedModelsByProfileId: { | |
| 48 | + local: { | |
| 49 | + chat: "TEST LLM", | |
| 50 | + edit: "TEST LLM", | |
| 51 | + apply: "TEST LLM", | |
| 52 | + embed: "Transformers.js (Built-In)", | |
| 53 | + autocomplete: "TEST LLM", | |
| 54 | + rerank: null, | |
| 55 | + summarize: null, | |
| 56 | + }, | |
| 57 | + }, | |
| 58 | + }, | |
| 59 | + null, | |
| 60 | + 2, | |
| 61 | + ), | |
| 62 | + ); | |
| 59 | 63 | } |
| 60 | 64 | |
| 61 | 65 | await NextEditActions.reload(); |
| @@ -77,20 +81,27 @@ | ||
| 77 | 81 | |
| 78 | 82 | after(async function () { |
| 79 | 83 | // this.timeout(DEFAULT_TIMEOUT.XL); |
| 80 | - | |
| 84 | + | |
| 81 | 85 | // Update config.json to delete optInNextEditFeature. |
| 82 | - const globalContext = await fs.readFile(TestUtils.getGlobalContextFilePath(), "utf8"); | |
| 86 | + const globalContext = await fs.readFile( | |
| 87 | + TestUtils.getGlobalContextFilePath(), | |
| 88 | + "utf8", | |
| 89 | + ); | |
| 83 | 90 | const sharedConfig = JSON.parse(globalContext).sharedConfig; |
| 84 | - | |
| 91 | + | |
| 85 | 92 | const sharedConfigWithoutNextEdit = { ...sharedConfig }; |
| 86 | 93 | delete sharedConfigWithoutNextEdit.optInNextEditFeature; |
| 87 | 94 | |
| 88 | 95 | const globalContextWithNextEditEnabled = { |
| 89 | 96 | ...JSON.parse(globalContext), |
| 90 | - "sharedConfig": sharedConfigWithoutNextEdit | |
| 97 | + sharedConfig: sharedConfigWithoutNextEdit, | |
| 91 | 98 | }; |
| 92 | 99 | |
| 93 | - await fs.writeFile(TestUtils.getGlobalContextFilePath(), JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8"); | |
| 100 | + await fs.writeFile( | |
| 101 | + TestUtils.getGlobalContextFilePath(), | |
| 102 | + JSON.stringify(globalContextWithNextEditEnabled, null, 2), | |
| 103 | + "utf8", | |
| 104 | + ); | |
| 94 | 105 | await NextEditActions.reload(); |
| 95 | 106 | }).timeout(DEFAULT_TIMEOUT.XL); |
| 96 | 107 | |
| @@ -116,5 +127,4 @@ | ||
| 116 | 127 | const rejected = await NextEditActions.rejectNextEditSuggestion(editor); |
| 117 | 128 | expect(rejected).to.be.true; |
| 118 | 129 | }).timeout(DEFAULT_TIMEOUT.XXL); |
| 119 | - | |
| 120 | -}); | |
| No newline at the end of the file | ||
| 130 | +}); |
modified extensions/vscode/package.json +1 −1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | "name": "continue", |
| 3 | 3 | "icon": "media/icon.png", |
| 4 | 4 | "author": "Continue Dev, Inc", |
| 5 | - "version": "1.1.65", | |
| 5 | + "version": "1.1.66", | |
| 6 | 6 | "repository": { |
| 7 | 7 | "type": "git", |
| 8 | 8 | "url": "https://github.com/continuedev/continue" |
modified gui/src/components/Layout.tsx +1 −0
| @@ -47,6 +47,7 @@ | ||
| 47 | 47 | const dispatch = useAppDispatch(); |
| 48 | 48 | const onboardingCard = useOnboardingCard(); |
| 49 | 49 | const ideMessenger = useContext(IdeMessengerContext); |
| 50 | + const currentSessionId = useAppSelector((state) => state.session.id); | |
| 50 | 51 | |
| 51 | 52 | const { mainEditor } = useMainEditor(); |
| 52 | 53 | const dialogMessage = useAppSelector((state) => state.ui.dialogMessage); |
added gui/src/components/StepContainer/ConversationSummary.tsx +81 −0
| @@ -0,0 +1,81 @@ | ||
| 1 | +import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid"; | |
| 2 | +import { TrashIcon } from "@heroicons/react/24/outline"; | |
| 3 | +import { ChatHistoryItem } from "core"; | |
| 4 | +import { useState } from "react"; | |
| 5 | +import { AnimatedEllipsis } from "../"; | |
| 6 | +import { useAppSelector } from "../../redux/hooks"; | |
| 7 | +import StyledMarkdownPreview from "../StyledMarkdownPreview"; | |
| 8 | +import { useDeleteCompaction } from "../../util/compactConversation"; | |
| 9 | +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; | |
| 10 | + | |
| 11 | +interface ConversationSummaryProps { | |
| 12 | + item: ChatHistoryItem; | |
| 13 | + index: number; | |
| 14 | +} | |
| 15 | + | |
| 16 | +export default function ConversationSummary(props: ConversationSummaryProps) { | |
| 17 | + const [open, setOpen] = useState(false); | |
| 18 | + const isLoading = useAppSelector( | |
| 19 | + (state) => state.session.compactionLoading[props.index] || false, | |
| 20 | + ); | |
| 21 | + const deleteCompaction = useDeleteCompaction(); | |
| 22 | + | |
| 23 | + if (!props.item.conversationSummary && !isLoading) { | |
| 24 | + return null; | |
| 25 | + } | |
| 26 | + | |
| 27 | + // Loading state - much simpler | |
| 28 | + if (isLoading) { | |
| 29 | + return ( | |
| 30 | + <div className="mx-1.5 mb-4 mt-2"> | |
| 31 | + <div className="bg-vsc-input-background rounded-md shadow-sm"> | |
| 32 | + <div className="text-description flex items-center justify-start px-3 py-2 text-xs"> | |
| 33 | + <span>Generating conversation summary</span> | |
| 34 | + <AnimatedEllipsis /> | |
| 35 | + </div> | |
| 36 | + </div> | |
| 37 | + </div> | |
| 38 | + ); | |
| 39 | + } | |
| 40 | + | |
| 41 | + // Normal state with content | |
| 42 | + return ( | |
| 43 | + <div className="mx-1.5 mb-4 mt-2"> | |
| 44 | + <div className="bg-vsc-input-background rounded-md shadow-sm"> | |
| 45 | + <div | |
| 46 | + className="text-description flex cursor-pointer items-center gap-2 px-3 py-2 text-xs transition-colors duration-200 hover:brightness-105" | |
| 47 | + onClick={() => setOpen(!open)} | |
| 48 | + > | |
| 49 | + {open ? ( | |
| 50 | + <ChevronUpIcon className="h-3 w-3" /> | |
| 51 | + ) : ( | |
| 52 | + <ChevronDownIcon className="h-3 w-3" /> | |
| 53 | + )} | |
| 54 | + <span className="flex-1">Conversation Summary</span> | |
| 55 | + <HeaderButtonWithToolTip | |
| 56 | + text="Delete summary" | |
| 57 | + onClick={(e) => { | |
| 58 | + e.stopPropagation(); | |
| 59 | + deleteCompaction(props.index); | |
| 60 | + }} | |
| 61 | + > | |
| 62 | + <TrashIcon className="text-description-muted h-3 w-3" /> | |
| 63 | + </HeaderButtonWithToolTip> | |
| 64 | + </div> | |
| 65 | + {open && ( | |
| 66 | + <> | |
| 67 | + <div className="border-border border-0 border-t border-solid"></div> | |
| 68 | + <div className="max-h-[400px] overflow-y-auto px-3 pb-3 pt-2"> | |
| 69 | + <StyledMarkdownPreview | |
| 70 | + isRenderingInStepContainer | |
| 71 | + source={props.item.conversationSummary} | |
| 72 | + itemIndex={props.index} | |
| 73 | + useParentBackgroundColor | |
| 74 | + /> | |
| 75 | + </div> | |
| 76 | + </> | |
| 77 | + )} | |
| 78 | + </div> | |
| 79 | + </div> | |
| 80 | + ); | |
| 81 | +} |
modified gui/src/components/StepContainer/ResponseActions.tsx +42 −3
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { |
| 2 | + ArrowsPointingInIcon, | |
| 2 | 3 | BarsArrowDownIcon, |
| 3 | 4 | PencilSquareIcon, |
| 4 | 5 | TrashIcon, |
| @@ -7,10 +8,10 @@ | ||
| 7 | 8 | import { modelSupportsTools } from "core/llm/autodetect"; |
| 8 | 9 | import { renderChatMessage } from "core/util/messageContent"; |
| 9 | 10 | import { useMemo } from "react"; |
| 10 | -import { useDispatch } from "react-redux"; | |
| 11 | -import { useAppSelector } from "../../redux/hooks"; | |
| 11 | +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; | |
| 12 | 12 | import { selectSelectedChatModel } from "../../redux/slices/configSlice"; |
| 13 | 13 | import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; |
| 14 | +import { useCompactConversation } from "../../util/compactConversation"; | |
| 14 | 15 | import { FeedbackButtons } from "../FeedbackButtons"; |
| 15 | 16 | import { GenerateRuleDialog } from "../GenerateRuleDialog"; |
| 16 | 17 | import { CopyIconButton } from "../gui/CopyIconButton"; |
| @@ -33,12 +34,26 @@ | ||
| 33 | 34 | onDelete, |
| 34 | 35 | isLast, |
| 35 | 36 | }: ResponseActionsProps) { |
| 36 | - const dispatch = useDispatch(); | |
| 37 | + const dispatch = useAppDispatch(); | |
| 37 | 38 | const selectedModel = useAppSelector(selectSelectedChatModel); |
| 39 | + const contextPercentage = useAppSelector( | |
| 40 | + (state) => state.session.contextPercentage, | |
| 41 | + ); | |
| 42 | + const isPruned = useAppSelector((state) => state.session.isPruned); | |
| 38 | 43 | const ruleGenerationSupported = useMemo(() => { |
| 39 | 44 | return selectedModel && modelSupportsTools(selectedModel); |
| 40 | 45 | }, [selectedModel]); |
| 41 | 46 | |
| 47 | + const percent = Math.round((contextPercentage ?? 0) * 100); | |
| 48 | + const buttonColorClass = | |
| 49 | + isLast && (isPruned || percent > 80) | |
| 50 | + ? "text-warning" | |
| 51 | + : "text-description-muted"; | |
| 52 | + | |
| 53 | + const showLabel = isLast && (isPruned || percent >= 60); | |
| 54 | + | |
| 55 | + const compactConversation = useCompactConversation(); | |
| 56 | + | |
| 42 | 57 | const onGenerateRule = () => { |
| 43 | 58 | dispatch(setShowDialog(true)); |
| 44 | 59 | dispatch(setDialogMessage(<GenerateRuleDialog />)); |
| @@ -46,6 +61,30 @@ | ||
| 46 | 61 | |
| 47 | 62 | return ( |
| 48 | 63 | <div className="text-description-muted mx-2 flex cursor-default items-center justify-end space-x-1 bg-transparent pb-0 text-xs"> |
| 64 | + <HeaderButtonWithToolTip | |
| 65 | + testId={`compact-button-${index}`} | |
| 66 | + text={ | |
| 67 | + showLabel | |
| 68 | + ? "Summarize conversation to reduce context length" | |
| 69 | + : "Compact conversation" | |
| 70 | + } | |
| 71 | + tabIndex={-1} | |
| 72 | + onClick={() => compactConversation(index)} | |
| 73 | + > | |
| 74 | + <div className="flex items-center space-x-1"> | |
| 75 | + <ArrowsPointingInIcon | |
| 76 | + className={`h-3.5 w-3.5 ${buttonColorClass || "text-description-muted"}`} | |
| 77 | + /> | |
| 78 | + {showLabel && ( | |
| 79 | + <span | |
| 80 | + className={`text-xs ${buttonColorClass || "text-description-muted"}`} | |
| 81 | + > | |
| 82 | + Compact conversation | |
| 83 | + </span> | |
| 84 | + )} | |
| 85 | + </div> | |
| 86 | + </HeaderButtonWithToolTip> | |
| 87 | + | |
| 49 | 88 | {isLast && ruleGenerationSupported && ( |
| 50 | 89 | <HeaderButtonWithToolTip |
| 51 | 90 | tabIndex={-1} |
modified gui/src/components/StepContainer/StepContainer.tsx +32 −5
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | import { selectUIConfig } from "../../redux/slices/configSlice"; |
| 7 | 7 | import { deleteMessage } from "../../redux/slices/sessionSlice"; |
| 8 | 8 | import StyledMarkdownPreview from "../StyledMarkdownPreview"; |
| 9 | +import ConversationSummary from "./ConversationSummary"; | |
| 9 | 10 | import Reasoning from "./Reasoning"; |
| 10 | 11 | import ResponseActions from "./ResponseActions"; |
| 11 | 12 | import ThinkingIndicator from "./ThinkingIndicator"; |
| @@ -14,6 +15,7 @@ | ||
| 14 | 15 | item: ChatHistoryItem; |
| 15 | 16 | index: number; |
| 16 | 17 | isLast: boolean; |
| 18 | + latestSummaryIndex?: number; | |
| 17 | 19 | } |
| 18 | 20 | |
| 19 | 21 | export default function StepContainer(props: StepContainerProps) { |
| @@ -23,11 +25,15 @@ | ||
| 23 | 25 | const historyItemAfterThis = useAppSelector( |
| 24 | 26 | (state) => state.session.history[props.index + 1], |
| 25 | 27 | ); |
| 26 | - const warningMessage = useAppSelector( | |
| 27 | - (state) => state.session.warningMessage, | |
| 28 | - ); | |
| 29 | 28 | const uiConfig = useAppSelector(selectUIConfig); |
| 30 | 29 | |
| 30 | + // Calculate dimming and indicator state based on latest summary index | |
| 31 | + const latestSummaryIndex = props.latestSummaryIndex ?? -1; | |
| 32 | + const isBeforeLatestSummary = | |
| 33 | + latestSummaryIndex !== -1 && props.index <= latestSummaryIndex; | |
| 34 | + const isLatestSummary = | |
| 35 | + latestSummaryIndex !== -1 && props.index === latestSummaryIndex; | |
| 36 | + | |
| 31 | 37 | const isNextMsgAssistantOrThinking = |
| 32 | 38 | historyItemAfterThis?.message.role === "assistant" || |
| 33 | 39 | historyItemAfterThis?.message.role === "thinking" || |
| @@ -83,7 +89,9 @@ | ||
| 83 | 89 | |
| 84 | 90 | return ( |
| 85 | 91 | <div> |
| 86 | - <div className="bg-background overflow-hidden p-1 px-1.5"> | |
| 92 | + <div | |
| 93 | + className={`bg-background p-1 px-1.5 ${isBeforeLatestSummary ? "opacity-35" : ""}`} | |
| 94 | + > | |
| 87 | 95 | {uiConfig?.displayRawMarkdown ? ( |
| 88 | 96 | <pre className="text-2xs max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4"> |
| 89 | 97 | {renderChatMessage(props.item.message)} |
| @@ -101,9 +109,12 @@ | ||
| 101 | 109 | )} |
| 102 | 110 | {props.isLast && <ThinkingIndicator historyItem={props.item} />} |
| 103 | 111 | </div> |
| 112 | + | |
| 104 | 113 | {shouldRenderResponseAction() && ( |
| 105 | 114 | // We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on stream complete |
| 106 | - <div className={`mt-2 h-7 transition-opacity duration-300 ease-in-out`}> | |
| 115 | + <div | |
| 116 | + className={`mt-2 h-7 transition-opacity duration-300 ease-in-out ${isBeforeLatestSummary ? "opacity-35" : ""}`} | |
| 117 | + > | |
| 107 | 118 | {!isStreaming && ( |
| 108 | 119 | <ResponseActions |
| 109 | 120 | isTruncated={isTruncated} |
| @@ -116,6 +127,22 @@ | ||
| 116 | 127 | )} |
| 117 | 128 | </div> |
| 118 | 129 | )} |
| 130 | + | |
| 131 | + {/* Show compaction indicator for the latest summary */} | |
| 132 | + {isLatestSummary && ( | |
| 133 | + <div className="mx-1.5 my-5"> | |
| 134 | + <div className="flex items-center"> | |
| 135 | + <div className="border-border flex-1 border-t border-solid"></div> | |
| 136 | + <span className="text-description mx-3 text-xs"> | |
| 137 | + Previous Conversation Compacted | |
| 138 | + </span> | |
| 139 | + <div className="border-border flex-1 border-t border-solid"></div> | |
| 140 | + </div> | |
| 141 | + </div> | |
| 142 | + )} | |
| 143 | + | |
| 144 | + {/* ConversationSummary is outside the dimmed container so it's always at full opacity */} | |
| 145 | + <ConversationSummary item={props.item} index={props.index} /> | |
| 119 | 146 | </div> |
| 120 | 147 | ); |
| 121 | 148 | } |
modified gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +1 −1
| @@ -265,7 +265,7 @@ | ||
| 265 | 265 | return ( |
| 266 | 266 | <div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor mb-2 mt-2 flex min-w-0 flex-col outline outline-1"> |
| 267 | 267 | <div |
| 268 | - className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "border-command-border border-b" : ""}`} | |
| 268 | + className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "rounded-t-default border-command-border border-b" : "rounded-default"}`} | |
| 269 | 269 | style={{ fontSize: `${getFontSize() - 2}px` }} |
| 270 | 270 | > |
| 271 | 271 | <div className="flex max-w-[50%] flex-row items-center"> |
modified gui/src/components/console/Details.tsx +5 −0
| @@ -117,6 +117,11 @@ | ||
| 117 | 117 | format={(v: number) => v.toFixed(1)} |
| 118 | 118 | ></Cell> |
| 119 | 119 | </div> |
| 120 | + {/* {summary.costBreakdown && ( | |
| 121 | + <pre className="whitespace-pre-wrap px-2 text-sm"> | |
| 122 | + {summary.costBreakdown.breakdown} | |
| 123 | + </pre> | |
| 124 | + )} */} | |
| 120 | 125 | </div> |
| 121 | 126 | <div |
| 122 | 127 | ref={scrollTop} |
modified gui/src/components/console/Layout.tsx +42 −8
| @@ -2,11 +2,13 @@ | ||
| 2 | 2 | import useLLMLog from "../../hooks/useLLMLog"; |
| 3 | 3 | import Details from "./Details"; |
| 4 | 4 | import List from "./List"; |
| 5 | +import TotalUsage from "./TotalUsage"; | |
| 5 | 6 | |
| 6 | 7 | export default function Layout() { |
| 7 | 8 | const llmLog = useLLMLog(); |
| 8 | 9 | |
| 9 | 10 | const [selectedId, setSelectedId] = useState<string | undefined>(undefined); |
| 11 | + const [showTotalUsage, setShowTotalUsage] = useState(false); | |
| 10 | 12 | |
| 11 | 13 | const interaction = selectedId |
| 12 | 14 | ? llmLog.interactions.get(selectedId) |
| @@ -16,14 +18,46 @@ | ||
| 16 | 18 | <div>Loading...</div> |
| 17 | 19 | ) : ( |
| 18 | 20 | <div className="flex h-full w-full"> |
| 19 | - <List | |
| 20 | - llmLog={llmLog} | |
| 21 | - onClickInteraction={(interactionId) => { | |
| 22 | - setSelectedId(interactionId); | |
| 23 | - }} | |
| 24 | - ></List> | |
| 25 | - {interaction && ( | |
| 26 | - <Details key="{selectedId}" interaction={interaction}></Details> | |
| 21 | + <div className="flex h-full w-full flex-col"> | |
| 22 | + {/* <div className="flex-shrink-0 border-b border-[color:var(--vscode-panel-border)] p-3"> | |
| 23 | + <button | |
| 24 | + onClick={() => setShowTotalUsage(true)} | |
| 25 | + className="float-right cursor-pointer border-none bg-transparent text-sm text-[color:var(--vscode-textLink-foreground)] underline hover:text-[color:var(--vscode-textLink-activeForeground)]" | |
| 26 | + > | |
| 27 | + View Total Usage Summary | |
| 28 | + </button> | |
| 29 | + </div> */} | |
| 30 | + <div className="flex min-h-0 flex-1 overflow-hidden"> | |
| 31 | + <List | |
| 32 | + llmLog={llmLog} | |
| 33 | + onClickInteraction={(interactionId) => { | |
| 34 | + setSelectedId(interactionId); | |
| 35 | + }} | |
| 36 | + ></List> | |
| 37 | + {interaction && ( | |
| 38 | + <Details key="{selectedId}" interaction={interaction}></Details> | |
| 39 | + )} | |
| 40 | + </div> | |
| 41 | + </div> | |
| 42 | + | |
| 43 | + {/* Full-screen popover for TotalUsage */} | |
| 44 | + {showTotalUsage && ( | |
| 45 | + <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50"> | |
| 46 | + <div className="relative h-full w-full max-w-6xl overflow-hidden bg-[color:var(--vscode-panel-background)] shadow-2xl"> | |
| 47 | + {/* Close button */} | |
| 48 | + <button | |
| 49 | + onClick={() => setShowTotalUsage(false)} | |
| 50 | + className="absolute right-4 top-4 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-[color:var(--vscode-button-background)] text-[color:var(--vscode-button-foreground)] transition-colors hover:bg-[color:var(--vscode-button-hoverBackground)]" | |
| 51 | + > | |
| 52 | + × | |
| 53 | + </button> | |
| 54 | + | |
| 55 | + {/* Content container with scroll */} | |
| 56 | + <div className="h-full overflow-y-auto p-6"> | |
| 57 | + <TotalUsage llmLog={llmLog} /> | |
| 58 | + </div> | |
| 59 | + </div> | |
| 60 | + </div> | |
| 27 | 61 | )} |
| 28 | 62 | </div> |
| 29 | 63 | ); |
added gui/src/components/console/TotalUsage.tsx +362 −0
| @@ -0,0 +1,362 @@ | ||
| 1 | +import { calculateRequestCost } from "core/llm/utils/calculateRequestCost"; | |
| 2 | +import React, { useMemo, useState } from "react"; | |
| 3 | +import { LLMLog } from "../../hooks/useLLMLog"; | |
| 4 | +import useTotalUsage from "../../hooks/useTotalUsage"; | |
| 5 | + | |
| 6 | +interface TotalUsageProps { | |
| 7 | + llmLog: LLMLog; | |
| 8 | +} | |
| 9 | + | |
| 10 | +const StatCard: React.FC<{ label: string; value: number; color?: string }> = ({ | |
| 11 | + label, | |
| 12 | + value, | |
| 13 | + color = "var(--vscode-foreground)", | |
| 14 | +}) => ( | |
| 15 | + <div className="flex flex-col items-center rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3"> | |
| 16 | + <div className="text-sm text-[color:var(--vscode-descriptionForeground)]"> | |
| 17 | + {label} | |
| 18 | + </div> | |
| 19 | + <div className="text-lg font-semibold" style={{ color }}> | |
| 20 | + {value.toLocaleString()} | |
| 21 | + </div> | |
| 22 | + </div> | |
| 23 | +); | |
| 24 | + | |
| 25 | +const CostChart: React.FC<{ llmLog: LLMLog }> = ({ llmLog }) => { | |
| 26 | + const chartData = useMemo(() => { | |
| 27 | + let cumulativeCost = 0; | |
| 28 | + const dataPoints: { interaction: number; cost: number }[] = []; | |
| 29 | + | |
| 30 | + llmLog.order.forEach((id, index) => { | |
| 31 | + const interaction = llmLog.interactions.get(id); | |
| 32 | + | |
| 33 | + // Calculate cost for this interaction if we have the necessary data | |
| 34 | + if ( | |
| 35 | + interaction?.end?.usage && | |
| 36 | + interaction.start?.provider && | |
| 37 | + interaction.start?.options?.model | |
| 38 | + ) { | |
| 39 | + const costBreakdown = calculateRequestCost( | |
| 40 | + interaction.start.provider, | |
| 41 | + interaction.start.options.model, | |
| 42 | + interaction.end.usage, | |
| 43 | + ); | |
| 44 | + if (costBreakdown) { | |
| 45 | + cumulativeCost += costBreakdown.cost; | |
| 46 | + } | |
| 47 | + } | |
| 48 | + | |
| 49 | + dataPoints.push({ interaction: index + 1, cost: cumulativeCost }); | |
| 50 | + }); | |
| 51 | + | |
| 52 | + return dataPoints; | |
| 53 | + }, [llmLog.order, llmLog.interactions]); | |
| 54 | + | |
| 55 | + if (chartData.length === 0 || chartData[chartData.length - 1].cost === 0) { | |
| 56 | + return null; | |
| 57 | + } | |
| 58 | + | |
| 59 | + const maxCost = Math.max(...chartData.map((d) => d.cost)); | |
| 60 | + const maxInteraction = chartData.length; | |
| 61 | + const chartWidth = 400; | |
| 62 | + const chartHeight = 200; | |
| 63 | + const padding = 40; | |
| 64 | + | |
| 65 | + const xScale = (interaction: number) => | |
| 66 | + ((interaction - 1) / (maxInteraction - 1)) * (chartWidth - 2 * padding) + | |
| 67 | + padding; | |
| 68 | + | |
| 69 | + const yScale = (cost: number) => | |
| 70 | + chartHeight - padding - (cost / maxCost) * (chartHeight - 2 * padding); | |
| 71 | + | |
| 72 | + const pathData = chartData | |
| 73 | + .map( | |
| 74 | + (d, i) => | |
| 75 | + `${i === 0 ? "M" : "L"} ${xScale(d.interaction)} ${yScale(d.cost)}`, | |
| 76 | + ) | |
| 77 | + .join(" "); | |
| 78 | + | |
| 79 | + return ( | |
| 80 | + <div className="mb-4 rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-4"> | |
| 81 | + <h3 className="mb-3 text-sm font-semibold text-[color:var(--vscode-foreground)]"> | |
| 82 | + Cumulative Cost Over Interactions | |
| 83 | + </h3> | |
| 84 | + <div className="flex justify-center"> | |
| 85 | + <svg | |
| 86 | + width={chartWidth} | |
| 87 | + height={chartHeight} | |
| 88 | + className="overflow-visible" | |
| 89 | + > | |
| 90 | + {/* Grid lines */} | |
| 91 | + <defs> | |
| 92 | + <pattern | |
| 93 | + id="grid" | |
| 94 | + width="20" | |
| 95 | + height="20" | |
| 96 | + patternUnits="userSpaceOnUse" | |
| 97 | + > | |
| 98 | + <path | |
| 99 | + d="M 20 0 L 0 0 0 20" | |
| 100 | + fill="none" | |
| 101 | + stroke="var(--vscode-panel-border)" | |
| 102 | + strokeWidth="0.5" | |
| 103 | + opacity="0.3" | |
| 104 | + /> | |
| 105 | + </pattern> | |
| 106 | + </defs> | |
| 107 | + <rect width={chartWidth} height={chartHeight} fill="url(#grid)" /> | |
| 108 | + | |
| 109 | + {/* Chart area background */} | |
| 110 | + <rect | |
| 111 | + x={padding} | |
| 112 | + y={padding} | |
| 113 | + width={chartWidth - 2 * padding} | |
| 114 | + height={chartHeight - 2 * padding} | |
| 115 | + fill="var(--vscode-editor-background)" | |
| 116 | + stroke="var(--vscode-panel-border)" | |
| 117 | + strokeWidth="1" | |
| 118 | + /> | |
| 119 | + | |
| 120 | + {/* Cost line */} | |
| 121 | + <path | |
| 122 | + d={pathData} | |
| 123 | + fill="none" | |
| 124 | + stroke="var(--vscode-charts-green)" | |
| 125 | + strokeWidth="2" | |
| 126 | + strokeLinecap="round" | |
| 127 | + /> | |
| 128 | + | |
| 129 | + {/* Data points */} | |
| 130 | + {chartData.map((d, i) => ( | |
| 131 | + <circle | |
| 132 | + key={i} | |
| 133 | + cx={xScale(d.interaction)} | |
| 134 | + cy={yScale(d.cost)} | |
| 135 | + r="3" | |
| 136 | + fill="var(--vscode-charts-green)" | |
| 137 | + stroke="var(--vscode-editor-background)" | |
| 138 | + strokeWidth="1" | |
| 139 | + /> | |
| 140 | + ))} | |
| 141 | + | |
| 142 | + {/* Y-axis labels */} | |
| 143 | + {[0, 0.25, 0.5, 0.75, 1].map((ratio) => { | |
| 144 | + const cost = maxCost * ratio; | |
| 145 | + const y = yScale(cost); | |
| 146 | + return ( | |
| 147 | + <g key={ratio}> | |
| 148 | + <line | |
| 149 | + x1={padding - 5} | |
| 150 | + y1={y} | |
| 151 | + x2={padding} | |
| 152 | + y2={y} | |
| 153 | + stroke="var(--vscode-foreground)" | |
| 154 | + strokeWidth="1" | |
| 155 | + /> | |
| 156 | + <text | |
| 157 | + x={padding - 8} | |
| 158 | + y={y + 4} | |
| 159 | + textAnchor="end" | |
| 160 | + fontSize="10" | |
| 161 | + fill="var(--vscode-descriptionForeground)" | |
| 162 | + > | |
| 163 | + ${cost.toFixed(4)} | |
| 164 | + </text> | |
| 165 | + </g> | |
| 166 | + ); | |
| 167 | + })} | |
| 168 | + | |
| 169 | + {/* X-axis labels */} | |
| 170 | + {[0, 0.25, 0.5, 0.75, 1].map((ratio) => { | |
| 171 | + const interaction = Math.round(1 + ratio * (maxInteraction - 1)); | |
| 172 | + const x = xScale(interaction); | |
| 173 | + return ( | |
| 174 | + <g key={ratio}> | |
| 175 | + <line | |
| 176 | + x1={x} | |
| 177 | + y1={chartHeight - padding} | |
| 178 | + x2={x} | |
| 179 | + y2={chartHeight - padding + 5} | |
| 180 | + stroke="var(--vscode-foreground)" | |
| 181 | + strokeWidth="1" | |
| 182 | + /> | |
| 183 | + <text | |
| 184 | + x={x} | |
| 185 | + y={chartHeight - padding + 18} | |
| 186 | + textAnchor="middle" | |
| 187 | + fontSize="10" | |
| 188 | + fill="var(--vscode-descriptionForeground)" | |
| 189 | + > | |
| 190 | + {interaction} | |
| 191 | + </text> | |
| 192 | + </g> | |
| 193 | + ); | |
| 194 | + })} | |
| 195 | + | |
| 196 | + {/* Axis labels */} | |
| 197 | + <text | |
| 198 | + x={chartWidth / 2} | |
| 199 | + y={chartHeight - 5} | |
| 200 | + textAnchor="middle" | |
| 201 | + fontSize="12" | |
| 202 | + fill="var(--vscode-foreground)" | |
| 203 | + > | |
| 204 | + Interaction Number | |
| 205 | + </text> | |
| 206 | + <text | |
| 207 | + x={15} | |
| 208 | + y={chartHeight / 2} | |
| 209 | + textAnchor="middle" | |
| 210 | + fontSize="12" | |
| 211 | + fill="var(--vscode-foreground)" | |
| 212 | + transform={`rotate(-90 15 ${chartHeight / 2})`} | |
| 213 | + > | |
| 214 | + Cumulative Cost ($) | |
| 215 | + </text> | |
| 216 | + </svg> | |
| 217 | + </div> | |
| 218 | + </div> | |
| 219 | + ); | |
| 220 | +}; | |
| 221 | + | |
| 222 | +const TotalUsage: React.FC<TotalUsageProps> = ({ llmLog }) => { | |
| 223 | + const totalUsage = useTotalUsage(llmLog); | |
| 224 | + const [showCostBreakdown, setShowCostBreakdown] = useState(false); | |
| 225 | + | |
| 226 | + return ( | |
| 227 | + <div className="border-b border-[color:var(--vscode-panel-border)] p-4"> | |
| 228 | + <div className="mb-4 flex items-center justify-between"> | |
| 229 | + <h2 className="text-lg font-semibold text-[color:var(--vscode-foreground)]"> | |
| 230 | + Total Usage Summary | |
| 231 | + </h2> | |
| 232 | + <div className="flex items-center gap-4"> | |
| 233 | + {totalUsage.totalCost > 0 && ( | |
| 234 | + <button | |
| 235 | + onClick={() => setShowCostBreakdown(!showCostBreakdown)} | |
| 236 | + className="cursor-pointer text-lg font-semibold text-[color:var(--vscode-charts-green)] hover:text-[color:var(--vscode-charts-blue)]" | |
| 237 | + > | |
| 238 | + ${totalUsage.totalCost.toFixed(6)} | |
| 239 | + </button> | |
| 240 | + )} | |
| 241 | + <div className="text-sm text-[color:var(--vscode-descriptionForeground)]"> | |
| 242 | + {totalUsage.totalInteractions} interactions | |
| 243 | + </div> | |
| 244 | + </div> | |
| 245 | + </div> | |
| 246 | + | |
| 247 | + {showCostBreakdown && totalUsage.costBreakdowns.length > 0 && ( | |
| 248 | + <div className="mb-4 max-h-32 overflow-y-auto rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3"> | |
| 249 | + <h3 className="mb-2 text-sm font-semibold text-[color:var(--vscode-foreground)]"> | |
| 250 | + Cost Breakdown | |
| 251 | + </h3> | |
| 252 | + <div className="space-y-2 text-xs"> | |
| 253 | + {totalUsage.costBreakdowns.map((breakdown, index) => ( | |
| 254 | + <div | |
| 255 | + key={index} | |
| 256 | + className="border-b border-[color:var(--vscode-panel-border)] pb-2 last:border-b-0" | |
| 257 | + > | |
| 258 | + <pre className="whitespace-pre-wrap text-[color:var(--vscode-descriptionForeground)]"> | |
| 259 | + {breakdown.breakdown} | |
| 260 | + </pre> | |
| 261 | + </div> | |
| 262 | + ))} | |
| 263 | + </div> | |
| 264 | + </div> | |
| 265 | + )} | |
| 266 | + | |
| 267 | + <div className="mb-4 grid grid-cols-2 gap-3 md:grid-cols-4"> | |
| 268 | + <StatCard | |
| 269 | + label="Input Tokens" | |
| 270 | + value={totalUsage.totalPromptTokens} | |
| 271 | + color="var(--vscode-charts-blue)" | |
| 272 | + /> | |
| 273 | + <StatCard | |
| 274 | + label="Output Tokens" | |
| 275 | + value={totalUsage.totalGeneratedTokens} | |
| 276 | + color="var(--vscode-charts-green)" | |
| 277 | + /> | |
| 278 | + <StatCard | |
| 279 | + label="Thinking Tokens" | |
| 280 | + value={totalUsage.totalThinkingTokens} | |
| 281 | + color="var(--vscode-charts-purple)" | |
| 282 | + /> | |
| 283 | + <StatCard | |
| 284 | + label="Cache Read" | |
| 285 | + value={totalUsage.totalCachedTokens} | |
| 286 | + color="var(--vscode-charts-orange)" | |
| 287 | + /> | |
| 288 | + </div> | |
| 289 | + | |
| 290 | + {totalUsage.totalCost > 0 && ( | |
| 291 | + <> | |
| 292 | + <CostChart llmLog={llmLog} /> | |
| 293 | + <div className="mb-4"> | |
| 294 | + <div className="flex flex-col items-center rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3"> | |
| 295 | + <div className="text-sm text-[color:var(--vscode-descriptionForeground)]"> | |
| 296 | + Total Cost | |
| 297 | + </div> | |
| 298 | + <div className="text-2xl font-bold text-[color:var(--vscode-charts-green)]"> | |
| 299 | + ${totalUsage.totalCost.toFixed(6)} | |
| 300 | + </div> | |
| 301 | + <div className="text-xs text-[color:var(--vscode-descriptionForeground)]"> | |
| 302 | + {totalUsage.costBreakdowns.length} cost calculations | |
| 303 | + </div> | |
| 304 | + </div> | |
| 305 | + </div> | |
| 306 | + </> | |
| 307 | + )} | |
| 308 | + | |
| 309 | + {totalUsage.totalCacheWriteTokens > 0 && ( | |
| 310 | + <div className="mb-4 grid grid-cols-1 gap-3 md:grid-cols-2"> | |
| 311 | + <StatCard | |
| 312 | + label="Cache Write" | |
| 313 | + value={totalUsage.totalCacheWriteTokens} | |
| 314 | + color="var(--vscode-charts-red)" | |
| 315 | + /> | |
| 316 | + <div className="flex items-center justify-center rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3"> | |
| 317 | + <div className="text-sm text-[color:var(--vscode-descriptionForeground)]"> | |
| 318 | + Cache Hit Rate:{" "} | |
| 319 | + {totalUsage.totalPromptTokens > 0 | |
| 320 | + ? ( | |
| 321 | + (totalUsage.totalCachedTokens / | |
| 322 | + totalUsage.totalPromptTokens) * | |
| 323 | + 100 | |
| 324 | + ).toFixed(1) | |
| 325 | + : "0"} | |
| 326 | + % | |
| 327 | + </div> | |
| 328 | + </div> | |
| 329 | + </div> | |
| 330 | + )} | |
| 331 | + | |
| 332 | + <div className="grid grid-cols-3 gap-3 text-sm"> | |
| 333 | + <div className="rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-2 text-center"> | |
| 334 | + <div className="text-[color:var(--vscode-charts-green)]"> | |
| 335 | + {totalUsage.totalSuccessfulInteractions} | |
| 336 | + </div> | |
| 337 | + <div className="text-[color:var(--vscode-descriptionForeground)]"> | |
| 338 | + Success | |
| 339 | + </div> | |
| 340 | + </div> | |
| 341 | + <div className="rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-2 text-center"> | |
| 342 | + <div className="text-[color:var(--vscode-charts-red)]"> | |
| 343 | + {totalUsage.totalErrorInteractions} | |
| 344 | + </div> | |
| 345 | + <div className="text-[color:var(--vscode-descriptionForeground)]"> | |
| 346 | + Error | |
| 347 | + </div> | |
| 348 | + </div> | |
| 349 | + <div className="rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-2 text-center"> | |
| 350 | + <div className="text-[color:var(--vscode-charts-yellow)]"> | |
| 351 | + {totalUsage.totalCancelledInteractions} | |
| 352 | + </div> | |
| 353 | + <div className="text-[color:var(--vscode-descriptionForeground)]"> | |
| 354 | + Cancelled | |
| 355 | + </div> | |
| 356 | + </div> | |
| 357 | + </div> | |
| 358 | + </div> | |
| 359 | + ); | |
| 360 | +}; | |
| 361 | + | |
| 362 | +export default TotalUsage; |
added gui/src/components/mainInput/ContextStatus.tsx +89 −0
| @@ -0,0 +1,89 @@ | ||
| 1 | +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; | |
| 2 | +import { saveCurrentSession } from "../../redux/thunks/session"; | |
| 3 | +import { useCompactConversation } from "../../util/compactConversation"; | |
| 4 | +import { ToolTip } from "../gui/Tooltip"; | |
| 5 | + | |
| 6 | +const ContextStatus = () => { | |
| 7 | + const dispatch = useAppDispatch(); | |
| 8 | + const contextPercentage = useAppSelector( | |
| 9 | + (state) => state.session.contextPercentage, | |
| 10 | + ); | |
| 11 | + const history = useAppSelector((state) => state.session.history); | |
| 12 | + const percent = Math.round((contextPercentage ?? 0) * 100); | |
| 13 | + const isPruned = useAppSelector((state) => state.session.isPruned); | |
| 14 | + | |
| 15 | + const compactConversation = useCompactConversation(); | |
| 16 | + if (!isPruned && percent < 60) { | |
| 17 | + return null; | |
| 18 | + } | |
| 19 | + | |
| 20 | + const barColorClass = isPruned | |
| 21 | + ? "bg-error" | |
| 22 | + : percent > 80 | |
| 23 | + ? "bg-warning" | |
| 24 | + : "bg-description"; | |
| 25 | + | |
| 26 | + return ( | |
| 27 | + <div> | |
| 28 | + <ToolTip | |
| 29 | + id="context-status" | |
| 30 | + closeEvents={{ | |
| 31 | + // blur: false, | |
| 32 | + mouseleave: true, | |
| 33 | + click: true, | |
| 34 | + mouseup: false, | |
| 35 | + }} | |
| 36 | + clickable | |
| 37 | + > | |
| 38 | + <div className="flex flex-col gap-0 text-xs"> | |
| 39 | + <span className="inline-block"> | |
| 40 | + {`${percent}% of context filled`} | |
| 41 | + </span> | |
| 42 | + {isPruned && ( | |
| 43 | + <span className="inline-block"> | |
| 44 | + {`Oldest messages are being removed`} | |
| 45 | + </span> | |
| 46 | + )} | |
| 47 | + {history.length > 0 && ( | |
| 48 | + <div className="flex flex-col gap-1 whitespace-pre"> | |
| 49 | + <div> | |
| 50 | + <span | |
| 51 | + className="inline-block cursor-pointer underline" | |
| 52 | + onClick={() => compactConversation(history.length - 1)} | |
| 53 | + > | |
| 54 | + Compact conversation | |
| 55 | + </span> | |
| 56 | + {"\n"} | |
| 57 | + <span className="inline-block">or</span> {"\n"} | |
| 58 | + <span | |
| 59 | + className="inline-block cursor-pointer underline" | |
| 60 | + onClick={() => { | |
| 61 | + dispatch( | |
| 62 | + saveCurrentSession({ | |
| 63 | + openNewSession: true, | |
| 64 | + generateTitle: false, | |
| 65 | + }), | |
| 66 | + ); | |
| 67 | + }} | |
| 68 | + > | |
| 69 | + Start a new session | |
| 70 | + </span> | |
| 71 | + </div> | |
| 72 | + </div> | |
| 73 | + )} | |
| 74 | + </div> | |
| 75 | + </ToolTip> | |
| 76 | + <div | |
| 77 | + data-tooltip-id="context-status" | |
| 78 | + className="border-description-muted relative h-[14px] w-[7px] rounded-[1px] border-[0.5px] border-solid md:h-[10px] md:w-[5px]" | |
| 79 | + > | |
| 80 | + <div | |
| 81 | + className={`transition-height absolute bottom-0 left-0 w-full duration-300 ease-in-out ${barColorClass}`} | |
| 82 | + style={{ height: `${percent}%` }} | |
| 83 | + ></div> | |
| 84 | + </div> | |
| 85 | + </div> | |
| 86 | + ); | |
| 87 | +}; | |
| 88 | + | |
| 89 | +export default ContextStatus; |
modified gui/src/components/mainInput/ContinueInputBox.tsx +0 −19
| @@ -10,9 +10,6 @@ | ||
| 10 | 10 | import { ToolbarOptions } from "./InputToolbar"; |
| 11 | 11 | import { Lump } from "./Lump"; |
| 12 | 12 | import { TipTapEditor } from "./TipTapEditor"; |
| 13 | -import WarningMessageBox from "./WarningMessageBox"; | |
| 14 | -import EditConfigAction from "./WarningMessageBox/Actions/EditConfigAction"; | |
| 15 | -import NewSessionAction from "./WarningMessageBox/Actions/NewSessionAction"; | |
| 16 | 13 | |
| 17 | 14 | interface ContinueInputBoxProps { |
| 18 | 15 | isLastUserInput: boolean; |
| @@ -43,9 +40,6 @@ | ||
| 43 | 40 | |
| 44 | 41 | function ContinueInputBox(props: ContinueInputBoxProps) { |
| 45 | 42 | const isStreaming = useAppSelector((state) => state.session.isStreaming); |
| 46 | - const warningMessage = useAppSelector( | |
| 47 | - (state) => state.session.warningMessage, | |
| 48 | - ); | |
| 49 | 43 | const availableSlashCommands = useAppSelector( |
| 50 | 44 | selectSlashCommandComboBoxInputs, |
| 51 | 45 | ); |
| @@ -125,19 +119,6 @@ | ||
| 125 | 119 | /> |
| 126 | 120 | </div> |
| 127 | 121 | )} |
| 128 | - {props.isLastUserInput && | |
| 129 | - warningMessage && | |
| 130 | - (warningMessage.category === "exceeded-context-length" ? ( | |
| 131 | - <WarningMessageBox | |
| 132 | - warningMessage={warningMessage} | |
| 133 | - actions={[NewSessionAction]} | |
| 134 | - /> | |
| 135 | - ) : ( | |
| 136 | - <WarningMessageBox | |
| 137 | - warningMessage={warningMessage} | |
| 138 | - actions={[EditConfigAction]} | |
| 139 | - /> | |
| 140 | - ))} | |
| 141 | 122 | </div> |
| 142 | 123 | ); |
| 143 | 124 | } |
added gui/src/components/mainInput/InlineErrorMessage.tsx +48 −0
| @@ -0,0 +1,48 @@ | ||
| 1 | +import { useContext } from "react"; | |
| 2 | +import { IdeMessengerContext } from "../../context/IdeMessenger"; | |
| 3 | +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; | |
| 4 | +import { setInlineErrorMessage } from "../../redux/slices/sessionSlice"; | |
| 5 | + | |
| 6 | +export type InlineErrorMessageType = "out-of-context"; | |
| 7 | + | |
| 8 | +export default function InlineErrorMessage() { | |
| 9 | + const dispatch = useAppDispatch(); | |
| 10 | + const ideMessenger = useContext(IdeMessengerContext); | |
| 11 | + const inlineErrorMessage = useAppSelector( | |
| 12 | + (state) => state.session.inlineErrorMessage, | |
| 13 | + ); | |
| 14 | + if (inlineErrorMessage === "out-of-context") { | |
| 15 | + return ( | |
| 16 | + <div | |
| 17 | + className={`border-border relative m-2 flex flex-col rounded-md border border-solid bg-transparent p-4`} | |
| 18 | + > | |
| 19 | + <p className={`thread-message text-error text-center`}> | |
| 20 | + {`Message exceeds context limit.`} | |
| 21 | + </p> | |
| 22 | + <div className="text-description flex flex-row items-center justify-center gap-1.5 px-3"> | |
| 23 | + <div | |
| 24 | + className="cursor-pointer text-xs hover:underline" | |
| 25 | + onClick={() => { | |
| 26 | + ideMessenger.post("config/openProfile", { | |
| 27 | + profileId: undefined, | |
| 28 | + }); | |
| 29 | + }} | |
| 30 | + > | |
| 31 | + <span className="xs:flex hidden">Open config</span> | |
| 32 | + <span className="xs:hidden">Config</span> | |
| 33 | + </div> | |
| 34 | + | | |
| 35 | + <span | |
| 36 | + className="cursor-pointer text-xs hover:underline" | |
| 37 | + onClick={() => { | |
| 38 | + dispatch(setInlineErrorMessage(undefined)); | |
| 39 | + }} | |
| 40 | + > | |
| 41 | + Hide | |
| 42 | + </span> | |
| 43 | + </div> | |
| 44 | + </div> | |
| 45 | + ); | |
| 46 | + } | |
| 47 | + return null; | |
| 48 | +} |
modified gui/src/components/mainInput/InputToolbar.tsx +2 −1
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | import { ModeSelect } from "../ModeSelect"; |
| 20 | 20 | import { Button } from "../ui"; |
| 21 | 21 | import { useFontSize } from "../ui/font"; |
| 22 | +import ContextStatus from "./ContextStatus"; | |
| 22 | 23 | import HoverItem from "./InputToolbar/HoverItem"; |
| 23 | 24 | |
| 24 | 25 | export interface ToolbarOptions { |
| @@ -170,6 +171,7 @@ | ||
| 170 | 171 | fontSize: tinyFont, |
| 171 | 172 | }} |
| 172 | 173 | > |
| 174 | + {!isInEdit && <ContextStatus />} | |
| 173 | 175 | {!props.toolbarOptions?.hideUseCodebase && !isInEdit && ( |
| 174 | 176 | <div |
| 175 | 177 | className={`${toolsSupported ? "md:flex" : "int:flex"} hover:underline" hidden transition-colors duration-200`} |
| @@ -209,7 +211,6 @@ | ||
| 209 | 211 | </span> |
| 210 | 212 | </HoverItem> |
| 211 | 213 | )} |
| 212 | - | |
| 213 | 214 | <Button |
| 214 | 215 | data-tooltip-id="enter-tooltip" |
| 215 | 216 | variant={props.isMainInput ? "primary" : "secondary"} |
modified gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx +1 −1
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | onClick={() => void dispatch(cancelStream())} |
| 15 | 15 | className="text-2xs cursor-pointer px-1.5 py-0.5 hover:brightness-125" |
| 16 | 16 | > |
| 17 | - <span className="text-description">Pause</span> | |
| 17 | + <span className="text-description">Stop</span> | |
| 18 | 18 | {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} |
| 19 | 19 | <span className="text-description-muted ml-1 opacity-75"> |
| 20 | 20 | {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()}⌫ |
modified gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts +3 −0
| @@ -15,6 +15,9 @@ | ||
| 15 | 15 | addOptions() { |
| 16 | 16 | return { |
| 17 | 17 | suggestion: { |
| 18 | + allow: ({ editor }) => | |
| 19 | + // the first character is "/". we want to avoid slash commands when there is a space after it | |
| 20 | + editor.getText().at(1) !== " ", | |
| 18 | 21 | char: "/", |
| 19 | 22 | pluginKey: new PluginKey(this.name), |
| 20 | 23 | startOfLine: true, |
deleted gui/src/components/mainInput/WarningMessageBox/Actions/EditConfigAction.tsx +0 −15
| @@ -1,15 +0,0 @@ | ||
| 1 | -import { useContext } from "react"; | |
| 2 | -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; | |
| 3 | -export default function EditConfigAction() { | |
| 4 | - const ideMessenger = useContext(IdeMessengerContext); | |
| 5 | - return ( | |
| 6 | - <span | |
| 7 | - onClick={() => | |
| 8 | - ideMessenger.post("config/openProfile", { profileId: undefined }) | |
| 9 | - } | |
| 10 | - className="hover:underline" | |
| 11 | - > | |
| 12 | - Open configuration file | |
| 13 | - </span> | |
| 14 | - ); | |
| 15 | -} |
deleted gui/src/components/mainInput/WarningMessageBox/Actions/NewSessionAction.tsx +0 −10
| @@ -1,10 +0,0 @@ | ||
| 1 | -import { useAppDispatch } from "../../../../redux/hooks"; | |
| 2 | -import { newSession } from "../../../../redux/slices/sessionSlice"; | |
| 3 | -export default function NewSessionAction() { | |
| 4 | - const dispatch = useAppDispatch(); | |
| 5 | - return ( | |
| 6 | - <span onClick={() => dispatch(newSession())} className="hover:underline"> | |
| 7 | - Start a new session | |
| 8 | - </span> | |
| 9 | - ); | |
| 10 | -} |
deleted gui/src/components/mainInput/WarningMessageBox/ExpendableBox.tsx +0 −41
| @@ -1,41 +0,0 @@ | ||
| 1 | -import { ReactNode, useEffect, useRef, useState } from "react"; | |
| 2 | -export default function ExpendableBox({ children }: { children: ReactNode }) { | |
| 3 | - const [isExpended, setIsExpended] = useState(false); | |
| 4 | - const [showTrigger, setShowTrigger] = useState(true); | |
| 5 | - const expendableDivRef = useRef<HTMLDivElement>(null); | |
| 6 | - const toggleExpendable = () => { | |
| 7 | - setIsExpended((pre) => !pre); | |
| 8 | - }; | |
| 9 | - | |
| 10 | - useEffect(() => { | |
| 11 | - if (expendableDivRef.current) { | |
| 12 | - expendableDivRef.current.style.maxHeight = isExpended ? "600px" : "0px"; | |
| 13 | - } | |
| 14 | - | |
| 15 | - if (isExpended) { | |
| 16 | - setShowTrigger(false); | |
| 17 | - } else { | |
| 18 | - setTimeout(() => setShowTrigger(true), 200); | |
| 19 | - } | |
| 20 | - }, [isExpended]); | |
| 21 | - | |
| 22 | - return ( | |
| 23 | - <div className="flex flex-col"> | |
| 24 | - <div | |
| 25 | - onClick={toggleExpendable} | |
| 26 | - className={`h-[9px] w-[9px] self-end ${showTrigger ? "" : "hidden"} bg-warning my-2 mr-4 rounded-lg`} | |
| 27 | - ></div> | |
| 28 | - | |
| 29 | - <div | |
| 30 | - onClick={toggleExpendable} | |
| 31 | - ref={expendableDivRef} | |
| 32 | - style={{ | |
| 33 | - transition: "max-height 0.3s ease-in-out", | |
| 34 | - overflowY: "hidden", | |
| 35 | - }} | |
| 36 | - > | |
| 37 | - {children} | |
| 38 | - </div> | |
| 39 | - </div> | |
| 40 | - ); | |
| 41 | -} |
deleted gui/src/components/mainInput/WarningMessageBox/index.tsx +0 −55
| @@ -1,55 +0,0 @@ | ||
| 1 | -import { WarningMessage } from "core"; | |
| 2 | -import { ReactElement } from "react"; | |
| 3 | -import ExpendableBox from "./ExpendableBox"; | |
| 4 | - | |
| 5 | -function MessageBox({ | |
| 6 | - warningMessage, | |
| 7 | - actions, | |
| 8 | -}: { | |
| 9 | - warningMessage: WarningMessage; | |
| 10 | - actions?: (() => ReactElement)[]; | |
| 11 | -}) { | |
| 12 | - const warningMessageTextColor = | |
| 13 | - warningMessage.level === "fatal" ? "text-error" : "text-warning"; | |
| 14 | - const warningMessageBorderColor = | |
| 15 | - warningMessage.level === "fatal" ? "border-error" : "border-warning"; | |
| 16 | - return ( | |
| 17 | - <div | |
| 18 | - className={`relative m-2 flex flex-col rounded-md border border-solid ${warningMessageBorderColor} bg-transparent p-4`} | |
| 19 | - > | |
| 20 | - <p className={`thread-message ${warningMessageTextColor}`}> | |
| 21 | - <b>Warning: </b> | |
| 22 | - {`${warningMessage.message}`} | |
| 23 | - </p> | |
| 24 | - {actions && ( | |
| 25 | - <div> | |
| 26 | - <p>{`Recommended Action${actions.length > 1 ? "s" : ""}:`}</p> | |
| 27 | - <ul> | |
| 28 | - {actions.map((action, ind) => { | |
| 29 | - return <li key={`warning-action-${ind}`}>{action()}</li>; | |
| 30 | - })} | |
| 31 | - </ul> | |
| 32 | - </div> | |
| 33 | - )} | |
| 34 | - </div> | |
| 35 | - ); | |
| 36 | -} | |
| 37 | - | |
| 38 | -export default function WarningMessageBox({ | |
| 39 | - warningMessage, | |
| 40 | - actions, | |
| 41 | -}: { | |
| 42 | - warningMessage: WarningMessage; | |
| 43 | - actions?: (() => ReactElement)[]; | |
| 44 | -}) { | |
| 45 | - if (warningMessage.category === "exceeded-context-length") { | |
| 46 | - return ( | |
| 47 | - <ExpendableBox | |
| 48 | - children={ | |
| 49 | - <MessageBox warningMessage={warningMessage} actions={actions} /> | |
| 50 | - } | |
| 51 | - /> | |
| 52 | - ); | |
| 53 | - } | |
| 54 | - return <MessageBox warningMessage={warningMessage} actions={actions} />; | |
| 55 | -} |
modified gui/src/components/modelSelection/ModelSelect.tsx +1 −1
| @@ -218,7 +218,7 @@ | ||
| 218 | 218 | {modelSelectTitle(selectedModel) || "Select model"} |
| 219 | 219 | </span> |
| 220 | 220 | <ChevronDownIcon |
| 221 | - className="h-2 w-2 flex-shrink-0 hover:brightness-110" | |
| 221 | + className="hidden h-2 w-2 flex-shrink-0 hover:brightness-110 min-[200px]:flex" | |
| 222 | 222 | aria-hidden="true" |
| 223 | 223 | /> |
| 224 | 224 | </ListboxButton> |
modified gui/src/console.tsx +1 −1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | import Layout from "./components/console/Layout"; |
| 4 | 4 | import "./indexConsole.css"; |
| 5 | 5 | |
| 6 | -(async () => { | |
| 6 | +void (async () => { | |
| 7 | 7 | ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( |
| 8 | 8 | <React.StrictMode> |
| 9 | 9 | <Layout></Layout> |
modified gui/src/context/MockIdeMessenger.ts +2 −1
| @@ -86,7 +86,8 @@ | ||
| 86 | 86 | }, |
| 87 | 87 | "llm/compileChat": { |
| 88 | 88 | compiledChatMessages: [], |
| 89 | - pruningStatus: "not-pruned", | |
| 89 | + didPrune: false, | |
| 90 | + contextPercentage: 0.5, | |
| 90 | 91 | }, |
| 91 | 92 | }; |
| 92 | 93 |
modified gui/src/hooks/useLLMSummary.ts +18 −0
| @@ -1,3 +1,7 @@ | ||
| 1 | +import { | |
| 2 | + calculateRequestCost, | |
| 3 | + CostBreakdown, | |
| 4 | +} from "core/llm/utils/calculateRequestCost"; | |
| 1 | 5 | import { useMemo } from "react"; |
| 2 | 6 | import { LLMInteraction } from "./useLLMLog"; |
| 3 | 7 | |
| @@ -62,6 +66,19 @@ | ||
| 62 | 66 | : undefined; |
| 63 | 67 | } |
| 64 | 68 | |
| 69 | + let costBreakdown: CostBreakdown | null = null; | |
| 70 | + if ( | |
| 71 | + interaction.end?.usage && | |
| 72 | + interaction.start?.provider && | |
| 73 | + interaction.start?.options?.model | |
| 74 | + ) { | |
| 75 | + costBreakdown = calculateRequestCost( | |
| 76 | + interaction.start.provider, | |
| 77 | + interaction.start.options.model, | |
| 78 | + interaction.end.usage, | |
| 79 | + ); | |
| 80 | + } | |
| 81 | + | |
| 65 | 82 | return { |
| 66 | 83 | result, |
| 67 | 84 | type, |
| @@ -71,6 +88,7 @@ | ||
| 71 | 88 | promptTokens, |
| 72 | 89 | generatedTokens, |
| 73 | 90 | thinkingTokens, |
| 91 | + costBreakdown, | |
| 74 | 92 | }; |
| 75 | 93 | }, [interaction]); |
| 76 | 94 | } |
added gui/src/hooks/useTotalUsage.ts +102 −0
| @@ -0,0 +1,102 @@ | ||
| 1 | +import { | |
| 2 | + calculateRequestCost, | |
| 3 | + CostBreakdown, | |
| 4 | +} from "core/llm/utils/calculateRequestCost"; | |
| 5 | +import { useMemo } from "react"; | |
| 6 | +import { LLMLog } from "./useLLMLog"; | |
| 7 | + | |
| 8 | +export interface TotalUsage { | |
| 9 | + totalPromptTokens: number; | |
| 10 | + totalGeneratedTokens: number; | |
| 11 | + totalThinkingTokens: number; | |
| 12 | + totalCachedTokens: number; | |
| 13 | + totalCacheWriteTokens: number; | |
| 14 | + totalInteractions: number; | |
| 15 | + totalSuccessfulInteractions: number; | |
| 16 | + totalErrorInteractions: number; | |
| 17 | + totalCancelledInteractions: number; | |
| 18 | + totalCost: number; | |
| 19 | + costBreakdowns: CostBreakdown[]; | |
| 20 | +} | |
| 21 | + | |
| 22 | +/** | |
| 23 | + * Hook to calculate total usage across all interactions in the LLM log | |
| 24 | + */ | |
| 25 | +export default function useTotalUsage(llmLog: LLMLog): TotalUsage { | |
| 26 | + return useMemo(() => { | |
| 27 | + let totalPromptTokens = 0; | |
| 28 | + let totalGeneratedTokens = 0; | |
| 29 | + let totalThinkingTokens = 0; | |
| 30 | + let totalCachedTokens = 0; | |
| 31 | + let totalCacheWriteTokens = 0; | |
| 32 | + let totalInteractions = 0; | |
| 33 | + let totalSuccessfulInteractions = 0; | |
| 34 | + let totalErrorInteractions = 0; | |
| 35 | + let totalCancelledInteractions = 0; | |
| 36 | + let totalCost = 0; | |
| 37 | + const costBreakdowns: CostBreakdown[] = []; | |
| 38 | + | |
| 39 | + // Iterate through all interactions | |
| 40 | + for (const interaction of llmLog.interactions.values()) { | |
| 41 | + if (interaction.end) { | |
| 42 | + totalInteractions++; | |
| 43 | + | |
| 44 | + // Add basic token counts | |
| 45 | + totalPromptTokens += interaction.end.promptTokens || 0; | |
| 46 | + totalGeneratedTokens += interaction.end.generatedTokens || 0; | |
| 47 | + totalThinkingTokens += interaction.end.thinkingTokens || 0; | |
| 48 | + | |
| 49 | + // Add cache-related tokens from usage if available | |
| 50 | + if (interaction.end.usage) { | |
| 51 | + const usage = interaction.end.usage; | |
| 52 | + totalCachedTokens += usage.promptTokensDetails?.cachedTokens || 0; | |
| 53 | + totalCacheWriteTokens += | |
| 54 | + usage.promptTokensDetails?.cacheWriteTokens || 0; | |
| 55 | + | |
| 56 | + // Calculate cost if we have the necessary information | |
| 57 | + if ( | |
| 58 | + interaction.start?.provider && | |
| 59 | + interaction.start?.options?.model | |
| 60 | + ) { | |
| 61 | + const costBreakdown = calculateRequestCost( | |
| 62 | + interaction.start.provider, | |
| 63 | + interaction.start.options.model, | |
| 64 | + usage, | |
| 65 | + ); | |
| 66 | + if (costBreakdown) { | |
| 67 | + totalCost += costBreakdown.cost; | |
| 68 | + costBreakdowns.push(costBreakdown); | |
| 69 | + } | |
| 70 | + } | |
| 71 | + } | |
| 72 | + | |
| 73 | + // Count interaction outcomes | |
| 74 | + switch (interaction.end.kind) { | |
| 75 | + case "success": | |
| 76 | + totalSuccessfulInteractions++; | |
| 77 | + break; | |
| 78 | + case "error": | |
| 79 | + totalErrorInteractions++; | |
| 80 | + break; | |
| 81 | + case "cancel": | |
| 82 | + totalCancelledInteractions++; | |
| 83 | + break; | |
| 84 | + } | |
| 85 | + } | |
| 86 | + } | |
| 87 | + | |
| 88 | + return { | |
| 89 | + totalPromptTokens, | |
| 90 | + totalGeneratedTokens, | |
| 91 | + totalThinkingTokens, | |
| 92 | + totalCachedTokens, | |
| 93 | + totalCacheWriteTokens, | |
| 94 | + totalInteractions, | |
| 95 | + totalSuccessfulInteractions, | |
| 96 | + totalErrorInteractions, | |
| 97 | + totalCancelledInteractions, | |
| 98 | + totalCost, | |
| 99 | + costBreakdowns, | |
| 100 | + }; | |
| 101 | + }, [llmLog]); | |
| 102 | +} |
modified gui/src/pages/config/HelpCenterSection.tsx +26 −1
| @@ -1,13 +1,14 @@ | ||
| 1 | 1 | import { |
| 2 | 2 | ArrowTopRightOnSquareIcon, |
| 3 | 3 | DocumentArrowUpIcon, |
| 4 | + NumberedListIcon, | |
| 4 | 5 | PaintBrushIcon, |
| 5 | 6 | TableCellsIcon, |
| 6 | 7 | } from "@heroicons/react/24/outline"; |
| 7 | 8 | import { useContext } from "react"; |
| 8 | 9 | import { useNavigate } from "react-router-dom"; |
| 9 | 10 | import { IdeMessengerContext } from "../../context/IdeMessenger"; |
| 10 | -import { useAppDispatch } from "../../redux/hooks"; | |
| 11 | +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; | |
| 11 | 12 | import { setOnboardingCard } from "../../redux/slices/uiSlice"; |
| 12 | 13 | import { saveCurrentSession } from "../../redux/thunks/session"; |
| 13 | 14 | import { ROUTES } from "../../util/navigation"; |
| @@ -18,6 +19,21 @@ | ||
| 18 | 19 | const navigate = useNavigate(); |
| 19 | 20 | const dispatch = useAppDispatch(); |
| 20 | 21 | |
| 22 | + const currentSession = useAppSelector((state) => state.session); | |
| 23 | + | |
| 24 | + const handleViewSessionData = async () => { | |
| 25 | + const sessionData = await ideMessenger.request("history/load", { | |
| 26 | + id: currentSession.id, | |
| 27 | + }); | |
| 28 | + | |
| 29 | + if (sessionData.status === "success") { | |
| 30 | + await ideMessenger.request("showVirtualFile", { | |
| 31 | + name: `${sessionData.content.title}.json`, | |
| 32 | + content: JSON.stringify(sessionData.content, null, 2), | |
| 33 | + }); | |
| 34 | + } | |
| 35 | + }; | |
| 36 | + | |
| 21 | 37 | return ( |
| 22 | 38 | <div className="py-5"> |
| 23 | 39 | <h3 className="mb-4 mt-0 text-xl">Help center</h3> |
| @@ -68,6 +84,15 @@ | ||
| 68 | 84 | onClick={() => navigate("/stats")} |
| 69 | 85 | /> |
| 70 | 86 | |
| 87 | + {currentSession.history.length > 0 && !currentSession.isStreaming && ( | |
| 88 | + <MoreHelpRow | |
| 89 | + title="View current session history" | |
| 90 | + description="Open the current chat session file for troubleshooting" | |
| 91 | + Icon={NumberedListIcon} | |
| 92 | + onClick={handleViewSessionData} | |
| 93 | + /> | |
| 94 | + )} | |
| 95 | + | |
| 71 | 96 | <MoreHelpRow |
| 72 | 97 | title="Quickstart" |
| 73 | 98 | description="Reopen the quickstart and tutorial file" |
modified gui/src/pages/gui/Chat.tsx +56 −39
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | ChatBubbleOvalLeftIcon, |
| 4 | 4 | } from "@heroicons/react/24/outline"; |
| 5 | 5 | import { Editor, JSONContent } from "@tiptap/react"; |
| 6 | -import { InputModifiers } from "core"; | |
| 6 | +import { ChatHistoryItem, InputModifiers } from "core"; | |
| 7 | 7 | import { renderChatMessage } from "core/util/messageContent"; |
| 8 | 8 | import { |
| 9 | 9 | useCallback, |
| @@ -43,11 +43,22 @@ | ||
| 43 | 43 | import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; |
| 44 | 44 | import { ToolCallDiv } from "./ToolCallDiv"; |
| 45 | 45 | |
| 46 | +import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage"; | |
| 46 | 47 | import { cancelStream } from "../../redux/thunks/cancelStream"; |
| 47 | 48 | import { EmptyChatBody } from "./EmptyChatBody"; |
| 48 | 49 | import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; |
| 49 | 50 | import { useAutoScroll } from "./useAutoScroll"; |
| 50 | 51 | |
| 52 | +// Helper function to find the index of the latest conversation summary | |
| 53 | +function findLatestSummaryIndex(history: ChatHistoryItem[]): number { | |
| 54 | + for (let i = history.length - 1; i >= 0; i--) { | |
| 55 | + if (history[i].conversationSummary) { | |
| 56 | + return i; | |
| 57 | + } | |
| 58 | + } | |
| 59 | + return -1; // No summary found | |
| 60 | +} | |
| 61 | + | |
| 51 | 62 | const StepsDiv = styled.div` |
| 52 | 63 | position: relative; |
| 53 | 64 | background-color: transparent; |
| @@ -113,9 +124,6 @@ | ||
| 113 | 124 | const jetbrains = useMemo(() => { |
| 114 | 125 | return isJetBrains(); |
| 115 | 126 | }, []); |
| 116 | - const warningMessage = useAppSelector( | |
| 117 | - (state) => state.session.warningMessage, | |
| 118 | - ); | |
| 119 | 127 | |
| 120 | 128 | useAutoScroll(stepsDivRef, history); |
| 121 | 129 | |
| @@ -128,7 +136,6 @@ | ||
| 128 | 136 | !e.shiftKey |
| 129 | 137 | ) { |
| 130 | 138 | void dispatch(cancelStream()); |
| 131 | - if (isInEdit) ideMessenger.post("rejectDiff", {}); | |
| 132 | 139 | } |
| 133 | 140 | }; |
| 134 | 141 | window.addEventListener("keydown", listener); |
| @@ -273,19 +280,26 @@ | ||
| 273 | 280 | toolCallStates, |
| 274 | 281 | } = item; |
| 275 | 282 | |
| 283 | + // Calculate once for the entire function | |
| 284 | + const latestSummaryIndex = findLatestSummaryIndex(history); | |
| 285 | + const isBeforeLatestSummary = | |
| 286 | + latestSummaryIndex !== -1 && index < latestSummaryIndex; | |
| 287 | + | |
| 276 | 288 | if (message.role === "user") { |
| 277 | 289 | return ( |
| 278 | - <ContinueInputBox | |
| 279 | - onEnter={(editorState, modifiers) => | |
| 280 | - sendInput(editorState, modifiers, index) | |
| 281 | - } | |
| 282 | - isLastUserInput={isLastUserInput(index)} | |
| 283 | - isMainInput={false} | |
| 284 | - editorState={editorState} | |
| 285 | - contextItems={contextItems} | |
| 286 | - appliedRules={appliedRules} | |
| 287 | - inputId={message.id} | |
| 288 | - /> | |
| 290 | + <div className={isBeforeLatestSummary ? "opacity-50" : ""}> | |
| 291 | + <ContinueInputBox | |
| 292 | + onEnter={(editorState, modifiers) => | |
| 293 | + sendInput(editorState, modifiers, index) | |
| 294 | + } | |
| 295 | + isLastUserInput={isLastUserInput(index)} | |
| 296 | + isMainInput={false} | |
| 297 | + editorState={editorState} | |
| 298 | + contextItems={contextItems} | |
| 299 | + appliedRules={appliedRules} | |
| 300 | + inputId={message.id} | |
| 301 | + /> | |
| 302 | + </div> | |
| 289 | 303 | ); |
| 290 | 304 | } |
| 291 | 305 | |
| @@ -314,6 +328,7 @@ | ||
| 314 | 328 | index={index} |
| 315 | 329 | isLast={index === history.length - 1} |
| 316 | 330 | item={item} |
| 331 | + latestSummaryIndex={latestSummaryIndex} | |
| 317 | 332 | /> |
| 318 | 333 | </TimelineItem> |
| 319 | 334 | </div> |
| @@ -330,14 +345,16 @@ | ||
| 330 | 345 | |
| 331 | 346 | if (message.role === "thinking") { |
| 332 | 347 | return ( |
| 333 | - <ThinkingBlockPeek | |
| 334 | - content={renderChatMessage(message)} | |
| 335 | - redactedThinking={message.redactedThinking} | |
| 336 | - index={index} | |
| 337 | - prevItem={index > 0 ? history[index - 1] : null} | |
| 338 | - inProgress={index === history.length - 1} | |
| 339 | - signature={message.signature} | |
| 340 | - /> | |
| 348 | + <div className={isBeforeLatestSummary ? "opacity-50" : ""}> | |
| 349 | + <ThinkingBlockPeek | |
| 350 | + content={renderChatMessage(message)} | |
| 351 | + redactedThinking={message.redactedThinking} | |
| 352 | + index={index} | |
| 353 | + prevItem={index > 0 ? history[index - 1] : null} | |
| 354 | + inProgress={index === history.length - 1} | |
| 355 | + signature={message.signature} | |
| 356 | + /> | |
| 357 | + </div> | |
| 341 | 358 | ); |
| 342 | 359 | } |
| 343 | 360 | |
| @@ -356,6 +373,7 @@ | ||
| 356 | 373 | index={index} |
| 357 | 374 | isLast={index === history.length - 1} |
| 358 | 375 | item={item} |
| 376 | + latestSummaryIndex={latestSummaryIndex} | |
| 359 | 377 | /> |
| 360 | 378 | </TimelineItem> |
| 361 | 379 | </div> |
| @@ -391,6 +409,7 @@ | ||
| 391 | 409 | > |
| 392 | 410 | {renderChatHistoryItem(item, index)} |
| 393 | 411 | </ErrorBoundary> |
| 412 | + {index === history.length - 1 && <InlineErrorMessage />} | |
| 394 | 413 | </div> |
| 395 | 414 | ))} |
| 396 | 415 | </StepsDiv> |
| @@ -412,21 +431,19 @@ | ||
| 412 | 431 | <div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2"> |
| 413 | 432 | <div className="xs:inline hidden"> |
| 414 | 433 | {history.length === 0 && lastSessionId && !isInEdit && ( |
| 415 | - <div className="xs:inline hidden"> | |
| 416 | - <NewSessionButton | |
| 417 | - onClick={async () => { | |
| 418 | - await dispatch( | |
| 419 | - loadLastSession({ | |
| 420 | - saveCurrentSession: true, | |
| 421 | - }), | |
| 422 | - ); | |
| 423 | - }} | |
| 424 | - className="flex items-center gap-2" | |
| 425 | - > | |
| 426 | - <ArrowLeftIcon className="h-3 w-3" /> | |
| 427 | - <span className="text-xs">Last Session</span> | |
| 428 | - </NewSessionButton> | |
| 429 | - </div> | |
| 434 | + <NewSessionButton | |
| 435 | + onClick={async () => { | |
| 436 | + await dispatch( | |
| 437 | + loadLastSession({ | |
| 438 | + saveCurrentSession: true, | |
| 439 | + }), | |
| 440 | + ); | |
| 441 | + }} | |
| 442 | + className="flex items-center gap-2" | |
| 443 | + > | |
| 444 | + <ArrowLeftIcon className="h-3 w-3" /> | |
| 445 | + <span className="text-xs">Last Session</span> | |
| 446 | + </NewSessionButton> | |
| 430 | 447 | )} |
| 431 | 448 | </div> |
| 432 | 449 | </div> |
modified gui/src/redux/slices/sessionSlice.test.ts +1 −0
| @@ -75,6 +75,7 @@ | ||
| 75 | 75 | }, |
| 76 | 76 | newestToolbarPreviewForInput: {}, |
| 77 | 77 | isSessionMetadataLoading: false, |
| 78 | + compactionLoading: {}, | |
| 78 | 79 | }); |
| 79 | 80 | |
| 80 | 81 | describe("Basic Chat Message", () => { |
modified gui/src/redux/slices/sessionSlice.ts +60 −8
| @@ -23,7 +23,6 @@ | ||
| 23 | 23 | Tool, |
| 24 | 24 | ToolCallDelta, |
| 25 | 25 | ToolCallState, |
| 26 | - WarningMessage, | |
| 27 | 26 | } from "core"; |
| 28 | 27 | import { BuiltInToolNames } from "core/tools/builtIn"; |
| 29 | 28 | import { NEW_SESSION_TITLE } from "core/util/constants"; |
| @@ -34,6 +33,7 @@ | ||
| 34 | 33 | import { findUriInDirs, getUriPathBasename } from "core/util/uri"; |
| 35 | 34 | import { findLastIndex } from "lodash"; |
| 36 | 35 | import { v4 as uuidv4 } from "uuid"; |
| 36 | +import { type InlineErrorMessageType } from "../../components/mainInput/InlineErrorMessage"; | |
| 37 | 37 | import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/utils"; |
| 38 | 38 | import { addToolCallDeltaToState } from "../../util/toolCallState"; |
| 39 | 39 | import { RootState } from "../store"; |
| @@ -224,7 +224,10 @@ | ||
| 224 | 224 | }; |
| 225 | 225 | newestToolbarPreviewForInput: Record<string, string>; |
| 226 | 226 | hasReasoningEnabled?: boolean; |
| 227 | - warningMessage?: WarningMessage; | |
| 227 | + isPruned?: boolean; | |
| 228 | + contextPercentage?: number; | |
| 229 | + inlineErrorMessage?: InlineErrorMessageType; | |
| 230 | + compactionLoading: Record<number, boolean>; // Track compaction loading by message index | |
| 228 | 231 | }; |
| 229 | 232 | |
| 230 | 233 | const initialState: SessionState = { |
| @@ -244,6 +247,7 @@ | ||
| 244 | 247 | }, |
| 245 | 248 | lastSessionId: undefined, |
| 246 | 249 | newestToolbarPreviewForInput: {}, |
| 250 | + compactionLoading: {}, | |
| 247 | 251 | }; |
| 248 | 252 | |
| 249 | 253 | export const sessionSlice = createSlice({ |
| @@ -287,6 +291,7 @@ | ||
| 287 | 291 | if (state.history.length < 2) { |
| 288 | 292 | return; |
| 289 | 293 | } |
| 294 | + | |
| 290 | 295 | const lastUserOrToolIdx = findLastIndex( |
| 291 | 296 | state.history, |
| 292 | 297 | (item) => item.message.role === "tool" || item.message.role === "user", |
| @@ -313,7 +318,14 @@ | ||
| 313 | 318 | } |
| 314 | 319 | |
| 315 | 320 | if (validAssistantMessageIdx === -1) { |
| 316 | - state.history = state.history.slice(0, lastUserOrToolIdx + 1); | |
| 321 | + const lastMsg = state.history[lastUserOrToolIdx]; | |
| 322 | + const lastRole = lastMsg.message.role as "user" | "tool"; | |
| 323 | + if (lastRole === "user") { | |
| 324 | + state.mainEditorContentTrigger = lastMsg.editorState; | |
| 325 | + state.history = state.history.slice(0, lastUserOrToolIdx); | |
| 326 | + } else { | |
| 327 | + state.history = state.history.slice(0, lastUserOrToolIdx + 1); | |
| 328 | + } | |
| 317 | 329 | } else { |
| 318 | 330 | state.history = state.history.slice(0, validAssistantMessageIdx + 1); |
| 319 | 331 | } |
| @@ -421,12 +433,27 @@ | ||
| 421 | 433 | }, |
| 422 | 434 | contextItems: [], |
| 423 | 435 | }); |
| 436 | + state.inlineErrorMessage = undefined; | |
| 437 | + state.isPruned = false; | |
| 438 | + state.contextPercentage = undefined; | |
| 424 | 439 | } |
| 425 | 440 | }, |
| 426 | 441 | deleteMessage: (state, action: PayloadAction<number>) => { |
| 427 | 442 | // Deletes the current assistant message and the previous user message |
| 428 | 443 | state.history.splice(action.payload - 1, 2); |
| 429 | - state.warningMessage = undefined; | |
| 444 | + state.inlineErrorMessage = undefined; | |
| 445 | + state.isPruned = false; | |
| 446 | + state.contextPercentage = undefined; | |
| 447 | + }, | |
| 448 | + deleteCompaction: (state, action: PayloadAction<number>) => { | |
| 449 | + // Removes the conversation summary from the specified message | |
| 450 | + const historyItem = state.history[action.payload]; | |
| 451 | + if (historyItem?.conversationSummary) { | |
| 452 | + state.history[action.payload] = { | |
| 453 | + ...historyItem, | |
| 454 | + conversationSummary: undefined, | |
| 455 | + }; | |
| 456 | + } | |
| 430 | 457 | }, |
| 431 | 458 | updateHistoryItemAtIndex: ( |
| 432 | 459 | state, |
| @@ -637,6 +664,10 @@ | ||
| 637 | 664 | state.isStreaming = false; |
| 638 | 665 | state.symbols = {}; |
| 639 | 666 | |
| 667 | + state.inlineErrorMessage = undefined; | |
| 668 | + state.isPruned = false; | |
| 669 | + state.contextPercentage = undefined; | |
| 670 | + | |
| 640 | 671 | if (payload) { |
| 641 | 672 | state.history = payload.history as any; |
| 642 | 673 | state.title = payload.title; |
| @@ -892,11 +923,28 @@ | ||
| 892 | 923 | state.newestToolbarPreviewForInput[payload.inputId] = |
| 893 | 924 | payload.contextItemId; |
| 894 | 925 | }, |
| 895 | - setWarningMessage: ( | |
| 926 | + setCompactionLoading: ( | |
| 927 | + state, | |
| 928 | + action: PayloadAction<{ index: number; loading: boolean }>, | |
| 929 | + ) => { | |
| 930 | + const { index, loading } = action.payload; | |
| 931 | + if (loading) { | |
| 932 | + state.compactionLoading[index] = true; | |
| 933 | + } else { | |
| 934 | + delete state.compactionLoading[index]; | |
| 935 | + } | |
| 936 | + }, | |
| 937 | + setInlineErrorMessage: ( | |
| 896 | 938 | state, |
| 897 | - action: PayloadAction<WarningMessage | undefined>, | |
| 939 | + action: PayloadAction<SessionState["inlineErrorMessage"]>, | |
| 898 | 940 | ) => { |
| 899 | - state.warningMessage = action.payload; | |
| 941 | + state.inlineErrorMessage = action.payload; | |
| 942 | + }, | |
| 943 | + setIsPruned: (state, action: PayloadAction<boolean>) => { | |
| 944 | + state.isPruned = action.payload; | |
| 945 | + }, | |
| 946 | + setContextPercentage: (state, action: PayloadAction<number>) => { | |
| 947 | + state.contextPercentage = action.payload; | |
| 900 | 948 | }, |
| 901 | 949 | }, |
| 902 | 950 | selectors: { |
| @@ -962,6 +1010,7 @@ | ||
| 962 | 1010 | clearDanglingMessages, |
| 963 | 1011 | setMainEditorContentTrigger, |
| 964 | 1012 | deleteMessage, |
| 1013 | + deleteCompaction, | |
| 965 | 1014 | setIsGatheringContext, |
| 966 | 1015 | resetNextCodeBlockToApplyIndex, |
| 967 | 1016 | updateApplyState, |
| @@ -981,7 +1030,10 @@ | ||
| 981 | 1030 | setNewestToolbarPreviewForInput, |
| 982 | 1031 | setIsInEdit, |
| 983 | 1032 | setHasReasoningEnabled, |
| 984 | - setWarningMessage, | |
| 1033 | + setInlineErrorMessage, | |
| 1034 | + setIsPruned, | |
| 1035 | + setContextPercentage, | |
| 1036 | + setCompactionLoading, | |
| 985 | 1037 | } = sessionSlice.actions; |
| 986 | 1038 | |
| 987 | 1039 | export const { selectIsGatheringContext } = sessionSlice.selectors; |
modified gui/src/redux/thunks/streamNormalInput.ts +16 −27
| @@ -11,9 +11,11 @@ | ||
| 11 | 11 | addPromptCompletionPair, |
| 12 | 12 | setActive, |
| 13 | 13 | setAppliedRulesAtIndex, |
| 14 | + setContextPercentage, | |
| 14 | 15 | setInactive, |
| 16 | + setInlineErrorMessage, | |
| 17 | + setIsPruned, | |
| 15 | 18 | setToolGenerated, |
| 16 | - setWarningMessage, | |
| 17 | 19 | streamUpdate, |
| 18 | 20 | } from "../slices/sessionSlice"; |
| 19 | 21 | import { AppThunkDispatch, RootState, ThunkApiType } from "../store"; |
| @@ -184,42 +186,29 @@ | ||
| 184 | 186 | ); |
| 185 | 187 | |
| 186 | 188 | dispatch(setActive()); |
| 187 | - // Remove the warning message before each compileChat call | |
| 188 | - dispatch(setWarningMessage(undefined)); | |
| 189 | + dispatch(setInlineErrorMessage(undefined)); | |
| 190 | + | |
| 189 | 191 | const precompiledRes = await extra.ideMessenger.request("llm/compileChat", { |
| 190 | 192 | messages, |
| 191 | 193 | options: completionOptions, |
| 192 | 194 | }); |
| 193 | 195 | |
| 194 | 196 | if (precompiledRes.status === "error") { |
| 195 | - throw new Error(precompiledRes.error); | |
| 196 | - } | |
| 197 | - | |
| 198 | - const { compiledChatMessages, pruningStatus } = precompiledRes.content; | |
| 199 | - | |
| 200 | - switch (pruningStatus) { | |
| 201 | - case "pruned": | |
| 202 | - dispatch( | |
| 203 | - setWarningMessage({ | |
| 204 | - message: `Chat history exceeds model's context length (${state.config.config.selectedModelByRole.chat?.contextLength} tokens). Old messages will not be included.`, | |
| 205 | - level: "warning", | |
| 206 | - category: "exceeded-context-length", | |
| 207 | - }), | |
| 208 | - ); | |
| 209 | - break; | |
| 210 | - case "deleted-last-input": | |
| 211 | - dispatch( | |
| 212 | - setWarningMessage({ | |
| 213 | - message: | |
| 214 | - "The provided context items are too large. Please trim the context item to fit the model's context length or increase the model's context length by editing the configuration.", | |
| 215 | - level: "fatal", | |
| 216 | - category: "deleted-last-input", | |
| 217 | - }), | |
| 218 | - ); | |
| 197 | + if (precompiledRes.error.includes("Not enough context")) { | |
| 198 | + dispatch(setInlineErrorMessage("out-of-context")); | |
| 219 | 199 | dispatch(setInactive()); |
| 220 | 200 | return; |
| 201 | + } else { | |
| 202 | + throw new Error(precompiledRes.error); | |
| 203 | + } | |
| 221 | 204 | } |
| 222 | 205 | |
| 206 | + const { compiledChatMessages, didPrune, contextPercentage } = | |
| 207 | + precompiledRes.content; | |
| 208 | + | |
| 209 | + dispatch(setIsPruned(didPrune)); | |
| 210 | + dispatch(setContextPercentage(contextPercentage)); | |
| 211 | + | |
| 223 | 212 | // Send request and stream response |
| 224 | 213 | const streamAborter = state.session.streamAborter; |
| 225 | 214 | const gen = extra.ideMessenger.llmStreamChat( |
modified gui/src/redux/util/constructMessages.ts +25 −3
| @@ -40,7 +40,21 @@ | ||
| 40 | 40 | appliedRules: RuleWithSource[]; |
| 41 | 41 | appliedRuleIndex: number; |
| 42 | 42 | } { |
| 43 | - const historyCopy = [...history]; | |
| 43 | + // Find the most recent conversation summary and filter history accordingly | |
| 44 | + let summaryContent = ""; | |
| 45 | + let filteredHistory = history; | |
| 46 | + | |
| 47 | + for (let i = history.length - 1; i >= 0; i--) { | |
| 48 | + const summary = history[i].conversationSummary; | |
| 49 | + if (summary) { | |
| 50 | + summaryContent = summary; | |
| 51 | + // Only include messages that come AFTER the message with the summary | |
| 52 | + filteredHistory = history.slice(i + 1); | |
| 53 | + break; | |
| 54 | + } | |
| 55 | + } | |
| 56 | + | |
| 57 | + const historyCopy = [...filteredHistory]; | |
| 44 | 58 | |
| 45 | 59 | const msgs: MessageWithContextItems[] = []; |
| 46 | 60 | let appliedRuleIndex = -1; |
| @@ -160,12 +174,20 @@ | ||
| 160 | 174 | rulePolicies, |
| 161 | 175 | }); |
| 162 | 176 | |
| 163 | - if (systemMessage.trim()) { | |
| 177 | + // Append conversation summary to system message if it exists | |
| 178 | + let finalSystemMessage = systemMessage; | |
| 179 | + if (summaryContent) { | |
| 180 | + finalSystemMessage = systemMessage | |
| 181 | + ? `${systemMessage}\n\nPrevious conversation summary:\n\n ${summaryContent}` | |
| 182 | + : `Previous conversation summary:\n\n ${summaryContent}`; | |
| 183 | + } | |
| 184 | + | |
| 185 | + if (finalSystemMessage.trim()) { | |
| 164 | 186 | msgs.unshift({ |
| 165 | 187 | ctxItems: [], |
| 166 | 188 | message: { |
| 167 | 189 | role: "system", |
| 168 | - content: systemMessage, | |
| 190 | + content: finalSystemMessage, | |
| 169 | 191 | }, |
| 170 | 192 | }); |
| 171 | 193 | } |
added gui/src/util/compactConversation.ts +58 −0
| @@ -0,0 +1,58 @@ | ||
| 1 | +import { useContext } from "react"; | |
| 2 | +import { IdeMessengerContext } from "../context/IdeMessenger"; | |
| 3 | +import { useAppDispatch, useAppSelector } from "../redux/hooks"; | |
| 4 | +import { | |
| 5 | + setCompactionLoading, | |
| 6 | + deleteCompaction, | |
| 7 | +} from "../redux/slices/sessionSlice"; | |
| 8 | +import { loadSession, saveCurrentSession } from "../redux/thunks/session"; | |
| 9 | + | |
| 10 | +export const useCompactConversation = () => { | |
| 11 | + const dispatch = useAppDispatch(); | |
| 12 | + const ideMessenger = useContext(IdeMessengerContext); | |
| 13 | + const currentSessionId = useAppSelector((state) => state.session.id); | |
| 14 | + | |
| 15 | + return async (index: number) => { | |
| 16 | + if (!currentSessionId) { | |
| 17 | + return; | |
| 18 | + } | |
| 19 | + | |
| 20 | + try { | |
| 21 | + // Set loading state | |
| 22 | + dispatch(setCompactionLoading({ index, loading: true })); | |
| 23 | + | |
| 24 | + await ideMessenger.request("conversation/compact", { | |
| 25 | + index, | |
| 26 | + sessionId: currentSessionId, | |
| 27 | + }); | |
| 28 | + | |
| 29 | + // Reload the current session to refresh the conversation state | |
| 30 | + dispatch( | |
| 31 | + loadSession({ | |
| 32 | + sessionId: currentSessionId, | |
| 33 | + saveCurrentSession: false, | |
| 34 | + }), | |
| 35 | + ); | |
| 36 | + } catch (error) { | |
| 37 | + console.error("Error compacting conversation:", error); | |
| 38 | + } finally { | |
| 39 | + // Clear loading state | |
| 40 | + dispatch(setCompactionLoading({ index, loading: false })); | |
| 41 | + } | |
| 42 | + }; | |
| 43 | +}; | |
| 44 | + | |
| 45 | +export const useDeleteCompaction = () => { | |
| 46 | + const dispatch = useAppDispatch(); | |
| 47 | + | |
| 48 | + return (index: number) => { | |
| 49 | + // Update local state and save to persistence | |
| 50 | + dispatch(deleteCompaction(index)); | |
| 51 | + dispatch( | |
| 52 | + saveCurrentSession({ | |
| 53 | + openNewSession: false, | |
| 54 | + generateTitle: false, | |
| 55 | + }), | |
| 56 | + ); | |
| 57 | + }; | |
| 58 | +}; |
modified package-lock.json +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | { |
| 2 | - "name": "continue", | |
| 2 | + "name": "wt-openai-adapters-tests", | |
| 3 | 3 | "lockfileVersion": 3, |
| 4 | 4 | "requires": true, |
| 5 | 5 | "packages": { |
modified packages/config-yaml/CHANGELOG.md +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
added packages/config-yaml/src/load/unroll.test.ts +91 −0
| @@ -0,0 +1,91 @@ | ||
| 1 | +import { PackageIdentifier } from "../interfaces/slugs.js"; | |
| 2 | +import { parseMarkdownRuleOrAssistantUnrolled } from "./unroll.js"; | |
| 3 | + | |
| 4 | +describe("parseMarkdownRuleOrAssistantUnrolled tests", () => { | |
| 5 | + it("parses valid YAML content as AssistantUnrolled", () => { | |
| 6 | + const mockId: PackageIdentifier = { | |
| 7 | + uriType: "file", | |
| 8 | + filePath: "./foo/bar.yaml", | |
| 9 | + }; | |
| 10 | + const yamlContent = ` | |
| 11 | +name: Test Assistant | |
| 12 | +version: 1.0.0 | |
| 13 | + | |
| 14 | +models: | |
| 15 | + - name: model | |
| 16 | + model: modelname | |
| 17 | + provider: ollama | |
| 18 | +`; | |
| 19 | + const result = parseMarkdownRuleOrAssistantUnrolled(yamlContent, mockId); | |
| 20 | + expect(result).toHaveProperty("name", "Test Assistant"); | |
| 21 | + expect(result).toHaveProperty("version", "1.0.0"); | |
| 22 | + expect(result.models?.length).toBe(1); | |
| 23 | + expect(result.models?.[0]).toHaveProperty("name", "model"); | |
| 24 | + }); | |
| 25 | + | |
| 26 | + it("parses markdown rule content as AssistantUnrolled", () => { | |
| 27 | + const mockId: PackageIdentifier = { | |
| 28 | + uriType: "file", | |
| 29 | + filePath: "./foo/bar.md", | |
| 30 | + }; | |
| 31 | + const markdownContent = ` | |
| 32 | +--- | |
| 33 | +name: rulename | |
| 34 | +description: my rule description | |
| 35 | +pattern: "**" | |
| 36 | +--- | |
| 37 | +This is the rule | |
| 38 | +`; | |
| 39 | + const result = parseMarkdownRuleOrAssistantUnrolled( | |
| 40 | + markdownContent, | |
| 41 | + mockId, | |
| 42 | + ); | |
| 43 | + expect(result).toHaveProperty("name"); | |
| 44 | + expect(result).toHaveProperty("version"); | |
| 45 | + expect(Array.isArray(result.rules)).toBe(true); | |
| 46 | + expect(result.rules).toBeDefined(); | |
| 47 | + expect(result.rules!.length).toBe(1); | |
| 48 | + const rule = result.rules![0]; | |
| 49 | + expect(rule).toHaveProperty("name", "rulename"); | |
| 50 | + expect(rule).toHaveProperty("description", "my rule description"); | |
| 51 | + expect(rule).toHaveProperty("globs", "./foo/**/*"); | |
| 52 | + expect(rule).toHaveProperty("rule", "This is the rule"); | |
| 53 | + }); | |
| 54 | + | |
| 55 | + it("throws error for invalid content in yaml file", () => { | |
| 56 | + const mockId: PackageIdentifier = { | |
| 57 | + uriType: "file", | |
| 58 | + filePath: "./foo/bar.yaml", | |
| 59 | + }; | |
| 60 | + const invalidContent = ` | |
| 61 | +name: Test Assistant | |
| 62 | +version: 1.0.0 | |
| 63 | + | |
| 64 | +model: # should be models | |
| 65 | + - name: model | |
| 66 | + model: modelname | |
| 67 | + provider: ollama | |
| 68 | +`; | |
| 69 | + expect(() => | |
| 70 | + parseMarkdownRuleOrAssistantUnrolled(invalidContent, mockId), | |
| 71 | + ).toThrow(); | |
| 72 | + }); | |
| 73 | + | |
| 74 | + it("Every non-YAML file is a rule", () => { | |
| 75 | + const mockId: PackageIdentifier = { | |
| 76 | + uriType: "file", | |
| 77 | + filePath: "./foo/bar", | |
| 78 | + }; | |
| 79 | + const dubiousContent = `This is not \nproper #YAML#`; | |
| 80 | + const result = parseMarkdownRuleOrAssistantUnrolled(dubiousContent, mockId); | |
| 81 | + expect(result).toHaveProperty("name"); | |
| 82 | + expect(result).toHaveProperty("version"); | |
| 83 | + expect(Array.isArray(result.rules)).toBe(true); | |
| 84 | + expect(result.rules).toBeDefined(); | |
| 85 | + expect(result.rules!.length).toBe(1); | |
| 86 | + const rule = result.rules![0]; | |
| 87 | + expect(rule).toHaveProperty("name", "foo/bar"); | |
| 88 | + expect(rule).toHaveProperty("globs", "./foo/**/*"); | |
| 89 | + expect(rule).toHaveProperty("rule", dubiousContent); | |
| 90 | + }); | |
| 91 | +}); |
modified packages/config-yaml/src/load/unroll.ts +25 −52
| @@ -286,9 +286,7 @@ | ||
| 286 | 286 | options.platformClient, |
| 287 | 287 | options.alwaysUseProxy, |
| 288 | 288 | ); |
| 289 | - const renderedYaml = renderTemplateData(templatedYaml, { | |
| 290 | - secrets, | |
| 291 | - }); | |
| 289 | + const renderedYaml = renderTemplateData(templatedYaml, { secrets }); | |
| 292 | 290 | |
| 293 | 291 | // Parse again and replace models with proxy versions where secrets weren't rendered |
| 294 | 292 | const finalConfig = useProxyForUnrenderedSecrets( |
| @@ -298,11 +296,7 @@ | ||
| 298 | 296 | options.onPremProxyUrl, |
| 299 | 297 | ); |
| 300 | 298 | |
| 301 | - return { | |
| 302 | - config: finalConfig, | |
| 303 | - errors, | |
| 304 | - configLoadInterrupted, | |
| 305 | - }; | |
| 299 | + return { config: finalConfig, errors, configLoadInterrupted }; | |
| 306 | 300 | } |
| 307 | 301 | |
| 308 | 302 | export async function unrollBlocks( |
| @@ -366,10 +360,7 @@ | ||
| 366 | 360 | return { |
| 367 | 361 | index, |
| 368 | 362 | block: null, |
| 369 | - error: { | |
| 370 | - fatal: false, | |
| 371 | - message: msg, | |
| 372 | - }, | |
| 363 | + error: { fatal: false, message: msg }, | |
| 373 | 364 | }; |
| 374 | 365 | } |
| 375 | 366 | } else { |
| @@ -461,11 +452,7 @@ | ||
| 461 | 452 | registry, |
| 462 | 453 | ); |
| 463 | 454 | |
| 464 | - return { | |
| 465 | - blockType, | |
| 466 | - resolvedBlock, | |
| 467 | - error: null, | |
| 468 | - }; | |
| 455 | + return { blockType, resolvedBlock, error: null }; | |
| 469 | 456 | } catch (err) { |
| 470 | 457 | let msg = ""; |
| 471 | 458 | if (injectBlock.uriType === "file") { |
| @@ -481,10 +468,7 @@ | ||
| 481 | 468 | return { |
| 482 | 469 | blockType: null, |
| 483 | 470 | resolvedBlock: null, |
| 484 | - error: { | |
| 485 | - fatal: false, | |
| 486 | - message: msg, | |
| 487 | - }, | |
| 471 | + error: { fatal: false, message: msg }, | |
| 488 | 472 | }; |
| 489 | 473 | } |
| 490 | 474 | }); |
| @@ -581,57 +565,46 @@ | ||
| 581 | 565 | return parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id); |
| 582 | 566 | } |
| 583 | 567 | |
| 584 | -function parseMarkdownRuleOrAssistantUnrolled( | |
| 568 | +export function parseMarkdownRuleOrAssistantUnrolled( | |
| 585 | 569 | content: string, |
| 586 | 570 | id: PackageIdentifier, |
| 587 | 571 | ): AssistantUnrolled { |
| 588 | - // Try to parse as YAML first, then as markdown rule if that fails | |
| 589 | - let parsedYaml: AssistantUnrolled; | |
| 590 | - try { | |
| 591 | - parsedYaml = parseBlock(content); | |
| 592 | - } catch (yamlError) { | |
| 593 | - // If YAML parsing fails, try parsing as markdown rule | |
| 594 | - try { | |
| 595 | - const rule = markdownToRule(content, id); | |
| 596 | - // Convert the rule object to the expected format | |
| 597 | - parsedYaml = { | |
| 598 | - name: rule.name, | |
| 599 | - version: "1.0.0", | |
| 600 | - rules: [rule], | |
| 601 | - }; | |
| 602 | - } catch (markdownError) { | |
| 603 | - // If both fail, throw the original YAML error | |
| 604 | - throw yamlError; | |
| 605 | - } | |
| 606 | - } | |
| 607 | - | |
| 608 | - return parsedYaml; | |
| 572 | + return parseYamlOrMarkdownRule<AssistantUnrolled>(content, id, parseBlock); | |
| 609 | 573 | } |
| 610 | 574 | |
| 611 | 575 | function parseMarkdownRuleOrConfigYaml( |
| 612 | 576 | content: string, |
| 613 | 577 | id: PackageIdentifier, |
| 614 | 578 | ): ConfigYaml { |
| 615 | - // Try to parse as YAML first, then as markdown rule if that fails | |
| 616 | - let parsedYaml: ConfigYaml; | |
| 579 | + return parseYamlOrMarkdownRule<ConfigYaml>(content, id, parseConfigYaml); | |
| 580 | +} | |
| 581 | + | |
| 582 | +function parseYamlOrMarkdownRule<T>( | |
| 583 | + content: string, | |
| 584 | + id: PackageIdentifier, | |
| 585 | + parseYamlFn: (content: string) => T, | |
| 586 | +): T { | |
| 587 | + let parsedYaml: T; | |
| 617 | 588 | try { |
| 618 | - parsedYaml = parseConfigYaml(content); | |
| 589 | + // Try to parse as YAML first, then as markdown rule if that fails | |
| 590 | + parsedYaml = parseYamlFn(content); | |
| 619 | 591 | } catch (yamlError) { |
| 592 | + if ( | |
| 593 | + id.uriType === "file" && | |
| 594 | + [".yaml", ".yml"].some((ext) => id.filePath.endsWith(ext)) | |
| 595 | + ) { | |
| 596 | + throw yamlError; | |
| 597 | + } | |
| 620 | 598 | // If YAML parsing fails, try parsing as markdown rule |
| 621 | 599 | try { |
| 622 | 600 | const rule = markdownToRule(content, id); |
| 623 | 601 | // Convert the rule object to the expected format |
| 624 | - parsedYaml = { | |
| 625 | - name: rule.name, | |
| 626 | - version: "1.0.0", | |
| 627 | - rules: [rule], | |
| 628 | - }; | |
| 602 | + parsedYaml = { name: rule.name, version: "1.0.0", rules: [rule] } as T; | |
| 629 | 603 | } catch (markdownError) { |
| 630 | 604 | // If both fail, throw the original YAML error |
| 631 | 605 | throw yamlError; |
| 632 | 606 | } |
| 633 | 607 | } |
| 634 | - | |
| 635 | 608 | return parsedYaml; |
| 636 | 609 | } |
| 637 | 610 |
modified packages/continue-sdk/typescript/src/createOpenAIClient.ts +4 −1
| @@ -71,7 +71,10 @@ | ||
| 71 | 71 | ); |
| 72 | 72 | } |
| 73 | 73 | |
| 74 | - if (!("apiKeyLocation" in modelConfig) && !("envSecretLocations" in modelConfig)) { | |
| 74 | + if ( | |
| 75 | + !("apiKeyLocation" in modelConfig) && | |
| 76 | + !("envSecretLocations" in modelConfig) | |
| 77 | + ) { | |
| 75 | 78 | throw new Error( |
| 76 | 79 | `Model ${modelName} does not have an apiKeyLocation or envSecretLocations defined`, |
| 77 | 80 | ); |
modified packages/openai-adapters/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified packages/openai-adapters/package.json +11 −3
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "@continuedev/openai-adapters", |
| 3 | - "version": "1.0.45", | |
| 3 | + "version": "1.0.46", | |
| 4 | 4 | "description": "", |
| 5 | 5 | "main": "dist/index.js", |
| 6 | 6 | "types": "dist/index.d.ts", |
| 7 | 7 | "type": "module", |
| 8 | 8 | "scripts": { |
| 9 | - "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", | |
| 9 | + "test": "vitest", | |
| 10 | 10 | "build": "tsc" |
| 11 | 11 | }, |
| 12 | 12 | "author": "Nate Sesti and Ty Dunn", |
| @@ -25,11 +25,19 @@ | ||
| 25 | 25 | "zod": "^3.24.2" |
| 26 | 26 | }, |
| 27 | 27 | "devDependencies": { |
| 28 | + "@semantic-release/changelog": "^6.0.3", | |
| 29 | + "@semantic-release/commit-analyzer": "^13.0.1", | |
| 30 | + "@semantic-release/git": "^10.0.1", | |
| 31 | + "@semantic-release/github": "^11.0.3", | |
| 32 | + "@semantic-release/npm": "^12.0.2", | |
| 33 | + "@semantic-release/release-notes-generator": "^14.0.3", | |
| 28 | 34 | "@types/follow-redirects": "^1.14.4", |
| 29 | 35 | "@types/jest": "^29.5.14", |
| 30 | 36 | "@types/json-schema": "^7.0.15", |
| 31 | 37 | "cross-env": "^7.0.3", |
| 38 | + "semantic-release": "^24.2.7", | |
| 32 | 39 | "ts-jest": "^29.2.3", |
| 33 | - "ts-node": "^10.9.2" | |
| 40 | + "ts-node": "^10.9.2", | |
| 41 | + "vitest": "^1.6.1" | |
| 34 | 42 | } |
| 35 | 43 | } |
modified packages/openai-adapters/src/apis/Anthropic.ts +54 −3
| @@ -8,12 +8,22 @@ | ||
| 8 | 8 | Completion, |
| 9 | 9 | CompletionCreateParamsNonStreaming, |
| 10 | 10 | CompletionCreateParamsStreaming, |
| 11 | + CompletionUsage, | |
| 11 | 12 | } from "openai/resources/index"; |
| 12 | 13 | import { ChatCompletionCreateParams } from "openai/src/resources/index.js"; |
| 13 | 14 | import { AnthropicConfig } from "../types.js"; |
| 14 | -import { chatChunk, chatChunkFromDelta, customFetch } from "../util.js"; | |
| 15 | +import { | |
| 16 | + chatChunk, | |
| 17 | + chatChunkFromDelta, | |
| 18 | + customFetch, | |
| 19 | + usageChatChunk, | |
| 20 | +} from "../util.js"; | |
| 15 | 21 | import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js"; |
| 16 | 22 | import { safeParseArgs } from "../util/parseArgs.js"; |
| 23 | +import { | |
| 24 | + CACHING_STRATEGIES, | |
| 25 | + CachingStrategyName, | |
| 26 | +} from "./AnthropicCachingStrategies.js"; | |
| 17 | 27 | import { |
| 18 | 28 | BaseLlmApi, |
| 19 | 29 | CreateRerankResponse, |
| @@ -24,7 +34,11 @@ | ||
| 24 | 34 | export class AnthropicApi implements BaseLlmApi { |
| 25 | 35 | apiBase: string = "https://api.anthropic.com/v1/"; |
| 26 | 36 | |
| 27 | - constructor(protected config: AnthropicConfig) { | |
| 37 | + constructor( | |
| 38 | + protected config: AnthropicConfig & { | |
| 39 | + cachingStrategy?: CachingStrategyName; | |
| 40 | + }, | |
| 41 | + ) { | |
| 28 | 42 | this.apiBase = config.apiBase ?? this.apiBase; |
| 29 | 43 | if (!this.apiBase.endsWith("/")) { |
| 30 | 44 | this.apiBase += "/"; |
| @@ -32,6 +46,16 @@ | ||
| 32 | 46 | } |
| 33 | 47 | |
| 34 | 48 | private _convertBody(oaiBody: ChatCompletionCreateParams) { |
| 49 | + // Step 1: Convert to clean Anthropic body (no caching) | |
| 50 | + const cleanBody = this._convertToCleanAnthropicBody(oaiBody); | |
| 51 | + | |
| 52 | + // Step 2: Apply caching strategy | |
| 53 | + const cachingStrategy = | |
| 54 | + CACHING_STRATEGIES[this.config.cachingStrategy ?? "systemAndTools"]; | |
| 55 | + return cachingStrategy(cleanBody); | |
| 56 | + } | |
| 57 | + | |
| 58 | + private _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) { | |
| 35 | 59 | let stop = undefined; |
| 36 | 60 | if (oaiBody.stop && Array.isArray(oaiBody.stop)) { |
| 37 | 61 | stop = oaiBody.stop.filter((x) => x.trim() !== ""); |
| @@ -52,7 +76,6 @@ | ||
| 52 | 76 | { |
| 53 | 77 | type: "text", |
| 54 | 78 | text: systemMessage, |
| 55 | - cache_control: { type: "ephemeral" }, | |
| 56 | 79 | }, |
| 57 | 80 | ] |
| 58 | 81 | : systemMessage, |
| @@ -155,6 +178,7 @@ | ||
| 155 | 178 | "Content-Type": "application/json", |
| 156 | 179 | Accept: "application/json", |
| 157 | 180 | "anthropic-version": "2023-06-01", |
| 181 | + "anthropic-beta": "prompt-caching-2024-07-31", | |
| 158 | 182 | "x-api-key": this.config.apiKey, |
| 159 | 183 | }, |
| 160 | 184 | body: JSON.stringify(this._convertBody(body)), |
| @@ -177,6 +201,9 @@ | ||
| 177 | 201 | completion.usage.input_tokens + completion.usage.output_tokens, |
| 178 | 202 | completion_tokens: completion.usage.output_tokens, |
| 179 | 203 | prompt_tokens: completion.usage.input_tokens, |
| 204 | + prompt_tokens_details: { | |
| 205 | + cached_tokens: completion.usage.cache_read_input_tokens || 0, | |
| 206 | + }, | |
| 180 | 207 | }, |
| 181 | 208 | choices: [ |
| 182 | 209 | { |
| @@ -205,6 +232,7 @@ | ||
| 205 | 232 | "Content-Type": "application/json", |
| 206 | 233 | Accept: "application/json", |
| 207 | 234 | "anthropic-version": "2023-06-01", |
| 235 | + "anthropic-beta": "prompt-caching-2024-07-31", | |
| 208 | 236 | "x-api-key": this.config.apiKey, |
| 209 | 237 | }, |
| 210 | 238 | body: JSON.stringify(this._convertBody(body)), |
| @@ -214,6 +242,12 @@ | ||
| 214 | 242 | |
| 215 | 243 | let lastToolUseId: string | undefined; |
| 216 | 244 | let lastToolUseName: string | undefined; |
| 245 | + | |
| 246 | + const usage: CompletionUsage = { | |
| 247 | + completion_tokens: 0, | |
| 248 | + prompt_tokens: 0, | |
| 249 | + total_tokens: 0, | |
| 250 | + }; | |
| 217 | 251 | for await (const value of streamSse(response as any)) { |
| 218 | 252 | // https://docs.anthropic.com/en/api/messages-streaming#event-types |
| 219 | 253 | switch (value.type) { |
| @@ -223,6 +257,15 @@ | ||
| 223 | 257 | lastToolUseName = value.content_block.name; |
| 224 | 258 | } |
| 225 | 259 | break; |
| 260 | + case "message_start": | |
| 261 | + usage.prompt_tokens = value.message.usage.input_tokens; | |
| 262 | + usage.prompt_tokens_details = { | |
| 263 | + cached_tokens: value.message.usage.cache_read_input_tokens || 0, | |
| 264 | + }; | |
| 265 | + break; | |
| 266 | + case "message_delta": | |
| 267 | + usage.completion_tokens = value.usage.output_tokens; | |
| 268 | + break; | |
| 226 | 269 | case "content_block_delta": |
| 227 | 270 | // https://docs.anthropic.com/en/api/messages-streaming#delta-types |
| 228 | 271 | switch (value.delta.type) { |
| @@ -263,6 +306,14 @@ | ||
| 263 | 306 | break; |
| 264 | 307 | } |
| 265 | 308 | } |
| 309 | + | |
| 310 | + yield usageChatChunk({ | |
| 311 | + model: body.model, | |
| 312 | + usage: { | |
| 313 | + ...usage, | |
| 314 | + total_tokens: usage.completion_tokens + usage.prompt_tokens, | |
| 315 | + }, | |
| 316 | + }); | |
| 266 | 317 | } |
| 267 | 318 | async completionNonStream( |
| 268 | 319 | body: CompletionCreateParamsNonStreaming, |
added packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts +369 −0
| @@ -0,0 +1,369 @@ | ||
| 1 | +import { | |
| 2 | + CACHING_STRATEGIES, | |
| 3 | + CachingStrategy, | |
| 4 | + CachingStrategyName, | |
| 5 | + getAvailableStrategies, | |
| 6 | + getStrategyDescription, | |
| 7 | +} from "./AnthropicCachingStrategies.js"; | |
| 8 | + | |
| 9 | +describe("AnthropicCachingStrategies", () => { | |
| 10 | + describe("noCachingStrategy", () => { | |
| 11 | + it("should return the body unchanged", () => { | |
| 12 | + const body = { system: "test", messages: [] }; | |
| 13 | + const result = CACHING_STRATEGIES.none(body); | |
| 14 | + expect(result).toBe(body); | |
| 15 | + }); | |
| 16 | + | |
| 17 | + it("should not modify complex objects", () => { | |
| 18 | + const body = { | |
| 19 | + system: [{ text: "test" }], | |
| 20 | + tools: [{ name: "test" }], | |
| 21 | + messages: [{ content: "test" }], | |
| 22 | + }; | |
| 23 | + const result = CACHING_STRATEGIES.none(body); | |
| 24 | + expect(result).toBe(body); | |
| 25 | + }); | |
| 26 | + }); | |
| 27 | + | |
| 28 | + describe("systemOnlyStrategy", () => { | |
| 29 | + it("should add cache_control to system messages array", () => { | |
| 30 | + const body = { | |
| 31 | + system: [{ text: "system message 1" }, { text: "system message 2" }], | |
| 32 | + messages: [{ content: "user message" }], | |
| 33 | + }; | |
| 34 | + | |
| 35 | + const result = CACHING_STRATEGIES.systemOnly(body); | |
| 36 | + | |
| 37 | + expect(result.system).toEqual([ | |
| 38 | + { text: "system message 1", cache_control: { type: "ephemeral" } }, | |
| 39 | + { text: "system message 2", cache_control: { type: "ephemeral" } }, | |
| 40 | + ]); | |
| 41 | + expect(result.messages).toEqual(body.messages); | |
| 42 | + }); | |
| 43 | + | |
| 44 | + it("should return body unchanged if system is not an array", () => { | |
| 45 | + const body = { | |
| 46 | + system: "string system message", | |
| 47 | + messages: [{ content: "user message" }], | |
| 48 | + }; | |
| 49 | + | |
| 50 | + const result = CACHING_STRATEGIES.systemOnly(body); | |
| 51 | + expect(result).toEqual(body); | |
| 52 | + }); | |
| 53 | + | |
| 54 | + it("should return body unchanged if system is undefined", () => { | |
| 55 | + const body = { | |
| 56 | + messages: [{ content: "user message" }], | |
| 57 | + }; | |
| 58 | + | |
| 59 | + const result = CACHING_STRATEGIES.systemOnly(body); | |
| 60 | + expect(result).toEqual(body); | |
| 61 | + }); | |
| 62 | + }); | |
| 63 | + | |
| 64 | + describe("systemAndToolsStrategy", () => { | |
| 65 | + it("should add cache_control to both system and tools", () => { | |
| 66 | + const body = { | |
| 67 | + system: [{ text: "system message" }], | |
| 68 | + tools: [{ name: "tool1" }, { name: "tool2" }], | |
| 69 | + messages: [{ content: "user message" }], | |
| 70 | + }; | |
| 71 | + | |
| 72 | + const result = CACHING_STRATEGIES.systemAndTools(body); | |
| 73 | + | |
| 74 | + expect(result.system).toEqual([ | |
| 75 | + { text: "system message", cache_control: { type: "ephemeral" } }, | |
| 76 | + ]); | |
| 77 | + expect(result.tools).toEqual([ | |
| 78 | + { name: "tool1" }, | |
| 79 | + { name: "tool2", cache_control: { type: "ephemeral" } }, | |
| 80 | + ]); | |
| 81 | + expect(result.messages).toEqual(body.messages); | |
| 82 | + }); | |
| 83 | + | |
| 84 | + it("should handle missing system messages", () => { | |
| 85 | + const body = { | |
| 86 | + tools: [{ name: "tool1" }], | |
| 87 | + messages: [{ content: "user message" }], | |
| 88 | + }; | |
| 89 | + | |
| 90 | + const result = CACHING_STRATEGIES.systemAndTools(body); | |
| 91 | + | |
| 92 | + expect(result.tools).toEqual([ | |
| 93 | + { name: "tool1", cache_control: { type: "ephemeral" } }, | |
| 94 | + ]); | |
| 95 | + expect(result.messages).toEqual(body.messages); | |
| 96 | + }); | |
| 97 | + | |
| 98 | + it("should handle missing tools", () => { | |
| 99 | + const body = { | |
| 100 | + system: [{ text: "system message" }], | |
| 101 | + messages: [{ content: "user message" }], | |
| 102 | + }; | |
| 103 | + | |
| 104 | + const result = CACHING_STRATEGIES.systemAndTools(body); | |
| 105 | + | |
| 106 | + expect(result.system).toEqual([ | |
| 107 | + { text: "system message", cache_control: { type: "ephemeral" } }, | |
| 108 | + ]); | |
| 109 | + expect(result.messages).toEqual(body.messages); | |
| 110 | + }); | |
| 111 | + | |
| 112 | + it("should handle non-array system and tools", () => { | |
| 113 | + const body = { | |
| 114 | + system: "string system", | |
| 115 | + tools: "string tools", | |
| 116 | + messages: [{ content: "user message" }], | |
| 117 | + }; | |
| 118 | + | |
| 119 | + const result = CACHING_STRATEGIES.systemAndTools(body); | |
| 120 | + expect(result).toEqual(body); | |
| 121 | + }); | |
| 122 | + }); | |
| 123 | + | |
| 124 | + describe("optimizedStrategy", () => { | |
| 125 | + it("should cache system messages and tools", () => { | |
| 126 | + const body = { | |
| 127 | + system: [{ text: "system message" }], | |
| 128 | + tools: [{ name: "tool1" }], | |
| 129 | + messages: [{ content: "short message" }], | |
| 130 | + }; | |
| 131 | + | |
| 132 | + const result = CACHING_STRATEGIES.optimized(body); | |
| 133 | + | |
| 134 | + expect(result.system).toEqual([ | |
| 135 | + { text: "system message", cache_control: { type: "ephemeral" } }, | |
| 136 | + ]); | |
| 137 | + expect(result.tools).toEqual([ | |
| 138 | + { name: "tool1", cache_control: { type: "ephemeral" } }, | |
| 139 | + ]); | |
| 140 | + }); | |
| 141 | + | |
| 142 | + it("should cache large string messages (>500 tokens)", () => { | |
| 143 | + const largeContent = "a".repeat(2100); // ~525 tokens | |
| 144 | + const body = { | |
| 145 | + messages: [{ content: largeContent }], | |
| 146 | + }; | |
| 147 | + | |
| 148 | + const result = CACHING_STRATEGIES.optimized(body); | |
| 149 | + | |
| 150 | + expect(result.messages).toEqual([ | |
| 151 | + { | |
| 152 | + content: [ | |
| 153 | + { | |
| 154 | + type: "text", | |
| 155 | + text: largeContent, | |
| 156 | + cache_control: { type: "ephemeral" }, | |
| 157 | + }, | |
| 158 | + ], | |
| 159 | + }, | |
| 160 | + ]); | |
| 161 | + }); | |
| 162 | + | |
| 163 | + it("should not cache small string messages (<500 tokens)", () => { | |
| 164 | + const smallContent = "a".repeat(100); // ~25 tokens | |
| 165 | + const body = { | |
| 166 | + messages: [{ content: smallContent }], | |
| 167 | + }; | |
| 168 | + | |
| 169 | + const result = CACHING_STRATEGIES.optimized(body); | |
| 170 | + | |
| 171 | + expect(result.messages).toEqual([{ content: smallContent }]); | |
| 172 | + }); | |
| 173 | + | |
| 174 | + it("should cache large text items in array content", () => { | |
| 175 | + const largeText = "a".repeat(2100); // ~525 tokens | |
| 176 | + const smallText = "a".repeat(100); // ~25 tokens | |
| 177 | + const body = { | |
| 178 | + messages: [ | |
| 179 | + { | |
| 180 | + content: [ | |
| 181 | + { type: "text", text: largeText }, | |
| 182 | + { type: "text", text: smallText }, | |
| 183 | + { type: "image", data: "image_data" }, | |
| 184 | + ], | |
| 185 | + }, | |
| 186 | + ], | |
| 187 | + }; | |
| 188 | + | |
| 189 | + const result = CACHING_STRATEGIES.optimized(body); | |
| 190 | + | |
| 191 | + expect(result.messages).toEqual([ | |
| 192 | + { | |
| 193 | + content: [ | |
| 194 | + { | |
| 195 | + type: "text", | |
| 196 | + text: largeText, | |
| 197 | + cache_control: { type: "ephemeral" }, | |
| 198 | + }, | |
| 199 | + { type: "text", text: smallText }, | |
| 200 | + { type: "image", data: "image_data" }, | |
| 201 | + ], | |
| 202 | + }, | |
| 203 | + ]); | |
| 204 | + }); | |
| 205 | + | |
| 206 | + it("should handle complex message structure", () => { | |
| 207 | + const body = { | |
| 208 | + system: [{ text: "system" }], | |
| 209 | + tools: [{ name: "tool" }], | |
| 210 | + messages: [ | |
| 211 | + { content: "small content" }, | |
| 212 | + { content: "a".repeat(2100) }, // large content | |
| 213 | + { | |
| 214 | + content: [ | |
| 215 | + { type: "text", text: "a".repeat(2100) }, // large text | |
| 216 | + { type: "image", data: "image" }, | |
| 217 | + ], | |
| 218 | + }, | |
| 219 | + ], | |
| 220 | + }; | |
| 221 | + | |
| 222 | + const result = CACHING_STRATEGIES.optimized(body); | |
| 223 | + | |
| 224 | + expect(result.system).toEqual([ | |
| 225 | + { text: "system", cache_control: { type: "ephemeral" } }, | |
| 226 | + ]); | |
| 227 | + expect(result.tools).toEqual([ | |
| 228 | + { name: "tool", cache_control: { type: "ephemeral" } }, | |
| 229 | + ]); | |
| 230 | + expect(result.messages[0]).toEqual({ content: "small content" }); | |
| 231 | + expect(result.messages[1]).toEqual({ | |
| 232 | + content: [ | |
| 233 | + { | |
| 234 | + type: "text", | |
| 235 | + text: "a".repeat(2100), | |
| 236 | + cache_control: { type: "ephemeral" }, | |
| 237 | + }, | |
| 238 | + ], | |
| 239 | + }); | |
| 240 | + expect(result.messages[2].content[0]).toEqual({ | |
| 241 | + type: "text", | |
| 242 | + text: "a".repeat(2100), | |
| 243 | + cache_control: { type: "ephemeral" }, | |
| 244 | + }); | |
| 245 | + }); | |
| 246 | + | |
| 247 | + it("should handle empty or missing messages", () => { | |
| 248 | + const body = { | |
| 249 | + system: [{ text: "system" }], | |
| 250 | + }; | |
| 251 | + | |
| 252 | + const result = CACHING_STRATEGIES.optimized(body); | |
| 253 | + | |
| 254 | + expect(result.system).toEqual([ | |
| 255 | + { text: "system", cache_control: { type: "ephemeral" } }, | |
| 256 | + ]); | |
| 257 | + expect(result.messages).toBeUndefined(); | |
| 258 | + }); | |
| 259 | + | |
| 260 | + it("should handle non-array messages", () => { | |
| 261 | + const body = { | |
| 262 | + system: [{ text: "system" }], | |
| 263 | + messages: "not an array", | |
| 264 | + }; | |
| 265 | + | |
| 266 | + const result = CACHING_STRATEGIES.optimized(body); | |
| 267 | + | |
| 268 | + expect(result.system).toEqual([ | |
| 269 | + { text: "system", cache_control: { type: "ephemeral" } }, | |
| 270 | + ]); | |
| 271 | + expect(result.messages).toBe("not an array"); | |
| 272 | + }); | |
| 273 | + }); | |
| 274 | + | |
| 275 | + describe("estimateTokenCount", () => { | |
| 276 | + it("should estimate token count correctly", () => { | |
| 277 | + // Test through the optimized strategy's behavior | |
| 278 | + const smallContent = "a".repeat(100); // ~25 tokens | |
| 279 | + const largeContent = "a".repeat(2100); // ~525 tokens | |
| 280 | + | |
| 281 | + const bodySmall = { messages: [{ content: smallContent }] }; | |
| 282 | + const bodyLarge = { messages: [{ content: largeContent }] }; | |
| 283 | + | |
| 284 | + const resultSmall = CACHING_STRATEGIES.optimized(bodySmall); | |
| 285 | + const resultLarge = CACHING_STRATEGIES.optimized(bodyLarge); | |
| 286 | + | |
| 287 | + // Small content should not be cached (remains string) | |
| 288 | + expect(resultSmall.messages[0].content).toBe(smallContent); | |
| 289 | + | |
| 290 | + // Large content should be cached (converted to array) | |
| 291 | + expect(Array.isArray(resultLarge.messages[0].content)).toBe(true); | |
| 292 | + }); | |
| 293 | + }); | |
| 294 | + | |
| 295 | + describe("getAvailableStrategies", () => { | |
| 296 | + it("should return all strategy names", () => { | |
| 297 | + const strategies = getAvailableStrategies(); | |
| 298 | + expect(strategies).toEqual([ | |
| 299 | + "none", | |
| 300 | + "systemOnly", | |
| 301 | + "systemAndTools", | |
| 302 | + "optimized", | |
| 303 | + ]); | |
| 304 | + }); | |
| 305 | + }); | |
| 306 | + | |
| 307 | + describe("getStrategyDescription", () => { | |
| 308 | + it("should return correct descriptions for all strategies", () => { | |
| 309 | + expect(getStrategyDescription("none")).toBe( | |
| 310 | + "No caching - baseline for comparison", | |
| 311 | + ); | |
| 312 | + expect(getStrategyDescription("systemOnly")).toBe( | |
| 313 | + "Cache only system messages (current implementation)", | |
| 314 | + ); | |
| 315 | + expect(getStrategyDescription("systemAndTools")).toBe( | |
| 316 | + "Cache system messages and tool definitions (high impact)", | |
| 317 | + ); | |
| 318 | + expect(getStrategyDescription("optimized")).toBe( | |
| 319 | + "Intelligent caching - system, tools, and large content (best performance)", | |
| 320 | + ); | |
| 321 | + }); | |
| 322 | + }); | |
| 323 | + | |
| 324 | + describe("CACHING_STRATEGIES", () => { | |
| 325 | + it("should contain all expected strategies", () => { | |
| 326 | + expect(Object.keys(CACHING_STRATEGIES)).toEqual([ | |
| 327 | + "none", | |
| 328 | + "systemOnly", | |
| 329 | + "systemAndTools", | |
| 330 | + "optimized", | |
| 331 | + ]); | |
| 332 | + }); | |
| 333 | + | |
| 334 | + it("should have all strategies as functions", () => { | |
| 335 | + Object.values(CACHING_STRATEGIES).forEach((strategy) => { | |
| 336 | + expect(typeof strategy).toBe("function"); | |
| 337 | + }); | |
| 338 | + }); | |
| 339 | + }); | |
| 340 | + | |
| 341 | + describe("CachingStrategy type", () => { | |
| 342 | + it("should accept valid caching strategy functions", () => { | |
| 343 | + const customStrategy: CachingStrategy = (body) => ({ | |
| 344 | + ...body, | |
| 345 | + custom: true, | |
| 346 | + }); | |
| 347 | + | |
| 348 | + const input = { test: "value" }; | |
| 349 | + const result = customStrategy(input); | |
| 350 | + | |
| 351 | + expect(result).toEqual({ test: "value", custom: true }); | |
| 352 | + }); | |
| 353 | + }); | |
| 354 | + | |
| 355 | + describe("CachingStrategyName type", () => { | |
| 356 | + it("should work with valid strategy names", () => { | |
| 357 | + const strategyNames: CachingStrategyName[] = [ | |
| 358 | + "none", | |
| 359 | + "systemOnly", | |
| 360 | + "systemAndTools", | |
| 361 | + "optimized", | |
| 362 | + ]; | |
| 363 | + | |
| 364 | + strategyNames.forEach((name) => { | |
| 365 | + expect(typeof CACHING_STRATEGIES[name]).toBe("function"); | |
| 366 | + }); | |
| 367 | + }); | |
| 368 | + }); | |
| 369 | +}); |
added packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts +147 −0
| @@ -0,0 +1,147 @@ | ||
| 1 | +// Caching strategy type - transforms a clean Anthropic body by adding cache_control | |
| 2 | +export type CachingStrategy = (anthropicBody: any) => any; | |
| 3 | + | |
| 4 | +// Utility function to estimate token count | |
| 5 | +const estimateTokenCount = (text: string): number => Math.ceil(text.length / 4); | |
| 6 | + | |
| 7 | +// Strategy 1: No Caching (Baseline) | |
| 8 | +const noCachingStrategy: CachingStrategy = (body) => body; | |
| 9 | + | |
| 10 | +// Strategy 2: System Messages Only (Current Implementation) | |
| 11 | +const systemOnlyStrategy: CachingStrategy = (body) => { | |
| 12 | + if (body.system && Array.isArray(body.system)) { | |
| 13 | + return { | |
| 14 | + ...body, | |
| 15 | + system: body.system.map((item: any) => ({ | |
| 16 | + ...item, | |
| 17 | + cache_control: { type: "ephemeral" }, | |
| 18 | + })), | |
| 19 | + }; | |
| 20 | + } | |
| 21 | + return body; | |
| 22 | +}; | |
| 23 | + | |
| 24 | +// Strategy 3: System and Tools (High Impact) | |
| 25 | +const systemAndToolsStrategy: CachingStrategy = (body) => { | |
| 26 | + const result = { ...body }; | |
| 27 | + | |
| 28 | + // Cache system messages | |
| 29 | + if (result.system && Array.isArray(result.system)) { | |
| 30 | + result.system = result.system.map((item: any) => ({ | |
| 31 | + ...item, | |
| 32 | + cache_control: { type: "ephemeral" }, | |
| 33 | + })); | |
| 34 | + } | |
| 35 | + | |
| 36 | + // Cache tool definitions | |
| 37 | + if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) { | |
| 38 | + result.tools = result.tools.map((tool: any, index: number) => { | |
| 39 | + if (index === result.tools.length - 1) { | |
| 40 | + return { | |
| 41 | + ...tool, | |
| 42 | + cache_control: { type: "ephemeral" }, | |
| 43 | + }; | |
| 44 | + } | |
| 45 | + return tool; | |
| 46 | + }); | |
| 47 | + } | |
| 48 | + | |
| 49 | + return result; | |
| 50 | +}; | |
| 51 | + | |
| 52 | +// Strategy 4: Optimized (Intelligent Caching) | |
| 53 | +const optimizedStrategy: CachingStrategy = (body) => { | |
| 54 | + const result = { ...body }; | |
| 55 | + | |
| 56 | + // Always cache system messages | |
| 57 | + if (result.system && Array.isArray(result.system)) { | |
| 58 | + result.system = result.system.map((item: any) => ({ | |
| 59 | + ...item, | |
| 60 | + cache_control: { type: "ephemeral" }, | |
| 61 | + })); | |
| 62 | + } | |
| 63 | + | |
| 64 | + // Cache tool definitions | |
| 65 | + if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) { | |
| 66 | + result.tools = result.tools.map((tool: any, index: number) => { | |
| 67 | + if (index === result.tools.length - 1) { | |
| 68 | + return { | |
| 69 | + ...tool, | |
| 70 | + cache_control: { type: "ephemeral" }, | |
| 71 | + }; | |
| 72 | + } | |
| 73 | + return tool; | |
| 74 | + }); | |
| 75 | + } | |
| 76 | + | |
| 77 | + // Cache large messages (>500 tokens) | |
| 78 | + if (result.messages && Array.isArray(result.messages)) { | |
| 79 | + result.messages = result.messages.map((message: any) => { | |
| 80 | + if (message.content && typeof message.content === "string") { | |
| 81 | + const tokens = estimateTokenCount(message.content); | |
| 82 | + if (tokens > 500) { | |
| 83 | + return { | |
| 84 | + ...message, | |
| 85 | + content: [ | |
| 86 | + { | |
| 87 | + type: "text", | |
| 88 | + text: message.content, | |
| 89 | + cache_control: { type: "ephemeral" }, | |
| 90 | + }, | |
| 91 | + ], | |
| 92 | + }; | |
| 93 | + } | |
| 94 | + } else if (message.content && Array.isArray(message.content)) { | |
| 95 | + const updatedContent = message.content.map((item: any) => { | |
| 96 | + if (item.type === "text" && item.text) { | |
| 97 | + const tokens = estimateTokenCount(item.text); | |
| 98 | + if (tokens > 500) { | |
| 99 | + return { | |
| 100 | + ...item, | |
| 101 | + cache_control: { type: "ephemeral" }, | |
| 102 | + }; | |
| 103 | + } | |
| 104 | + } | |
| 105 | + return item; | |
| 106 | + }); | |
| 107 | + | |
| 108 | + return { | |
| 109 | + ...message, | |
| 110 | + content: updatedContent, | |
| 111 | + }; | |
| 112 | + } | |
| 113 | + return message; | |
| 114 | + }); | |
| 115 | + } | |
| 116 | + | |
| 117 | + return result; | |
| 118 | +}; | |
| 119 | + | |
| 120 | +// Available caching strategies | |
| 121 | +export const CACHING_STRATEGIES = { | |
| 122 | + none: noCachingStrategy, | |
| 123 | + systemOnly: systemOnlyStrategy, | |
| 124 | + systemAndTools: systemAndToolsStrategy, | |
| 125 | + optimized: optimizedStrategy, | |
| 126 | +} as const; | |
| 127 | + | |
| 128 | +export type CachingStrategyName = keyof typeof CACHING_STRATEGIES; | |
| 129 | + | |
| 130 | +// Helper function to get available strategies | |
| 131 | +export const getAvailableStrategies = () => { | |
| 132 | + return Object.keys(CACHING_STRATEGIES) as CachingStrategyName[]; | |
| 133 | +}; | |
| 134 | + | |
| 135 | +// Helper function to get strategy description | |
| 136 | +export const getStrategyDescription = ( | |
| 137 | + strategy: CachingStrategyName, | |
| 138 | +): string => { | |
| 139 | + const descriptions = { | |
| 140 | + none: "No caching - baseline for comparison", | |
| 141 | + systemOnly: "Cache only system messages (current implementation)", | |
| 142 | + systemAndTools: "Cache system messages and tool definitions (high impact)", | |
| 143 | + optimized: | |
| 144 | + "Intelligent caching - system, tools, and large content (best performance)", | |
| 145 | + }; | |
| 146 | + return descriptions[strategy]; | |
| 147 | +}; |
modified packages/openai-adapters/src/index.ts +1 −1
| @@ -60,7 +60,7 @@ | ||
| 60 | 60 | return new LlamastackApi(config); |
| 61 | 61 | case "continue-proxy": |
| 62 | 62 | return new ContinueProxyApi(config); |
| 63 | - case "x-ai": | |
| 63 | + case "xAI": | |
| 64 | 64 | return openAICompatible("https://api.x.ai/v1/", config); |
| 65 | 65 | case "voyage": |
| 66 | 66 | return openAICompatible("https://api.voyageai.com/v1/", config); |
added packages/openai-adapters/src/test/adapter-test-utils.ts +321 −0
| @@ -0,0 +1,321 @@ | ||
| 1 | +import { afterEach, describe, expect, test, vi } from "vitest"; | |
| 2 | +import { BaseLlmApi } from "../apis/base.js"; | |
| 3 | +import { LLMConfig } from "../types.js"; | |
| 4 | +import { constructLlmApi } from "../index.js"; | |
| 5 | + | |
| 6 | +interface AdapterTestCase { | |
| 7 | + config: LLMConfig; | |
| 8 | + methodToTest: keyof BaseLlmApi; | |
| 9 | + params: any[]; | |
| 10 | + expectedRequest: { | |
| 11 | + url: string; | |
| 12 | + method: string; | |
| 13 | + headers?: Record<string, string>; | |
| 14 | + body?: Record<string, any>; | |
| 15 | + }; | |
| 16 | + mockResponse?: any; | |
| 17 | + mockStream?: any[]; | |
| 18 | +} | |
| 19 | + | |
| 20 | +function createMockStream(mockStream: any[]) { | |
| 21 | + const encoder = new TextEncoder(); | |
| 22 | + return new ReadableStream({ | |
| 23 | + start(controller) { | |
| 24 | + for (const chunk of mockStream) { | |
| 25 | + controller.enqueue( | |
| 26 | + encoder.encode( | |
| 27 | + `data: ${ | |
| 28 | + typeof chunk === "string" ? chunk : JSON.stringify(chunk) | |
| 29 | + }\n\n`, | |
| 30 | + ), | |
| 31 | + ); | |
| 32 | + } | |
| 33 | + controller.close(); | |
| 34 | + }, | |
| 35 | + }); | |
| 36 | +} | |
| 37 | + | |
| 38 | +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { | |
| 39 | + const mockFetch = vi.fn(); | |
| 40 | + | |
| 41 | + if (mockStream) { | |
| 42 | + const stream = createMockStream(mockStream); | |
| 43 | + mockFetch.mockResolvedValue( | |
| 44 | + new Response(stream, { | |
| 45 | + headers: { | |
| 46 | + "Content-Type": "text/event-stream", | |
| 47 | + }, | |
| 48 | + }), | |
| 49 | + ); | |
| 50 | + } else { | |
| 51 | + mockFetch.mockResolvedValue( | |
| 52 | + new Response(JSON.stringify(mockResponse), { | |
| 53 | + headers: { "Content-Type": "application/json" }, | |
| 54 | + }), | |
| 55 | + ); | |
| 56 | + } | |
| 57 | + | |
| 58 | + return mockFetch; | |
| 59 | +} | |
| 60 | + | |
| 61 | +function setupReadableStreamPolyfill() { | |
| 62 | + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved | |
| 63 | + // @ts-ignore | |
| 64 | + const originalFrom = ReadableStream.from; | |
| 65 | + // @ts-ignore | |
| 66 | + ReadableStream.from = (body) => { | |
| 67 | + if (body?.source) { | |
| 68 | + return body; | |
| 69 | + } | |
| 70 | + return originalFrom(body); | |
| 71 | + }; | |
| 72 | +} | |
| 73 | + | |
| 74 | +async function executeAdapterMethod( | |
| 75 | + api: BaseLlmApi, | |
| 76 | + methodToTest: keyof BaseLlmApi, | |
| 77 | + params: any[], | |
| 78 | +) { | |
| 79 | + if (typeof (api as any)[methodToTest] !== "function") { | |
| 80 | + throw new Error( | |
| 81 | + `Method ${String(methodToTest)} does not exist on the adapter instance.`, | |
| 82 | + ); | |
| 83 | + } | |
| 84 | + | |
| 85 | + const result = await (api as any)[methodToTest](...params); | |
| 86 | + | |
| 87 | + // If it's a generator/async iterator, consume it to trigger the HTTP request | |
| 88 | + if (result?.next) { | |
| 89 | + for await (const _ of result) { | |
| 90 | + // Just consume the generator to trigger the request | |
| 91 | + } | |
| 92 | + } | |
| 93 | +} | |
| 94 | + | |
| 95 | +function assertFetchCall(mockFetch: any, expectedRequest: any) { | |
| 96 | + expect(mockFetch).toHaveBeenCalledTimes(1); | |
| 97 | + const [url, options] = mockFetch.mock.calls[0]; | |
| 98 | + | |
| 99 | + expect(url.toString()).toBe(expectedRequest.url); | |
| 100 | + expect(options.method).toBe(expectedRequest.method); | |
| 101 | + | |
| 102 | + if (expectedRequest.headers) { | |
| 103 | + expect(options.headers).toEqual( | |
| 104 | + expect.objectContaining(expectedRequest.headers), | |
| 105 | + ); | |
| 106 | + } | |
| 107 | + | |
| 108 | + if (expectedRequest.body) { | |
| 109 | + const actualBody = JSON.parse(options.body as string); | |
| 110 | + expect(actualBody).toEqual(expectedRequest.body); | |
| 111 | + } | |
| 112 | +} | |
| 113 | + | |
| 114 | +export async function runAdapterTest(testCase: AdapterTestCase) { | |
| 115 | + const { | |
| 116 | + config, | |
| 117 | + methodToTest, | |
| 118 | + params, | |
| 119 | + expectedRequest, | |
| 120 | + mockResponse, | |
| 121 | + mockStream, | |
| 122 | + } = testCase; | |
| 123 | + | |
| 124 | + const mockFetch = setupMockFetch(mockResponse, mockStream); | |
| 125 | + setupReadableStreamPolyfill(); | |
| 126 | + | |
| 127 | + // Mock fetch globally before constructing the API | |
| 128 | + vi.stubGlobal("fetch", mockFetch); | |
| 129 | + | |
| 130 | + // For non-OpenAI adapters, mock the fetch package | |
| 131 | + const fetchPackage = await import("@continuedev/fetch"); | |
| 132 | + if (fetchPackage.fetchwithRequestOptions) { | |
| 133 | + vi.mocked(fetchPackage.fetchwithRequestOptions).mockImplementation( | |
| 134 | + mockFetch as any, | |
| 135 | + ); | |
| 136 | + } | |
| 137 | + | |
| 138 | + const api = constructLlmApi(config); | |
| 139 | + if (!api) { | |
| 140 | + throw new Error(`Failed to construct API for provider: ${config.provider}`); | |
| 141 | + } | |
| 142 | + | |
| 143 | + // For OpenAI adapters, we need to replace the fetch on the OpenAI client | |
| 144 | + if ((api as any).openai) { | |
| 145 | + (api as any).openai.fetch = mockFetch; | |
| 146 | + } | |
| 147 | + | |
| 148 | + await executeAdapterMethod(api, methodToTest, params); | |
| 149 | + assertFetchCall(mockFetch, expectedRequest); | |
| 150 | +} | |
| 151 | + | |
| 152 | +export interface AdapterTestConfig { | |
| 153 | + providerName: string; | |
| 154 | + config: LLMConfig; | |
| 155 | + expectedApiBase: string; | |
| 156 | + customHeaders?: Record<string, string>; | |
| 157 | + customBodyOptions?: any; | |
| 158 | +} | |
| 159 | + | |
| 160 | +export const createAdapterTests = (testConfig: AdapterTestConfig) => { | |
| 161 | + describe(testConfig.providerName, () => { | |
| 162 | + afterEach(() => { | |
| 163 | + vi.clearAllMocks(); | |
| 164 | + vi.unstubAllGlobals(); | |
| 165 | + }); | |
| 166 | + | |
| 167 | + test("should construct API correctly", () => { | |
| 168 | + const api = constructLlmApi(testConfig.config); | |
| 169 | + expect(api).toBeDefined(); | |
| 170 | + }); | |
| 171 | + | |
| 172 | + test("chatCompletionNonStream should send a valid request", async () => { | |
| 173 | + await runAdapterTest({ | |
| 174 | + config: testConfig.config, | |
| 175 | + methodToTest: "chatCompletionNonStream", | |
| 176 | + params: [ | |
| 177 | + { | |
| 178 | + model: "gpt-4", | |
| 179 | + messages: [{ role: "user", content: "hello" }], | |
| 180 | + }, | |
| 181 | + new AbortController().signal, | |
| 182 | + ], | |
| 183 | + expectedRequest: { | |
| 184 | + url: `${testConfig.expectedApiBase}chat/completions`, | |
| 185 | + method: "POST", | |
| 186 | + headers: { | |
| 187 | + ...testConfig.customHeaders, | |
| 188 | + }, | |
| 189 | + body: { | |
| 190 | + model: "gpt-4", | |
| 191 | + messages: [{ role: "user", content: "hello" }], | |
| 192 | + ...testConfig.customBodyOptions, | |
| 193 | + }, | |
| 194 | + }, | |
| 195 | + mockResponse: { | |
| 196 | + id: "test-id", | |
| 197 | + object: "chat.completion", | |
| 198 | + created: 1234567890, | |
| 199 | + model: "gpt-4", | |
| 200 | + choices: [ | |
| 201 | + { | |
| 202 | + index: 0, | |
| 203 | + message: { | |
| 204 | + role: "assistant", | |
| 205 | + content: "Hello! How can I help you today?", | |
| 206 | + }, | |
| 207 | + finish_reason: "stop", | |
| 208 | + }, | |
| 209 | + ], | |
| 210 | + usage: { | |
| 211 | + prompt_tokens: 10, | |
| 212 | + completion_tokens: 15, | |
| 213 | + total_tokens: 25, | |
| 214 | + }, | |
| 215 | + }, | |
| 216 | + }); | |
| 217 | + }); | |
| 218 | + | |
| 219 | + test("chatCompletionStream should send a valid request", async () => { | |
| 220 | + await runAdapterTest({ | |
| 221 | + config: testConfig.config, | |
| 222 | + methodToTest: "chatCompletionStream", | |
| 223 | + params: [ | |
| 224 | + { | |
| 225 | + model: "gpt-4", | |
| 226 | + messages: [{ role: "user", content: "hello" }], | |
| 227 | + stream: true, | |
| 228 | + }, | |
| 229 | + new AbortController().signal, | |
| 230 | + ], | |
| 231 | + expectedRequest: { | |
| 232 | + url: `${testConfig.expectedApiBase}chat/completions`, | |
| 233 | + method: "POST", | |
| 234 | + headers: { | |
| 235 | + ...testConfig.customHeaders, | |
| 236 | + }, | |
| 237 | + body: { | |
| 238 | + model: "gpt-4", | |
| 239 | + messages: [{ role: "user", content: "hello" }], | |
| 240 | + stream: true, | |
| 241 | + ...testConfig.customBodyOptions, | |
| 242 | + }, | |
| 243 | + }, | |
| 244 | + mockStream: [ | |
| 245 | + { | |
| 246 | + id: "test-id", | |
| 247 | + object: "chat.completion.chunk", | |
| 248 | + created: 1234567890, | |
| 249 | + model: "gpt-4", | |
| 250 | + choices: [ | |
| 251 | + { | |
| 252 | + index: 0, | |
| 253 | + delta: { content: "Hello" }, | |
| 254 | + finish_reason: null, | |
| 255 | + }, | |
| 256 | + ], | |
| 257 | + }, | |
| 258 | + { | |
| 259 | + id: "test-id", | |
| 260 | + object: "chat.completion.chunk", | |
| 261 | + created: 1234567890, | |
| 262 | + model: "gpt-4", | |
| 263 | + choices: [ | |
| 264 | + { | |
| 265 | + index: 0, | |
| 266 | + delta: { content: " world" }, | |
| 267 | + finish_reason: null, | |
| 268 | + }, | |
| 269 | + ], | |
| 270 | + }, | |
| 271 | + ], | |
| 272 | + }); | |
| 273 | + }); | |
| 274 | + | |
| 275 | + test("embed should send a valid request", async () => { | |
| 276 | + await runAdapterTest({ | |
| 277 | + config: testConfig.config, | |
| 278 | + methodToTest: "embed", | |
| 279 | + params: [ | |
| 280 | + { | |
| 281 | + model: "text-embedding-ada-002", | |
| 282 | + input: ["Hello", "World"], | |
| 283 | + }, | |
| 284 | + ], | |
| 285 | + expectedRequest: { | |
| 286 | + url: `${testConfig.expectedApiBase}embeddings`, | |
| 287 | + method: "POST", | |
| 288 | + headers: { | |
| 289 | + ...testConfig.customHeaders, | |
| 290 | + }, | |
| 291 | + body: { | |
| 292 | + model: "text-embedding-ada-002", | |
| 293 | + input: ["Hello", "World"], | |
| 294 | + encoding_format: "base64", | |
| 295 | + ...testConfig.customBodyOptions, | |
| 296 | + }, | |
| 297 | + }, | |
| 298 | + mockResponse: { | |
| 299 | + object: "list", | |
| 300 | + data: [ | |
| 301 | + { | |
| 302 | + object: "embedding", | |
| 303 | + embedding: [0.1, 0.2, 0.3], | |
| 304 | + index: 0, | |
| 305 | + }, | |
| 306 | + { | |
| 307 | + object: "embedding", | |
| 308 | + embedding: [0.4, 0.5, 0.6], | |
| 309 | + index: 1, | |
| 310 | + }, | |
| 311 | + ], | |
| 312 | + model: "text-embedding-ada-002", | |
| 313 | + usage: { | |
| 314 | + prompt_tokens: 6, | |
| 315 | + total_tokens: 6, | |
| 316 | + }, | |
| 317 | + }, | |
| 318 | + }); | |
| 319 | + }); | |
| 320 | + }); | |
| 321 | +}; |
added packages/openai-adapters/src/test/anthropic-adapter.vitest.ts +201 −0
| @@ -0,0 +1,201 @@ | ||
| 1 | +import { describe, test, vi, expect, afterEach } from "vitest"; | |
| 2 | +import { runAdapterTest } from "./adapter-test-utils.js"; | |
| 3 | + | |
| 4 | +// Mock the fetch package | |
| 5 | +vi.mock("@continuedev/fetch", async () => { | |
| 6 | + const actual = await vi.importActual("@continuedev/fetch"); | |
| 7 | + return { | |
| 8 | + ...actual, | |
| 9 | + fetchwithRequestOptions: vi.fn(), | |
| 10 | + }; | |
| 11 | +}); | |
| 12 | + | |
| 13 | +describe("Anthropic Adapter Tests", () => { | |
| 14 | + afterEach(() => { | |
| 15 | + vi.clearAllMocks(); | |
| 16 | + vi.unstubAllGlobals(); | |
| 17 | + }); | |
| 18 | + | |
| 19 | + test("should construct API correctly", async () => { | |
| 20 | + const { constructLlmApi } = await import("../index.js"); | |
| 21 | + const api = constructLlmApi({ | |
| 22 | + provider: "anthropic", | |
| 23 | + apiKey: "test-api-key", | |
| 24 | + }); | |
| 25 | + expect(api).toBeDefined(); | |
| 26 | + }); | |
| 27 | + | |
| 28 | + test("chatCompletionNonStream should send a valid request", async () => { | |
| 29 | + await runAdapterTest({ | |
| 30 | + config: { | |
| 31 | + provider: "anthropic", | |
| 32 | + apiKey: "test-api-key", | |
| 33 | + apiBase: "https://api.anthropic.com/v1/", | |
| 34 | + }, | |
| 35 | + methodToTest: "chatCompletionNonStream", | |
| 36 | + params: [ | |
| 37 | + { | |
| 38 | + model: "claude-3-5-sonnet-20241022", | |
| 39 | + messages: [{ role: "user", content: "hello" }], | |
| 40 | + }, | |
| 41 | + new AbortController().signal, | |
| 42 | + ], | |
| 43 | + expectedRequest: { | |
| 44 | + url: "https://api.anthropic.com/v1/messages", | |
| 45 | + method: "POST", | |
| 46 | + headers: { | |
| 47 | + "Content-Type": "application/json", | |
| 48 | + Accept: "application/json", | |
| 49 | + "anthropic-version": "2023-06-01", | |
| 50 | + "x-api-key": "test-api-key", | |
| 51 | + }, | |
| 52 | + body: { | |
| 53 | + messages: [{ role: "user", content: "hello" }], | |
| 54 | + system: undefined, | |
| 55 | + model: "claude-3-5-sonnet-20241022", | |
| 56 | + max_tokens: 4096, | |
| 57 | + stream: undefined, | |
| 58 | + }, | |
| 59 | + }, | |
| 60 | + mockResponse: { | |
| 61 | + id: "msg_test", | |
| 62 | + type: "message", | |
| 63 | + role: "assistant", | |
| 64 | + content: [ | |
| 65 | + { | |
| 66 | + type: "text", | |
| 67 | + text: "Hello! How can I help you today?", | |
| 68 | + }, | |
| 69 | + ], | |
| 70 | + model: "claude-3-5-sonnet-20241022", | |
| 71 | + stop_reason: "end_turn", | |
| 72 | + stop_sequence: null, | |
| 73 | + usage: { | |
| 74 | + input_tokens: 10, | |
| 75 | + output_tokens: 15, | |
| 76 | + }, | |
| 77 | + }, | |
| 78 | + }); | |
| 79 | + }); | |
| 80 | + | |
| 81 | + test("chatCompletionStream should send a valid request", async () => { | |
| 82 | + await runAdapterTest({ | |
| 83 | + config: { | |
| 84 | + provider: "anthropic", | |
| 85 | + apiKey: "test-api-key", | |
| 86 | + apiBase: "https://api.anthropic.com/v1/", | |
| 87 | + }, | |
| 88 | + methodToTest: "chatCompletionStream", | |
| 89 | + params: [ | |
| 90 | + { | |
| 91 | + model: "claude-3-5-sonnet-20241022", | |
| 92 | + messages: [{ role: "user", content: "hello" }], | |
| 93 | + stream: true, | |
| 94 | + }, | |
| 95 | + new AbortController().signal, | |
| 96 | + ], | |
| 97 | + expectedRequest: { | |
| 98 | + url: "https://api.anthropic.com/v1/messages", | |
| 99 | + method: "POST", | |
| 100 | + headers: { | |
| 101 | + "Content-Type": "application/json", | |
| 102 | + Accept: "application/json", | |
| 103 | + "anthropic-version": "2023-06-01", | |
| 104 | + "x-api-key": "test-api-key", | |
| 105 | + }, | |
| 106 | + body: { | |
| 107 | + messages: [{ role: "user", content: "hello" }], | |
| 108 | + system: undefined, | |
| 109 | + model: "claude-3-5-sonnet-20241022", | |
| 110 | + max_tokens: 4096, | |
| 111 | + stream: true, | |
| 112 | + }, | |
| 113 | + }, | |
| 114 | + mockStream: [ | |
| 115 | + { | |
| 116 | + type: "content_block_delta", | |
| 117 | + delta: { | |
| 118 | + type: "text_delta", | |
| 119 | + text: "Hello", | |
| 120 | + }, | |
| 121 | + }, | |
| 122 | + { | |
| 123 | + type: "content_block_delta", | |
| 124 | + delta: { | |
| 125 | + type: "text_delta", | |
| 126 | + text: " world", | |
| 127 | + }, | |
| 128 | + }, | |
| 129 | + ], | |
| 130 | + }); | |
| 131 | + }); | |
| 132 | + | |
| 133 | + test("chatCompletionStream with system message should convert correctly", async () => { | |
| 134 | + await runAdapterTest({ | |
| 135 | + config: { | |
| 136 | + provider: "anthropic", | |
| 137 | + apiKey: "test-api-key", | |
| 138 | + apiBase: "https://api.anthropic.com/v1/", | |
| 139 | + }, | |
| 140 | + methodToTest: "chatCompletionStream", | |
| 141 | + params: [ | |
| 142 | + { | |
| 143 | + model: "claude-3-5-sonnet-20241022", | |
| 144 | + messages: [ | |
| 145 | + { role: "system", content: "You are a helpful assistant." }, | |
| 146 | + { role: "user", content: "hello" }, | |
| 147 | + ], | |
| 148 | + stream: true, | |
| 149 | + }, | |
| 150 | + new AbortController().signal, | |
| 151 | + ], | |
| 152 | + expectedRequest: { | |
| 153 | + url: "https://api.anthropic.com/v1/messages", | |
| 154 | + method: "POST", | |
| 155 | + headers: { | |
| 156 | + "Content-Type": "application/json", | |
| 157 | + Accept: "application/json", | |
| 158 | + "anthropic-version": "2023-06-01", | |
| 159 | + "x-api-key": "test-api-key", | |
| 160 | + }, | |
| 161 | + body: { | |
| 162 | + messages: [{ role: "user", content: "hello" }], | |
| 163 | + system: [ | |
| 164 | + { | |
| 165 | + type: "text", | |
| 166 | + text: "You are a helpful assistant.", | |
| 167 | + cache_control: { type: "ephemeral" }, | |
| 168 | + }, | |
| 169 | + ], | |
| 170 | + model: "claude-3-5-sonnet-20241022", | |
| 171 | + max_tokens: 4096, | |
| 172 | + stream: true, | |
| 173 | + }, | |
| 174 | + }, | |
| 175 | + mockStream: [ | |
| 176 | + { | |
| 177 | + type: "content_block_delta", | |
| 178 | + delta: { | |
| 179 | + type: "text_delta", | |
| 180 | + text: "Hello", | |
| 181 | + }, | |
| 182 | + }, | |
| 183 | + ], | |
| 184 | + }); | |
| 185 | + }); | |
| 186 | + | |
| 187 | + test("embed should throw not implemented error", async () => { | |
| 188 | + const { constructLlmApi } = await import("../index.js"); | |
| 189 | + const api = constructLlmApi({ | |
| 190 | + provider: "anthropic", | |
| 191 | + apiKey: "test-api-key", | |
| 192 | + }); | |
| 193 | + | |
| 194 | + await expect( | |
| 195 | + api!.embed({ | |
| 196 | + model: "text-embedding-ada-002", | |
| 197 | + input: ["Hello", "World"], | |
| 198 | + }), | |
| 199 | + ).rejects.toThrow("Method not implemented."); | |
| 200 | + }); | |
| 201 | +}); |
modified packages/openai-adapters/src/test/main.test.ts +36 −29
| @@ -4,12 +4,13 @@ | ||
| 4 | 4 | import { INCEPTION_API_BASE } from "../apis/Inception.js"; |
| 5 | 5 | import { OpenAIApi } from "../apis/OpenAI.js"; |
| 6 | 6 | import { constructLlmApi } from "../index.js"; |
| 7 | -import { getLlmApi, testChat, testEmbed } from "./util.js"; | |
| 7 | +import { getLlmApi, testChat, testEmbed, testFim, testRerank } from "./util.js"; | |
| 8 | 8 | |
| 9 | 9 | dotenv.config(); |
| 10 | 10 | |
| 11 | 11 | export interface TestConfigOptions { |
| 12 | 12 | skipTools: boolean; |
| 13 | + expectUsage?: boolean; | |
| 13 | 14 | } |
| 14 | 15 | |
| 15 | 16 | function testConfig(_config: ModelConfig & { options?: TestConfigOptions }) { |
| @@ -34,8 +35,12 @@ | ||
| 34 | 35 | testEmbed(api, model); |
| 35 | 36 | } |
| 36 | 37 | |
| 37 | - if (config.roles?.includes("embed")) { | |
| 38 | - testEmbed(api, model); | |
| 38 | + if (config.roles?.includes("rerank")) { | |
| 39 | + testRerank(api, model); | |
| 40 | + } | |
| 41 | + | |
| 42 | + if (config.roles?.includes("autocomplete")) { | |
| 43 | + testFim(api, model); | |
| 39 | 44 | } |
| 40 | 45 | } |
| 41 | 46 | |
| @@ -51,6 +56,10 @@ | ||
| 51 | 56 | model: "claude-3-5-haiku-latest", |
| 52 | 57 | apiKey: process.env.ANTHROPIC_API_KEY!, |
| 53 | 58 | roles: ["chat"], |
| 59 | + options: { | |
| 60 | + skipTools: false, | |
| 61 | + expectUsage: true, | |
| 62 | + }, | |
| 54 | 63 | }, |
| 55 | 64 | { |
| 56 | 65 | provider: "gemini", |
| @@ -58,19 +67,19 @@ | ||
| 58 | 67 | apiKey: process.env.GEMINI_API_KEY!, |
| 59 | 68 | roles: ["chat"], |
| 60 | 69 | }, |
| 61 | - { | |
| 62 | - provider: "mistral", | |
| 63 | - model: "codestral-latest", | |
| 64 | - apiKey: process.env.MISTRAL_API_KEY!, | |
| 65 | - apiBase: "https://api.mistral.ai/v1", | |
| 66 | - roles: ["autocomplete"], | |
| 67 | - }, | |
| 68 | - { | |
| 69 | - provider: "deepseek", | |
| 70 | - model: "deepseek-coder", | |
| 71 | - apiKey: process.env.DEEPSEEK_API_KEY!, | |
| 72 | - roles: ["autocomplete"], | |
| 73 | - }, | |
| 70 | + // { | |
| 71 | + // provider: "mistral", | |
| 72 | + // model: "codestral-latest", | |
| 73 | + // apiKey: process.env.MISTRAL_API_KEY!, | |
| 74 | + // apiBase: "https://api.mistral.ai/v1", | |
| 75 | + // roles: ["autocomplete"], | |
| 76 | + // }, | |
| 77 | + // { | |
| 78 | + // provider: "deepseek", | |
| 79 | + // model: "deepseek-coder", | |
| 80 | + // apiKey: process.env.DEEPSEEK_API_KEY!, | |
| 81 | + // roles: ["autocomplete"], | |
| 82 | + // }, | |
| 74 | 83 | { |
| 75 | 84 | provider: "openai", |
| 76 | 85 | model: "text-embedding-3-small", |
| @@ -112,28 +121,26 @@ | ||
| 112 | 121 | model: "gpt-4.1", |
| 113 | 122 | apiBase: "https://continue-openai.openai.azure.com", |
| 114 | 123 | apiKey: process.env.AZURE_OPENAI_GPT41_API_KEY, |
| 124 | + roles: ["chat"], | |
| 115 | 125 | env: { |
| 116 | 126 | deployment: "gpt-4.1", |
| 117 | 127 | apiVersion: "2024-02-15-preview", |
| 118 | 128 | apiType: "azure-openai", |
| 119 | 129 | }, |
| 120 | - roles: ["chat"], | |
| 121 | - }, | |
| 122 | - { | |
| 123 | - provider: "azure", | |
| 124 | - model: "mistral-small-2503", | |
| 125 | - apiBase: "https://nate-0276-resource.services.ai.azure.com/models", | |
| 126 | - apiKey: process.env.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY, | |
| 127 | - roles: ["chat"], | |
| 128 | - options: { skipTools: true }, | |
| 129 | 130 | }, |
| 130 | 131 | ]; |
| 131 | 132 | |
| 132 | -TESTS.forEach((config) => { | |
| 133 | - describe(`${config.provider}/${config.model}`, () => { | |
| 134 | - testConfig({ name: config.model, ...config }); | |
| 133 | +if (process.env.IGNORE_API_KEY_TESTS === "true") { | |
| 134 | + test("Skipping API key tests", () => { | |
| 135 | + console.log("Skipping API key tests due to IGNORE_API_KEY_TESTS being set"); | |
| 135 | 136 | }); |
| 136 | -}); | |
| 137 | +} else { | |
| 138 | + TESTS.forEach((config) => { | |
| 139 | + describe(`${config.provider}/${config.model}`, () => { | |
| 140 | + testConfig({ name: config.model, ...config }); | |
| 141 | + }); | |
| 142 | + }); | |
| 143 | +} | |
| 137 | 144 | |
| 138 | 145 | describe("Configuration", () => { |
| 139 | 146 | it("should configure DeepSeek OpenAI client with correct apiBase and apiKey", () => { |
added packages/openai-adapters/src/test/openai-adapter.vitest.ts +28 −0
| @@ -0,0 +1,28 @@ | ||
| 1 | +import { describe, vi } from "vitest"; | |
| 2 | +import { createAdapterTests } from "./adapter-test-utils.js"; | |
| 3 | + | |
| 4 | +// Mock the fetch package (not needed for OpenAI but required by the shared test utils) | |
| 5 | +vi.mock("@continuedev/fetch", async () => { | |
| 6 | + const actual = await vi.importActual("@continuedev/fetch"); | |
| 7 | + return { | |
| 8 | + ...actual, | |
| 9 | + fetchwithRequestOptions: vi.fn(), | |
| 10 | + }; | |
| 11 | +}); | |
| 12 | + | |
| 13 | +describe("OpenAI Adapter Tests", () => { | |
| 14 | + createAdapterTests({ | |
| 15 | + providerName: "openai", | |
| 16 | + config: { | |
| 17 | + provider: "openai", | |
| 18 | + apiKey: "test-api-key", | |
| 19 | + apiBase: "https://api.openai.com/v1/", | |
| 20 | + }, | |
| 21 | + expectedApiBase: "https://api.openai.com/v1/", | |
| 22 | + customHeaders: { | |
| 23 | + authorization: "Bearer test-api-key", | |
| 24 | + "content-type": "application/json", | |
| 25 | + accept: "application/json", | |
| 26 | + }, | |
| 27 | + }); | |
| 28 | +}); |
modified packages/openai-adapters/src/test/util.ts +31 −3
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { CompletionUsage } from "openai/resources/completions.mjs"; | |
| 1 | 2 | import { BaseLlmApi, constructLlmApi } from "../index.js"; |
| 2 | 3 | import { LLMConfig } from "../types.js"; |
| 3 | 4 | import { TestConfigOptions } from "./main.test.js"; |
| @@ -88,12 +89,27 @@ | ||
| 88 | 89 | new AbortController().signal, |
| 89 | 90 | ); |
| 90 | 91 | let completion = ""; |
| 92 | + let usage: CompletionUsage | undefined = undefined; | |
| 91 | 93 | for await (const result of stream) { |
| 92 | - completion += result.choices[0].delta.content ?? ""; | |
| 93 | - | |
| 94 | - expect(result.choices.length).toBeGreaterThan(0); | |
| 94 | + completion += result.choices[0]?.delta.content ?? ""; | |
| 95 | + | |
| 96 | + if (result.usage) { | |
| 97 | + usage = result.usage; | |
| 98 | + } else { | |
| 99 | + // At the end we expect a final message without choices that shares usage | |
| 100 | + expect(result.choices.length).toBeGreaterThan(0); | |
| 101 | + } | |
| 95 | 102 | } |
| 96 | 103 | expect(completion.length).toBeGreaterThan(0); |
| 104 | + | |
| 105 | + if (options?.expectUsage === true) { | |
| 106 | + expect(usage).toBeDefined(); | |
| 107 | + expect(usage!.completion_tokens).toBeGreaterThan(0); | |
| 108 | + expect(usage!.prompt_tokens).toBeGreaterThan(0); | |
| 109 | + expect(usage!.total_tokens).toEqual( | |
| 110 | + usage!.prompt_tokens + usage!.completion_tokens, | |
| 111 | + ); | |
| 112 | + } | |
| 97 | 113 | }); |
| 98 | 114 | |
| 99 | 115 | test("should successfully stream multi-part chat with empty text", async () => { |
| @@ -122,6 +138,10 @@ | ||
| 122 | 138 | ); |
| 123 | 139 | let completion = ""; |
| 124 | 140 | for await (const result of stream) { |
| 141 | + // Skip usage chunks that have empty choices array | |
| 142 | + if (result.choices.length === 0) { | |
| 143 | + continue; | |
| 144 | + } | |
| 125 | 145 | completion += result.choices[0].delta.content ?? ""; |
| 126 | 146 | |
| 127 | 147 | expect(result.choices.length).toBeGreaterThan(0); |
| @@ -246,6 +266,10 @@ | ||
| 246 | 266 | }, |
| 247 | 267 | new AbortController().signal, |
| 248 | 268 | )) { |
| 269 | + // Skip usage chunks that have empty choices array | |
| 270 | + if (chunk.choices.length === 0) { | |
| 271 | + continue; | |
| 272 | + } | |
| 249 | 273 | const toolCall = chunk.choices[0].delta.tool_calls?.[0]; |
| 250 | 274 | if (!toolCall) { |
| 251 | 275 | continue; |
| @@ -317,6 +341,10 @@ | ||
| 317 | 341 | }, |
| 318 | 342 | new AbortController().signal, |
| 319 | 343 | )) { |
| 344 | + // Skip usage chunks that have empty choices array | |
| 345 | + if (chunk.choices.length === 0) { | |
| 346 | + continue; | |
| 347 | + } | |
| 320 | 348 | response += chunk.choices[0].delta.content ?? ""; |
| 321 | 349 | } |
| 322 | 350 |
modified packages/openai-adapters/src/types.ts +1 −1
| @@ -53,7 +53,7 @@ | ||
| 53 | 53 | z.literal("sambanova"), |
| 54 | 54 | z.literal("text-gen-webui"), |
| 55 | 55 | z.literal("vllm"), |
| 56 | - z.literal("x-ai"), | |
| 56 | + z.literal("xAI"), | |
| 57 | 57 | z.literal("scaleway"), |
| 58 | 58 | z.literal("ncompass"), |
| 59 | 59 | z.literal("relace"), |
modified packages/openai-adapters/src/util.ts +15 −0
| @@ -38,6 +38,21 @@ | ||
| 38 | 38 | }; |
| 39 | 39 | } |
| 40 | 40 | |
| 41 | +export function usageChatChunk(options: { | |
| 42 | + model: string; | |
| 43 | + id?: string | null; | |
| 44 | + usage?: CompletionUsage; | |
| 45 | +}): ChatCompletionChunk { | |
| 46 | + return { | |
| 47 | + choices: [], | |
| 48 | + usage: options.usage, | |
| 49 | + created: Date.now(), | |
| 50 | + id: options.id ?? "", | |
| 51 | + model: options.model, | |
| 52 | + object: "chat.completion.chunk", | |
| 53 | + }; | |
| 54 | +} | |
| 55 | + | |
| 41 | 56 | export function chatChunkFromDelta(options: { |
| 42 | 57 | delta: ChatCompletionChunk.Choice["delta"]; |
| 43 | 58 | model: string; |
added packages/openai-adapters/vitest.config.ts +15 −0
| @@ -0,0 +1,15 @@ | ||
| 1 | +import { defineConfig } from "vitest/config"; | |
| 2 | + | |
| 3 | +export default defineConfig({ | |
| 4 | + test: { | |
| 5 | + environment: "node", | |
| 6 | + globals: true, | |
| 7 | + testTimeout: 10000, | |
| 8 | + include: ["src/**/*.test.{ts,tsx}", "src/**/*.vitest.{ts,tsx}"], | |
| 9 | + }, | |
| 10 | + resolve: { | |
| 11 | + alias: { | |
| 12 | + "(.+)\\.js": "$1", | |
| 13 | + }, | |
| 14 | + }, | |
| 15 | +}); |
modified packages/shared-release.config.js +1 −7
| @@ -21,13 +21,7 @@ | ||
| 21 | 21 | "@semantic-release/release-notes-generator", |
| 22 | 22 | "@semantic-release/changelog", |
| 23 | 23 | "@semantic-release/npm", |
| 24 | - [ | |
| 25 | - "@semantic-release/git", | |
| 26 | - { | |
| 27 | - assets: ["CHANGELOG.md", "package.json"], | |
| 28 | - message: `chore(release): @continuedev/${packageName}@\${nextRelease.version} [skip ci]`, | |
| 29 | - }, | |
| 30 | - ], | |
| 24 | + // Removed @semantic-release/git plugin to avoid pushing to main | |
| 31 | 25 | "@semantic-release/github", |
| 32 | 26 | ], |
| 33 | 27 | }; |