Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⬆️ Upgrade AI SDK #1641

Merged
merged 3 commits into from
Jul 15, 2024
Merged

⬆️ Upgrade AI SDK #1641

merged 3 commits into from
Jul 15, 2024

Conversation

baptisteArno
Copy link
Owner

No description provided.

Copy link

vercel bot commented Jul 15, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
builder-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 15, 2024 0:31am
landing-page-v2 🛑 Canceled (Inspect) Jul 15, 2024 0:31am
viewer-v2 🔄 Building (Inspect) Visit Preview 💬 Add feedback Jul 15, 2024 0:31am

Copy link

coderabbitai bot commented Jul 15, 2024

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes encompass several updates across multiple files and modules. Key updates include renaming components, introducing new functions and constants, updating import statements, and enhancing function parameters and configurations. Notable additions are related to AI module functions, tool parsing, and constants for various models and APIs. Additionally, there are semantic changes in several functions and enhancements in the parsing and handling of data streams.

Changes

Files Change Summary
apps/builder/src/components/icons.tsx Renamed WebhookIcon component to ThunderIcon.
apps/builder/src/features/blocks/integrations/webhook/components/... Updated import statement to use ThunderIcon instead of WebhookIcon.
apps/builder/src/features/editor/components/BlockIcon.tsx Replaced WebhookIcon with ThunderIcon.
apps/builder/src/features/forge/components/ForgedBlockNodeContent.tsx Updated ForgedBlockNodeContent component to include a new indices prop.
apps/builder/src/features/forge/components/zodLayouts/ZodFieldLayout.tsx Refactored enumeration item parsing logic and modified parseEnumItems function signature.
packages/ai/parseChatCompletionMessages.ts Introduced parseChatCompletionMessages function with enhanced parameters and dependencies.
packages/ai/parseTools.ts Introduced parseTools function for tool management in an AI context.
packages/ai/schemas.ts Introduced schemas for defining tool parameters and functions within a toolset.
packages/ai/splitUserTextMessageIntoBlocks.ts Introduced splitUserTextMessageIntoBlocks function for processing user text messages.
packages/embeds/js/rollup.config.js Imported commonjs from @rollup/plugin-commonjs and added it as a plugin.
packages/embeds/js/src/features/blocks/integrations/openai/streamChat.ts Updated import statement for readDataStream.
packages/forge/blocks/anthropic/actions/createChatMessage.tsx Significant semantic alterations.
packages/forge/blocks/anthropic/constants.ts Introduced new constants related to anthropic models.
packages/forge/blocks/anthropic/helpers/isModelCompatibleWithVision.ts Introduced isModelCompatibleWithVision function.
packages/forge/blocks/anthropic/helpers/runChatCompletionStream.ts Handled running a chat completion stream with various options and tools.
packages/forge/blocks/elevenlabs/actions/convertTextToSpeech.ts Removed defaultValue field from createAction configuration object.
packages/forge/blocks/mistral/actions/createChatCompletion.ts Added imports, schemas, and functions related to tools and chat completion messages.
packages/forge/blocks/mistral/constants.ts Added a new constant maxToolRoundtrips.
packages/forge/blocks/mistral/helpers/runChatCompletionStream.ts Handled running a chat completion stream using Mistral API.
packages/forge/blocks/openRouter/actions/createChatCompletion.tsx Updated functions for running chat completions and set default temperature.
packages/forge/blocks/openRouter/constants.ts Added a new temperature field to defaultOpenRouterOptions.
packages/forge/blocks/openai/actions/askAssistant.tsx Renamed functions and updated imports related to assistant streams.
packages/forge/blocks/openai/actions/createChatCompletion.tsx Updated functions for running chat completions and added new options.
packages/forge/blocks/openai/helpers/AssistantStream.ts Renamed AssistantStream to AssistantStreamType and introduced a new function.
packages/forge/blocks/openai/helpers/splitUserTextMessageIntoOpenAIBlocks.ts Renamed splitUserTextMessageIntoBlocks to splitUserTextMessageIntoOpenAIBlocks.
packages/forge/blocks/openai/shared/parseChatCompletionOptions.ts Significant changes to the parseChatCompletionOptions function.
packages/forge/blocks/openai/shared/parseGenerateVariablesOptions.ts Removed defaultValue property from layout function calls.
packages/forge/blocks/openai/shared/runOpenAIChatCompletion.ts Introduced runOpenAIChatCompletion function with necessary configurations.
packages/forge/blocks/openai/shared/runOpenAIChatCompletionStream.ts Introduced runOpenAIChatCompletionStream function for streaming text generation using OpenAI's API.
packages/forge/blocks/togetherAi/actions/createChatCompletion.tsx Renamed functions related to running chat completions and added default temperature setting.
packages/forge/blocks/togetherAi/constants.ts Added a new temperature property to defaultTogetherOptions constant object.
packages/forge/core/zod/extendWithTypebotLayout.ts Added a new property toLabels of type `(val?: string) => string

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@baptisteArno
Copy link
Owner Author

@coderabbitai review

Copy link

coderabbitai bot commented Jul 15, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 9

Outside diff range, codebase verification and nitpick comments (1)
packages/ai/parseChatCompletionMessages.ts (1)

12-19: Ensure proper typing for function parameters.

The function parameters are well-defined, but consider using TypeScript interfaces or types for better maintainability and readability.

interface Message {
  role: 'Dialogue' | 'user' | 'assistant' | 'system';
  startsBy?: 'user' | 'assistant';
  dialogueVariableId?: string;
  content?: string;
}

interface Props {
  messages: Message[] | undefined;
  isVisionEnabled: boolean;
  shouldDownloadImages: boolean;
  variables: VariableStore;
  toolCalls?: ToolCallPart[];
  toolResults?: ToolResultPart[];
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a4fb8b6 and 515dc69.

Files ignored due to path filters (12)
  • apps/builder/public/templates/openai-assistant-chat.json is excluded by !**/*.json
  • apps/docs/openapi/builder.json is excluded by !**/*.json
  • apps/docs/openapi/viewer.json is excluded by !**/*.json
  • apps/viewer/package.json is excluded by !**/*.json
  • packages/ai/package.json is excluded by !**/*.json
  • packages/bot-engine/package.json is excluded by !**/*.json
  • packages/embeds/js/package.json is excluded by !**/*.json
  • packages/forge/blocks/anthropic/package.json is excluded by !**/*.json
  • packages/forge/blocks/difyAi/package.json is excluded by !**/*.json
  • packages/forge/blocks/mistral/package.json is excluded by !**/*.json
  • packages/forge/blocks/openai/package.json is excluded by !**/*.json
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !**/*.yaml
Files selected for processing (34)
  • apps/builder/src/components/icons.tsx (1 hunks)
  • apps/builder/src/features/blocks/integrations/webhook/components/HttpRequestIcon.tsx (1 hunks)
  • apps/builder/src/features/editor/components/BlockIcon.tsx (2 hunks)
  • apps/builder/src/features/forge/components/ForgedBlockNodeContent.tsx (2 hunks)
  • apps/builder/src/features/forge/components/zodLayouts/ZodFieldLayout.tsx (2 hunks)
  • apps/builder/src/features/graph/components/nodes/block/BlockNodeContent.tsx (1 hunks)
  • apps/builder/src/features/preview/components/WebPreview.tsx (2 hunks)
  • packages/ai/parseChatCompletionMessages.ts (1 hunks)
  • packages/ai/parseTools.ts (1 hunks)
  • packages/ai/schemas.ts (1 hunks)
  • packages/ai/splitUserTextMessageIntoBlocks.ts (1 hunks)
  • packages/embeds/js/rollup.config.js (2 hunks)
  • packages/embeds/js/src/features/blocks/integrations/openai/streamChat.ts (1 hunks)
  • packages/forge/blocks/anthropic/actions/createChatMessage.tsx (6 hunks)
  • packages/forge/blocks/anthropic/constants.ts (3 hunks)
  • packages/forge/blocks/anthropic/helpers/isModelCompatibleWithVision.ts (1 hunks)
  • packages/forge/blocks/anthropic/helpers/runChatCompletionStream.ts (1 hunks)
  • packages/forge/blocks/elevenlabs/actions/convertTextToSpeech.ts (1 hunks)
  • packages/forge/blocks/mistral/actions/createChatCompletion.ts (5 hunks)
  • packages/forge/blocks/mistral/constants.ts (1 hunks)
  • packages/forge/blocks/mistral/helpers/runChatCompletionStream.ts (1 hunks)
  • packages/forge/blocks/openRouter/actions/createChatCompletion.tsx (4 hunks)
  • packages/forge/blocks/openRouter/constants.ts (1 hunks)
  • packages/forge/blocks/openai/actions/askAssistant.tsx (2 hunks)
  • packages/forge/blocks/openai/actions/createChatCompletion.tsx (3 hunks)
  • packages/forge/blocks/openai/helpers/AssistantStream.ts (4 hunks)
  • packages/forge/blocks/openai/helpers/splitUserTextMessageIntoOpenAIBlocks.ts (1 hunks)
  • packages/forge/blocks/openai/shared/parseChatCompletionOptions.ts (4 hunks)
  • packages/forge/blocks/openai/shared/parseGenerateVariablesOptions.ts (1 hunks)
  • packages/forge/blocks/openai/shared/runOpenAIChatCompletion.ts (1 hunks)
  • packages/forge/blocks/openai/shared/runOpenAIChatCompletionStream.ts (1 hunks)
  • packages/forge/blocks/togetherAi/actions/createChatCompletion.tsx (4 hunks)
  • packages/forge/blocks/togetherAi/constants.ts (1 hunks)
  • packages/forge/core/zod/extendWithTypebotLayout.ts (1 hunks)
Files skipped from review due to trivial changes (7)
  • apps/builder/src/features/blocks/integrations/webhook/components/HttpRequestIcon.tsx
  • apps/builder/src/features/editor/components/BlockIcon.tsx
  • packages/forge/blocks/elevenlabs/actions/convertTextToSpeech.ts
  • packages/forge/blocks/mistral/constants.ts
  • packages/forge/blocks/openRouter/constants.ts
  • packages/forge/blocks/openai/helpers/splitUserTextMessageIntoOpenAIBlocks.ts
  • packages/forge/blocks/togetherAi/constants.ts
Additional context used
Biome
packages/ai/parseTools.ts

[error] 21-21: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

Additional comments not posted (45)
packages/forge/blocks/anthropic/helpers/isModelCompatibleWithVision.ts (1)

1-5: LGTM!

The function isModelCompatibleWithVision is correctly implemented.

packages/forge/blocks/anthropic/constants.ts (7)

Line range hint 1-7:
LGTM!

The anthropicModels constant is correctly defined.


11-15: LGTM!

The anthropicLegacyModels constant is correctly defined.


17-25: LGTM!

The anthropicModelLabels constant is correctly defined.


27-30: LGTM!

The defaultAnthropicOptions constant is correctly defined.


Line range hint 32-32:
LGTM!

The modelsWithImageUrlSupport constant is correctly defined.


Line range hint 34-38:
LGTM!

The supportedImageTypes constant is correctly defined.


42-42: LGTM!

The maxToolCalls constant is correctly defined.

packages/forge/core/zod/extendWithTypebotLayout.ts (2)

Line range hint 6-27:
LGTM!

The ZodLayoutMetadata type definition is correctly implemented.


Line range hint 31-45:
LGTM!

The extendWithTypebotLayout function is correctly implemented.

packages/embeds/js/rollup.config.js (1)

10-10: Approved: Addition of commonjs plugin.

The addition of the commonjs plugin is a good practice to ensure compatibility with CommonJS modules.

packages/forge/blocks/togetherAi/actions/createChatCompletion.tsx (4)

6-7: Approved: Addition of runOpenAIChatCompletionStream.

The addition of runOpenAIChatCompletionStream enhances the functionality by enabling chat completion streams.


16-16: Approved: Use of defaultTogetherOptions.temperature.

Setting the default temperature value from defaultTogetherOptions ensures consistency in configuration.


42-42: Approved: Use of runOpenAIChatCompletion with default base URL.

The use of runOpenAIChatCompletion with the default base URL from defaultTogetherOptions is appropriate.


48-53: Approved: Configuration for runOpenAIChatCompletionStream.

The configuration for runOpenAIChatCompletionStream is correctly set up with the default base URL.

apps/builder/src/features/preview/components/WebPreview.tsx (1)

1-1: Approved: Use of ThunderIcon in handleNewLogs.

The use of ThunderIcon in the handleNewLogs function is consistent with the recent renaming of the icon.

Also applies to: 21-21

packages/forge/blocks/openRouter/actions/createChatCompletion.tsx (4)

6-7: Approved: Addition of runOpenAIChatCompletionStream.

The addition of runOpenAIChatCompletionStream enhances the functionality by enabling chat completion streams.


38-38: Approved: Use of defaultOpenRouterOptions.temperature.

Setting the default temperature value from defaultOpenRouterOptions ensures consistency in configuration.


59-59: Approved: Use of runOpenAIChatCompletion with default base URL.

The use of runOpenAIChatCompletion with the default base URL from defaultOpenRouterOptions is appropriate.


65-70: Approved: Configuration for runOpenAIChatCompletionStream.

The configuration for runOpenAIChatCompletionStream is correctly set up with the default base URL.

packages/ai/schemas.ts (3)

4-17: LGTM!

The parameterBase schema is well-defined and includes appropriate layout configurations.


19-51: LGTM!

The toolParametersSchema is comprehensive and well-structured, ensuring type safety through the use of discriminated unions.


52-77: LGTM!

The toolsSchema is well-defined and includes comprehensive layout configurations for each property.

packages/forge/blocks/openai/shared/parseChatCompletionOptions.ts (2)

4-4: LGTM!

The import statement for toolsSchema is correct and necessary for the subsequent usage.


Line range hint 45-75:
LGTM!

The Props type and the parseChatCompletionOptions function are well-defined and include comprehensive layout configurations for each option.

packages/ai/parseTools.ts (1)

39-70: LGTM!

The parseParameters function is well-defined and handles different parameter types correctly.

packages/forge/blocks/openai/actions/createChatCompletion.tsx (1)

Line range hint 7-74:
LGTM!

The createChatCompletion action is well-defined and includes comprehensive configurations. The addition of the runOpenAIChatCompletionStream function is appropriate and follows the existing pattern.

packages/forge/blocks/openai/shared/parseGenerateVariablesOptions.ts (1)

Line range hint 2-2:
Ensure the new import is necessary.

The new import statement for readDataStream from @ai-sdk/ui-utils should be verified to ensure it is used within the file.

packages/embeds/js/src/features/blocks/integrations/openai/streamChat.ts (1)

2-2: Ensure the new import is necessary.

The new import statement for readDataStream from @ai-sdk/ui-utils should be verified to ensure it is used within the file.

packages/forge/blocks/openai/shared/runOpenAIChatCompletion.ts (1)

1-1: Ensure the new import is necessary.

The new import statement for maxToolCalls from ../constants should be verified to ensure it is used within the file.

apps/builder/src/features/forge/components/ForgedBlockNodeContent.tsx (1)

3-3: Ensure the new import is necessary.

The new import statement for ThunderIcon from @/components/icons should be verified to ensure it is used within the file.

packages/forge/blocks/mistral/helpers/runChatCompletionStream.ts (1)

22-35: Ensure proper error handling for missing API key and model.

The function correctly handles missing API keys and models, returning appropriate HTTP errors. Ensure that these checks are comprehensive and cover all edge cases.

packages/forge/blocks/anthropic/helpers/runChatCompletionStream.ts (1)

23-36: Ensure proper error handling for missing API key and model.

The function correctly handles missing API keys and models, returning appropriate HTTP errors. Ensure that these checks are comprehensive and cover all edge cases.

packages/forge/blocks/mistral/actions/createChatCompletion.ts (2)

67-67: Ensure proper schema validation for tools.

The tools option uses a schema for validation. Ensure that the schema is comprehensive and covers all necessary validations.


144-149: Ensure proper handling of streaming operations.

The streaming operations are handled correctly, but consider breaking down the logic into smaller helper functions for better readability and maintainability.

packages/forge/blocks/openai/shared/runOpenAIChatCompletionStream.ts (2)

10-18: LGTM! The type definition is well-structured.

The Props type is well-defined and includes all necessary fields.


20-131: Ensure proper error handling and stream management.

The function runOpenAIChatCompletionStream is well-structured and includes comprehensive error handling and stream management. However, consider the following suggestions:

  1. Error Logging: Add logging for errors to facilitate debugging.
  2. Stream Management: Ensure that the stream is properly closed in all scenarios, including error cases.
packages/forge/blocks/openai/helpers/AssistantStream.ts (1)

Line range hint 1-153:
Ensure proper error handling and stream management.

The function AssistantStream is well-structured and includes comprehensive stream management and error handling. However, consider the following suggestions:

  1. Error Logging: Add logging for errors to facilitate debugging.
  2. Stream Management: Ensure that the stream is properly closed in all scenarios, including error cases.
packages/forge/blocks/anthropic/actions/createChatMessage.tsx (2)

53-57: LGTM! The schema definition is well-structured.

The options schema is well-defined and includes all necessary fields.


126-162: Ensure proper error handling and stream management.

The function createChatMessage is well-structured and includes comprehensive error handling and stream management. However, consider the following suggestions:

  1. Error Logging: Add logging for errors to facilitate debugging.
  2. Stream Management: Ensure that the stream is properly closed in all scenarios, including error cases.
Verification successful

Error handling and stream management are properly implemented.

The createChatMessage function in both anthropic and difyAi implementations already includes comprehensive error handling and stream management. No further changes are required.

  • packages/forge/blocks/anthropic/actions/createChatMessage.tsx
  • packages/forge/blocks/difyAi/actions/createChatMessage.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the function usage and error handling.

# Test: Search for the function usage. Expect: Proper error handling and stream management.
rg --type python -A 5 $'createChatMessage'

Length of output: 72


Script:

#!/bin/bash
# Description: Verify the function usage and error handling.

# Test: Search for the function usage. Expect: Proper error handling and stream management.
rg --type tsx -A 5 $'createChatMessage'

Length of output: 66


Script:

#!/bin/bash
# Description: Verify the function usage and error handling.

# Test: Search for the function usage. Expect: Proper error handling and stream management.
rg --type ts -A 5 $'createChatMessage'

Length of output: 2189


Script:

#!/bin/bash
# Extract the implementation of createChatMessage from both files for verification.

# Extract from anthropic/actions/createChatMessage.tsx
ast-grep --lang tsx --pattern $'export const createChatMessage = createAction({
  $$$
})' packages/forge/blocks/anthropic/actions/createChatMessage.tsx

# Extract from difyAi/actions/createChatMessage.ts
ast-grep --lang ts --pattern $'export const createChatMessage = createAction({
  $$$
})' packages/forge/blocks/difyAi/actions/createChatMessage.ts

Length of output: 32022

apps/builder/src/features/graph/components/nodes/block/BlockNodeContent.tsx (1)

158-158: LGTM! The component changes are well-structured.

The BlockNodeContent component is well-structured and includes comprehensive handling of different block types. The indices prop is correctly passed to the ForgedBlockNodeContent component.

packages/forge/blocks/openai/actions/askAssistant.tsx (2)

14-16: Ensure new imports are necessary and correctly used.

The new imports AssistantStream, isModelCompatibleWithVision, and splitUserTextMessageIntoOpenAIBlocks should be reviewed to ensure they are necessary and correctly used in the new functionality.


297-306: Verify the correctness and integration of new functionality.

The new conditional block using isModelCompatibleWithVision and splitUserTextMessageIntoOpenAIBlocks should be verified for correctness and proper integration with the existing code.

apps/builder/src/features/forge/components/zodLayouts/ZodFieldLayout.tsx (1)

33-46: Verify the correctness and integration of new property toLabels.

The new property toLabels in the parseEnumItems function should be verified for correctness and proper integration with the existing code.

apps/builder/src/components/icons.tsx (1)

300-302: Verify the correctness and integration of new icon component ThunderIcon.

The new icon component ThunderIcon should be verified for correctness and proper integration with the existing code.

packages/ai/splitUserTextMessageIntoBlocks.ts Show resolved Hide resolved
packages/ai/parseTools.ts Outdated Show resolved Hide resolved
packages/ai/parseChatCompletionMessages.ts Outdated Show resolved Hide resolved
Comment on lines 106 to 118
if (toolCalls && toolCalls.length > 0) {
parsedMessages.push({
role: 'assistant',
content: toolCalls,
})
}

if (toolResults && toolResults.length > 0) {
parsedMessages.push({
role: 'tool',
content: toolResults,
})
}
Copy link

Choose a reason for hiding this comment

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

Consider separating tool calls and results handling.

The logic for handling tool calls and results is mixed with the main message parsing logic. Consider separating this into a different function or section for better readability and maintainability.

const handleToolCallsAndResults = (parsedMessages, toolCalls, toolResults) => {
  if (toolCalls && toolCalls.length > 0) {
    parsedMessages.push({ role: 'assistant', content: toolCalls });
  }

  if (toolResults && toolResults.length > 0) {
    parsedMessages.push({ role: 'tool', content: toolResults });
  }

  return parsedMessages;
};

Comment on lines 41 to 56
try {
const response = await streamText({
model,
temperature: options.temperature
? Number(options.temperature)
: undefined,
messages: await parseChatCompletionMessages({
messages: options.messages,
isVisionEnabled: false,
shouldDownloadImages: false,
variables,
toolCalls,
toolResults,
}),
tools: parseTools({ tools: options.tools, variables }),
})
Copy link

Choose a reason for hiding this comment

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

Optimize model creation and message parsing logic.

The model creation and message parsing logic are intertwined. Consider breaking down the logic into smaller helper functions for better readability and maintainability.

const createModel = (apiKey, modelName) => {
  return createMistral({ apiKey })(modelName);
};

const parseMessagesAndTools = async (options, variables, toolCalls, toolResults) => {
  const messages = await parseChatCompletionMessages({
    messages: options.messages,
    isVisionEnabled: false,
    shouldDownloadImages: false,
    variables,
    toolCalls,
    toolResults,
  });

  const tools = parseTools({ tools: options.tools, variables });

  return { messages, tools };
};

Comment on lines 42 to 57
try {
const response = await streamText({
model,
temperature: options.temperature
? Number(options.temperature)
: undefined,
messages: await parseChatCompletionMessages({
messages: options.messages,
isVisionEnabled: isModelCompatibleWithVision(modelName),
shouldDownloadImages: false,
variables,
toolCalls,
toolResults,
}),
tools: parseTools({ tools: options.tools, variables }),
})
Copy link

Choose a reason for hiding this comment

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

Optimize model creation and message parsing logic.

The model creation and message parsing logic are intertwined. Consider breaking down the logic into smaller helper functions for better readability and maintainability.

const createModel = (apiKey, modelName) => {
  return createAnthropic({ apiKey })(modelName);
};

const parseMessagesAndTools = async (options, variables, toolCalls, toolResults) => {
  const messages = await parseChatCompletionMessages({
    messages: options.messages,
    isVisionEnabled: isModelCompatibleWithVision(modelName),
    shouldDownloadImages: false,
    variables,
    toolCalls,
    toolResults,
  });

  const tools = parseTools({ tools: options.tools, variables });

  return { messages, tools };
};

Comment on lines 58 to 103

let totalToolCalls = 0

return {
stream: new ReadableStream({
async start(controller) {
const reader = response.toAIStream().getReader()

async function pump(reader: ReadableStreamDefaultReader<Uint8Array>) {
const { done, value } = await reader.read()

if (done) {
toolCalls = (await response.toolCalls) as ToolCallPart[]
toolResults = (await response.toolResults) as
| ToolResultPart[]
| undefined
return
}

controller.enqueue(value)
return pump(reader)
}

await pump(reader)

if (
toolCalls &&
toolCalls.length > 0 &&
totalToolCalls < maxToolCalls
) {
totalToolCalls += 1
const streamResponse = await runChatCompletionStream({
credentials: { apiKey },
options,
variables,
toolCalls,
toolResults,
})
if (!streamResponse.stream)
throw new APICallError({
message: streamResponse.httpError?.message ?? 'Unknown error',
statusCode: streamResponse.httpError?.status,
url: '',
requestBodyValues: {},
})
await pump(streamResponse.stream.getReader())
Copy link

Choose a reason for hiding this comment

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

Improve readability and maintainability of stream handling logic.

The stream handling logic is complex and involves nested async operations and recursive calls. Consider breaking down the logic into smaller helper functions for better readability and maintainability.

const handleStream = async (response, controller, toolCalls, toolResults, totalToolCalls, maxToolCalls, apiKey, options, variables) => {
  const reader = response.toAIStream().getReader();

  const pump = async (reader) => {
    const { done, value } = await reader.read();
    if (done) {
      toolCalls = (await response.toolCalls) as ToolCallPart[];
      toolResults = (await response.toolResults) as ToolResultPart[] | undefined;
      return;
    }
    controller.enqueue(value);
    return pump(reader);
  };

  await pump(reader);

  if (toolCalls && toolCalls.length > 0 && totalToolCalls < maxToolCalls) {
    totalToolCalls += 1;
    const streamResponse = await runChatCompletionStream({
      credentials: { apiKey },
      options,
      variables,
      toolCalls,
      toolResults,
    });
    if (!streamResponse.stream) throw new APICallError({
      message: streamResponse.httpError?.message ?? 'Unknown error',
      statusCode: streamResponse.httpError?.status,
      url: '',
      requestBodyValues: {},
    });
    await pump(streamResponse.stream.getReader());
  }

  controller.close();
};

Comment on lines +123 to +130
messages: await parseChatCompletionMessages({
messages: options.messages,
variables,
isVisionEnabled: false,
shouldDownloadImages: false,
}),
tools: parseTools({ tools: options.tools, variables }),
maxToolRoundtrips: maxToolRoundtrips,
Copy link

Choose a reason for hiding this comment

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

Optimize message parsing and tool handling logic.

The message parsing and tool handling logic are intertwined. Consider breaking down the logic into smaller helper functions for better readability and maintainability.

const parseMessagesAndTools = async (options, variables) => {
  const messages = await parseChatCompletionMessages({
    messages: options.messages,
    variables,
    isVisionEnabled: false,
    shouldDownloadImages: false,
  });

  const tools = parseTools({ tools: options.tools, variables });

  return { messages, tools };
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant