Skip to content
This repository has been archived by the owner on Mar 6, 2024. It is now read-only.

Added support for Azure bot #519

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

PycKamil
Copy link

@PycKamil PycKamil commented Feb 13, 2024

What:
Added langchain package that is used in AzureBot for communicating with Azure API. Based on provided configuration AzureBot will be used as Bot.

Why:
This fixes issue #382. Enable to use coderabbitai with Azure API.

Summary by CodeRabbit

  • New Features

    • Introduced an AzureBot class for integrating with Azure services and OpenAI chat model.
    • Added new interfaces for bot communication and protocol standardization.
    • Enhanced application configuration to support Azure API parameters.
  • Refactor

    • Updated the Bot class to implement the new BotProtocol interface.
    • Refactored code to use BotProtocol in place of direct Bot references, improving flexibility and maintainability.

Summary by CodeRabbit

  • New Feature: Added support for Azure bot. Users can now configure the bot to use Azure API by specifying the instance name, deployment name, and version.
  • Refactor: Introduced BotProtocol interface to improve flexibility and maintainability. The code can now handle different types of bots, not just the original Bot.
  • Chore: Updated dependencies in the package.json file and added the skipLibCheck option to the TypeScript configuration file for better development experience.

Copy link
Contributor

github-actions bot commented Feb 13, 2024

Image description CodeRabbit

Walkthrough

This update introduces support for Azure bot using the langchain package, enhancing flexibility and maintainability. It includes new configurations for Azure API instance, deployment, and version. The code now uses the BotProtocol interface instead of the Bot class, allowing both AzureBot and Bot to be used interchangeably.

Changes

Files Summary
action.yml, package.json, tsconfig.json Added @langchain/openai package and updated dependencies. Introduced skipLibCheck option in TypeScript configuration.
src/azure-bot.ts, src/bot-interface.ts, src/bot.ts, src/main.ts, src/options.ts Implemented AzureBot class and BotProtocol interface. Modified run function to create AzureBot instances under certain conditions. Added new options for Azure API configuration.
src/review-comment.ts, src/review.ts Replaced Bot class with BotProtocol interface in import statements and function signatures. Updated handleReviewComment function to accept heavyBot parameter of type BotProtocol.

"With a hop and a skip, we've made quite the trip, 🐇💨
From Bot to Protocol, oh what a spectacle! 👏🎩
Azure's in sight, shining so bright, ☁️✨
Our code's taken flight, thanks to this update's might!" 🚀🌙


Uplevel your code reviews with CodeRabbit Pro

CodeRabbit Pro

If you like this project, please support us by purchasing the Pro version. The Pro version has advanced context, superior noise reduction and several proprietary improvements compared to the open source version. Moreover, CodeRabbit Pro is free for open source projects.

Copy link

coderabbitaidev bot commented Feb 13, 2024

Warning

CodeRabbit GitHub Action Detected

The repository is using both CodeRabbit Pro and CodeRabbit Open Source (via GitHub Actions), which is not recommended as it may lead to duplicate comments and extra noise. Please remove the CodeRabbit GitHub Action.

Walkthrough

The recent update introduces the AzureBot class, integrating Azure services with an OpenAI chat model, and refines the bot interaction framework by segregating interfaces to a new file and updating dependencies across the board. This revamp enhances flexibility in bot instantiation, especially with Azure deployments, and streamlines the bot communication protocol for improved interaction and response handling.

Changes

Files Change Summaries
src/azure-bot.ts Introduces AzureBot class for Azure/OpenAI chat model integration.
src/bot-interface.ts Adds interfaces for Ids and BotProtocol, including a chat method.
src/bot.ts, src/review*.ts Implements BotProtocol interface; references to Bot updated to BotProtocol.
src/main.ts, src/options.ts Adds Azure API configuration options and conditional AzureBot instantiation.

"In the digital meadow, under the cloud's gaze,
🐇 A new bot hops forth, through the cybernetic maze.
Azure skies above, with OpenAI's might,
It chats, it learns, in the soft server light.
Code and bytes, in harmony blend,
A tale of updates, where innovation ascends."
🌟🌿🖥️🌿🌟


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-tests for this file.
  • 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 tests 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 from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

@coderabbitaidev coderabbitaidev bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between d5ec397 and 9857827.
Files ignored due to path filters (8)
  • action.yml is excluded by: !**/*.yml
  • dist/37.index.js is excluded by: !dist/**
  • dist/73.index.js is excluded by: !dist/**
  • dist/index.js is excluded by: !dist/**
  • dist/licenses.txt is excluded by: !dist/**
  • package-lock.json is excluded by: !**/*.json
  • package.json is excluded by: !**/*.json
  • tsconfig.json is excluded by: !**/*.json
Files selected for processing (7)
  • src/azure-bot.ts (1 hunks)
  • src/bot-interface.ts (1 hunks)
  • src/bot.ts (1 hunks)
  • src/main.ts (3 hunks)
  • src/options.ts (4 hunks)
  • src/review-comment.ts (2 hunks)
  • src/review.ts (2 hunks)
Additional comments: 6
src/bot-interface.ts (1)
  • 1-10: LGTM!
src/bot.ts (1)
  • 10-18: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [13-109]

LGTM!

src/main.ts (1)
  • 48-86: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [8-109]

LGTM!

src/options.ts (1)
  • 43-52: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [25-98]

LGTM!

src/review-comment.ts (1)
  • 23-23: LGTM!
src/review.ts (1)
  • 28-29: The change to use BotProtocol for lightBot and heavyBot parameters aligns with the objective to generalize bot handling. Ensure all instances where lightBot and heavyBot are used are compatible with the BotProtocol interface.

src/review.ts Outdated Show resolved Hide resolved
src/azure-bot.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between d5ec397 and 9857827 commits.
Files selected (11)
  • action.yml (1)
  • package-lock.json (93)
  • package.json (1)
  • src/azure-bot.ts (1)
  • src/bot-interface.ts (1)
  • src/bot.ts (1)
  • src/main.ts (3)
  • src/options.ts (4)
  • src/review-comment.ts (2)
  • src/review.ts (2)
  • tsconfig.json (1)
Files ignored due to filter (4)
  • dist/37.index.js
  • dist/73.index.js
  • dist/index.js
  • dist/licenses.txt
Files not summarized due to errors (1)
  • package-lock.json (diff tokens exceeds limit)
Files skipped from review due to trivial changes (2)
  • src/bot-interface.ts
  • tsconfig.json
Review comments generated (19)
  • Review: 10
  • LGTM: 9

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

src/review-comment.ts Outdated Show resolved Hide resolved
src/bot.ts Show resolved Hide resolved
action.yml Outdated Show resolved Hide resolved
src/azure-bot.ts Outdated Show resolved Hide resolved
Comment on lines +15 to +19
"@langchain/openai": "^0.0.14",
"@octokit/action": "^6.0.4",
"@octokit/plugin-retry": "^4.1.3",
"@octokit/plugin-throttling": "^6.1.0",
"langchain": "^0.1.17",
Copy link
Contributor

Choose a reason for hiding this comment

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

Image description CodeRabbit

The langchain package has been added as a dependency. Ensure that this package is actively maintained and does not have any known security vulnerabilities. Also, make sure it's compatible with the other packages in your project.

+        "@langchain/openai": "^0.0.14",
+        "langchain": "^0.1.17",

Comment on lines +203 to +348
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"node_modules/@anthropic-ai/sdk/node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/@babel/code-frame": {
"version": "7.18.6",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz",
"integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==",
"version": "7.23.5",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz",
"integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==",
"dev": true,
"dependencies": {
"@babel/highlight": "^7.18.6"
"@babel/highlight": "^7.23.4",
"chalk": "^2.4.2"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/code-frame/node_modules/ansi-styles": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
"integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
"dev": true,
"dependencies": {
"color-convert": "^1.9.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/@babel/code-frame/node_modules/chalk": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
"integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
"dev": true,
"dependencies": {
"ansi-styles": "^3.2.1",
"escape-string-regexp": "^1.0.5",
"supports-color": "^5.3.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/@babel/code-frame/node_modules/color-convert": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
"dev": true,
"dependencies": {
"color-name": "1.1.3"
}
},
"node_modules/@babel/code-frame/node_modules/color-name": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
"dev": true
},
"node_modules/@babel/code-frame/node_modules/escape-string-regexp": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
"integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
"dev": true,
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/@babel/code-frame/node_modules/has-flag": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
"integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
"dev": true,
"engines": {
"node": ">=4"
}
},
"node_modules/@babel/code-frame/node_modules/supports-color": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
"integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
"dev": true,
"dependencies": {
"has-flag": "^3.0.0"
},
"engines": {
"node": ">=4"
}
},
Copy link
Contributor

Choose a reason for hiding this comment

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

Image description CodeRabbit

The @anthropic-ai/sdk package and its dependencies have been added. As with the previous comment, ensure that this package is actively maintained, does not have any known security vulnerabilities, and is compatible with the other packages in your project.

+    "node_modules/@anthropic-ai/sdk": {
+      "version": "0.9.1",
+      "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.9.1.tgz",
+      "integrity": "sha512-wa1meQ2WSfoY8Uor3EdrJq0jTiZJoKoSii2ZVWRY1oN4Tlr5s59pADg9T79FTbPe1/se5c3pBeZgJL63wmuoBA==",
+      "dependencies": {
+        "@types/node": "^18.11.18",
+        "@types/node-fetch": "^2.6.4",
+        "abort-controller": "^3.0.0",
+        "agentkeepalive": "^4.2.1",
+        "digest-fetch": "^1.3.0",
+        "form-data-encoder": "1.7.2",
+        "formdata-node": "^4.3.2",
+        "node-fetch": "^2.6.7",
+        "web-streams-polyfill": "^3.2.1"
+      }
+    },

Comment on lines +389 to 395
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Image description CodeRabbit

The version of semver has been updated from 6.3.0 to 6.3.1. This is a patch update, so it should not introduce any breaking changes. However, you should still test your application thoroughly after this update.

-      "version": "6.3.0",
+      "version": "6.3.1",

Comment on lines 397 to 402
"node_modules/@babel/generator": {
"version": "7.21.3",
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.21.3.tgz",
"integrity": "sha512-QS3iR1GYC/YGUnW7IdggFeN5c1poPUurnGttOV/bZgPGV+izC/D8HnD6DLwod0fsatNyVn1G3EVWMYIF0nHbeA==",
"version": "7.23.6",
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz",
"integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==",
"dev": true,
"dependencies": {
Copy link
Contributor

Choose a reason for hiding this comment

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

Image description CodeRabbit

The version of @babel/generator has been updated from 7.21.3 to 7.23.6. This is a minor version update, so while it should not introduce any breaking changes, it may add new features. Make sure to check the changelog for this package and test your application thoroughly.

-      "version": "7.21.3",
+      "version": "7.23.6",

src/main.ts Outdated Show resolved Hide resolved
Copy link

@coderabbitaidev coderabbitaidev bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 9857827 and 009189b.
Files ignored due to path filters (2)
  • action.yml is excluded by: !**/*.yml
  • dist/index.js is excluded by: !dist/**
Files selected for processing (4)
  • src/azure-bot.ts (1 hunks)
  • src/main.ts (3 hunks)
  • src/review-comment.ts (2 hunks)
  • src/review.ts (2 hunks)
Files skipped from review as they are similar to previous changes (4)
  • src/azure-bot.ts
  • src/main.ts
  • src/review-comment.ts
  • src/review.ts

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between 9857827 and 009189b commits.
Files selected (5)
  • action.yml (1)
  • src/azure-bot.ts (1)
  • src/main.ts (3)
  • src/review-comment.ts (2)
  • src/review.ts (2)
Files ignored due to filter (1)
  • dist/index.js
Review comments generated (13)
  • Review: 8
  • LGTM: 5

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

Comment on lines +28 to +29
lightBot: BotProtocol,
heavyBot: BotProtocol,
Copy link
Contributor

Choose a reason for hiding this comment

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

Image description CodeRabbit

Great job on replacing the specific Bot type with the more generic BotProtocol interface. This change enhances the flexibility of the code, allowing it to handle different types of bots that implement the BotProtocol interface.

action.yml Show resolved Hide resolved
src/main.ts Show resolved Hide resolved
src/main.ts Show resolved Hide resolved
src/azure-bot.ts Outdated Show resolved Hide resolved
src/azure-bot.ts Outdated Show resolved Hide resolved
src/azure-bot.ts Show resolved Hide resolved
Copy link

@coderabbitaidev coderabbitaidev bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 009189b and 002b20e.
Files selected for processing (1)
  • src/azure-bot.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/azure-bot.ts

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between 009189b and 002b20e commits.
Files selected (1)
  • src/azure-bot.ts (1)
Review comments generated (2)
  • Review: 2
  • LGTM: 0

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

Comment on lines +1 to +112
private readonly model: ChatOpenAI | null = null
private readonly api: ConversationChain | null = null

private readonly options: Options

constructor(options: Options, openaiOptions: OpenAIOptions) {
this.options = options
if (
process.env.AZURE_OPENAI_API_KEY &&
options.azureApiDeployment &&
options.apiBaseUrl &&
options.azureApiInstance
) {
const currentDate = new Date().toISOString().split('T')[0]
const systemMessage = `${options.systemMessage}
Knowledge cutoff: ${openaiOptions.tokenLimits.knowledgeCutOff}
Current date: ${currentDate}

IMPORTANT: Entire response must be in the language with ISO code: ${options.language}
`
const chatPrompt = ChatPromptTemplate.fromMessages([
['system', systemMessage],
new MessagesPlaceholder('history'),
['human', '{input}']
])

this.model = new ChatOpenAI({
temperature: options.openaiModelTemperature,
maxTokens: openaiOptions.tokenLimits.responseTokens,
azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,
azureOpenAIApiVersion: options.azureApiVersion,
azureOpenAIApiInstanceName: options.azureApiInstance,
azureOpenAIApiDeploymentName: options.azureApiDeployment,
timeout: this.options.openaiTimeoutMS,
maxRetries: this.options.openaiRetries
})
this.api = new ConversationChain({
memory: new BufferMemory({returnMessages: true, memoryKey: 'history'}),
prompt: chatPrompt,
llm: this.model
})
} else {
const err =
"Unable to initialize the OpenAI API, ensure 'AZURE_OPENAI_API_KEY', 'azureApiDeployment', 'apiBaseUrl', and 'azureApiInstance' are properly set"
throw new Error(err)
}
}

chat = async (message: string, ids: Ids): Promise<[string, Ids]> => {
let res: [string, Ids] = ['', ids]
try {
res = await this.chat_(message)
return res
} catch (e: unknown) {
warning(`Failed to chat: ${e}`)
return res
}
}

private readonly chat_ = async (message: string): Promise<[string, Ids]> => {
// record timing
const start = Date.now()
if (!message) {
return ['', {}]
}

let response: ChainValues | undefined

if (this.api != null) {
try {
response = await this.api.call({input: message})
} catch (e: unknown) {
info(`response: ${response}, failed to send message to openai: ${e}`)
}
const end = Date.now()
info(`response: ${JSON.stringify(response)}`)
info(
`openai sendMessage (including retries) response time: ${
end - start
} ms`
)
} else {
setFailed('The OpenAI API is not initialized')
}
let responseText = ''
if (response != null) {
responseText = response.response
} else {
warning('openai response is null')
}
// remove the prefix "with " in the response
if (responseText.startsWith('with ')) {
responseText = responseText.substring(5)
}
if (this.options.debug) {
info(`openai responses: ${responseText}`)
}
return [responseText, {}]
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Image description CodeRabbit

The AzureBot class seems to be well implemented. It checks for the necessary environment variables and options before initializing the OpenAI API and throws an error if they are not set. The chat method is designed to handle errors gracefully, logging a warning instead of throwing an exception when a chat fails. However, there's a potential issue with the error handling in the chat_ method.

Comment on lines +72 to +111
private readonly chat_ = async (message: string): Promise<[string, Ids]> => {
// record timing
const start = Date.now()
if (!message) {
return ['', {}]
}

let response: ChainValues | undefined

if (this.api != null) {
try {
response = await this.api.call({input: message})
} catch (e: unknown) {
info(`response: ${response}, failed to send message to openai: ${e}`)
}
const end = Date.now()
info(`response: ${JSON.stringify(response)}`)
info(
`openai sendMessage (including retries) response time: ${
end - start
} ms`
)
} else {
setFailed('The OpenAI API is not initialized')
}
let responseText = ''
if (response != null) {
responseText = response.response
} else {
warning('openai response is null')
}
// remove the prefix "with " in the response
if (responseText.startsWith('with ')) {
responseText = responseText.substring(5)
}
if (this.options.debug) {
info(`openai responses: ${responseText}`)
}
return [responseText, {}]
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Image description CodeRabbit

In the chat_ method, you're catching any exceptions that occur when calling the OpenAI API, but you're not rethrowing them or handling them in any other way. This means that if an error occurs, the function will continue executing as if nothing happened, which could lead to unexpected behavior.

Consider rethrowing the exception after logging it, or handling it in some other appropriate way. Here's an example of how you might modify the code:

  if (this.api != null) {
    try {
      response = await this.api.call({input: message})
    } catch (e: unknown) {
      info(`response: ${response}, failed to send message to openai: ${e}`)
+     throw e
    }
    const end = Date.now()
    info(`response: ${JSON.stringify(response)}`)
    info(
      `openai sendMessage (including retries) response time: ${
        end - start
      } ms`
    )
  } else {
    setFailed('The OpenAI API is not initialized')
  }

This way, if an error occurs when calling the OpenAI API, the error will be logged and then rethrown, causing the chat method to catch it and log a warning.

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

Successfully merging this pull request may close these issues.

2 participants