-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Add DeepseekAIClient implementation and integrate with LLMProvider #1242
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JerryWu1234
wants to merge
7
commits into
browserbase:main
Choose a base branch
from
JerryWu1234:deepseek
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+347
−14
Open
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
f0381b5
Add DeepseekAIClient implementation and integrate with LLMProvider
JerryWu1234 015f2a2
Add a new changeset for the DeepseekAIClient implementation and its i…
JerryWu1234 1db71b9
Update DeepseekAIClient to enhance JSON response instructions and imp…
JerryWu1234 a96ed27
Update LLMProvider to support manual mode and modify model provider m…
JerryWu1234 f8bca53
Enhance V3Evaluator and LLMProvider to support optional manual mode
JerryWu1234 52f24b2
format file
JerryWu1234 8adf546
Refactor V3 class for improved code clarity and consistency
JerryWu1234 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,307 @@ | ||
| import OpenAI, { ClientOptions } from "openai"; | ||
| import { | ||
| ChatCompletionAssistantMessageParam, | ||
| ChatCompletionContentPartImage, | ||
| ChatCompletionContentPartText, | ||
| ChatCompletionCreateParamsNonStreaming, | ||
| ChatCompletionMessageParam, | ||
| ChatCompletionSystemMessageParam, | ||
| ChatCompletionUserMessageParam, | ||
| } from "openai/resources/chat"; | ||
| import zodToJsonSchema from "zod-to-json-schema"; | ||
| import { LogLine } from "../types/public/logs"; | ||
| import { AvailableModel } from "../types/public/model"; | ||
| import { validateZodSchema } from "../../utils"; | ||
| import { | ||
| ChatCompletionOptions, | ||
| ChatMessage, | ||
| CreateChatCompletionOptions, | ||
| LLMClient, | ||
| LLMResponse, | ||
| } from "./LLMClient"; | ||
| import { | ||
| CreateChatCompletionResponseError, | ||
| ZodSchemaValidationError, | ||
| } from "../types/public/sdkErrors"; | ||
|
|
||
| export class DeepseekAIClient extends LLMClient { | ||
| public type = "deepseek" as const; | ||
| private client: OpenAI; | ||
| public clientOptions: ClientOptions; | ||
|
|
||
| constructor({ | ||
| modelName, | ||
| clientOptions, | ||
| }: { | ||
| logger: (message: LogLine) => void; | ||
| modelName: AvailableModel; | ||
| clientOptions?: ClientOptions; | ||
| }) { | ||
| super(modelName); | ||
| this.clientOptions = clientOptions; | ||
| this.client = new OpenAI({ | ||
| ...clientOptions, | ||
| baseURL: "https://api.deepseek.com/v1", | ||
| }); | ||
| this.modelName = modelName; | ||
| } | ||
|
|
||
| async createChatCompletion<T = LLMResponse>({ | ||
| options, | ||
| logger, | ||
| retries = 3, | ||
| }: CreateChatCompletionOptions): Promise<T> { | ||
| const { requestId, ...optionsWithoutImageAndRequestId } = options; | ||
|
|
||
| logger({ | ||
| category: "deepseek", | ||
| message: "creating chat completion", | ||
| level: 2, | ||
| auxiliary: { | ||
| options: { | ||
| value: JSON.stringify({ | ||
| ...optionsWithoutImageAndRequestId, | ||
| requestId, | ||
| }), | ||
| type: "object", | ||
| }, | ||
| modelName: { | ||
| value: this.modelName, | ||
| type: "string", | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| if (options.image) { | ||
| const screenshotMessage: ChatMessage = { | ||
| role: "user", | ||
| content: [ | ||
| { | ||
| type: "image_url", | ||
| image_url: { | ||
| url: `data:image/jpeg;base64,${options.image.buffer.toString( | ||
| "base64", | ||
| )}`, | ||
| }, | ||
| }, | ||
| ...(options.image.description | ||
| ? [{ type: "text", text: options.image.description }] | ||
| : []), | ||
| ], | ||
| }; | ||
|
|
||
| options.messages.push(screenshotMessage); | ||
| } | ||
|
|
||
| let responseFormat: { type: "json_object" } | undefined = undefined; | ||
| if (options.response_model) { | ||
| try { | ||
| const parsedSchema = JSON.stringify( | ||
| zodToJsonSchema(options.response_model.schema), | ||
| ); | ||
| options.messages.push({ | ||
| role: "user", | ||
| content: `Respond in this zod schema format:\n${parsedSchema}\n | ||
| You must respond in JSON format. Your response must include the word 'json'. Do not include any other text, formatting or markdown in your output. Do not include \`\`\` or \`\`\`json in your response. Only the JSON object itself.`, | ||
| }); | ||
| responseFormat = { type: "json_object" }; | ||
| } catch (error) { | ||
| logger({ | ||
| category: "deepseek", | ||
| message: "Failed to parse response model schema", | ||
| level: 0, | ||
| }); | ||
|
|
||
| if (retries > 0) { | ||
| return this.createChatCompletion({ | ||
| options: options as ChatCompletionOptions, | ||
| logger, | ||
| retries: retries - 1, | ||
| }); | ||
| } | ||
|
|
||
| throw error; | ||
| } | ||
| } | ||
|
|
||
| /* eslint-disable */ | ||
| const { response_model, ...deepseekOptions } = { | ||
| ...optionsWithoutImageAndRequestId, | ||
| model: this.modelName, | ||
| }; | ||
| /* eslint-enable */ | ||
|
|
||
| logger({ | ||
| category: "deepseek", | ||
| message: "creating chat completion", | ||
| level: 2, | ||
| auxiliary: { | ||
| deepseekOptions: { | ||
| value: JSON.stringify(deepseekOptions), | ||
| type: "object", | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| const formattedMessages: ChatCompletionMessageParam[] = | ||
| options.messages.map((message) => { | ||
| if (Array.isArray(message.content)) { | ||
| const contentParts = message.content.map((content) => { | ||
| if ("image_url" in content) { | ||
| const imageContent: ChatCompletionContentPartImage = { | ||
| image_url: { | ||
| url: content.image_url.url, | ||
| }, | ||
| type: "image_url", | ||
| }; | ||
| return imageContent; | ||
| } else { | ||
| const textContent: ChatCompletionContentPartText = { | ||
| text: content.text, | ||
| type: "text", | ||
| }; | ||
| return textContent; | ||
| } | ||
| }); | ||
|
|
||
| if (message.role === "system") { | ||
| const formattedMessage: ChatCompletionSystemMessageParam = { | ||
| ...message, | ||
| role: "system", | ||
| content: contentParts | ||
| .map((c) => (c.type === "text" ? c.text : "")) | ||
| .join("\n"), | ||
| }; | ||
| return formattedMessage; | ||
| } else if (message.role === "user") { | ||
| const formattedMessage: ChatCompletionUserMessageParam = { | ||
| ...message, | ||
| role: "user", | ||
| content: contentParts, | ||
| }; | ||
| return formattedMessage; | ||
| } else { | ||
| const formattedMessage: ChatCompletionAssistantMessageParam = { | ||
| ...message, | ||
| role: "assistant", | ||
| content: contentParts | ||
| .map((c) => (c.type === "text" ? c.text : "")) | ||
| .join("\n"), | ||
| }; | ||
| return formattedMessage; | ||
| } | ||
| } | ||
|
|
||
| const formattedMessage: ChatCompletionUserMessageParam = { | ||
| role: "user", | ||
| content: message.content, | ||
| }; | ||
|
|
||
| return formattedMessage; | ||
| }); | ||
|
|
||
| const modelNameToUse = this.modelName.startsWith("deepseek/") | ||
| ? this.modelName.split("/")[1] | ||
| : this.modelName; | ||
|
|
||
| const body: ChatCompletionCreateParamsNonStreaming = { | ||
| ...deepseekOptions, | ||
| model: modelNameToUse, | ||
| messages: formattedMessages, | ||
| response_format: responseFormat, | ||
| stream: false, | ||
| tools: options.tools?.map((tool) => ({ | ||
| function: { | ||
| name: tool.name, | ||
| description: tool.description, | ||
| parameters: tool.parameters, | ||
| }, | ||
| type: "function", | ||
| })), | ||
| }; | ||
|
|
||
| const response = await this.client.chat.completions.create(body); | ||
|
|
||
| logger({ | ||
| category: "deepseek", | ||
| message: "response", | ||
| level: 2, | ||
| auxiliary: { | ||
| response: { | ||
| value: JSON.stringify(response), | ||
| type: "object", | ||
| }, | ||
| requestId: { | ||
| value: requestId, | ||
| type: "string", | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| if (options.response_model) { | ||
| const extractedData = response.choices[0].message.content; | ||
JerryWu1234 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| if (extractedData === null) { | ||
| const errorMessage = "Response content is null."; | ||
| logger({ | ||
| category: "deepseek", | ||
| message: errorMessage, | ||
| level: 0, | ||
| }); | ||
| if (retries > 0) { | ||
| return this.createChatCompletion({ | ||
| options: options as ChatCompletionOptions, | ||
| logger, | ||
| retries: retries - 1, | ||
| }); | ||
| } | ||
| throw new CreateChatCompletionResponseError(errorMessage); | ||
| } | ||
|
|
||
| const parsedData = JSON.parse(extractedData); | ||
|
|
||
| try { | ||
| validateZodSchema(options.response_model.schema, parsedData); | ||
| } catch (e) { | ||
| logger({ | ||
| category: "deepseek", | ||
| message: "Response failed Zod schema validation", | ||
| level: 0, | ||
| }); | ||
| if (retries > 0) { | ||
| return this.createChatCompletion({ | ||
| options: options as ChatCompletionOptions, | ||
| logger, | ||
| retries: retries - 1, | ||
| }); | ||
| } | ||
|
|
||
| if (e instanceof ZodSchemaValidationError) { | ||
| logger({ | ||
| category: "deepseek", | ||
| message: `Error during Deepseek chat completion: ${e.message}`, | ||
| level: 0, | ||
| auxiliary: { | ||
| errorDetails: { | ||
| value: `Message: ${e.message}${ | ||
| e.stack ? "\nStack: " + e.stack : "" | ||
| }`, | ||
| type: "string", | ||
| }, | ||
| requestId: { value: requestId, type: "string" }, | ||
| }, | ||
| }); | ||
| throw new CreateChatCompletionResponseError(e.message); | ||
| } | ||
| throw e; | ||
| } | ||
|
|
||
| return { | ||
| data: parsedData, | ||
| usage: response.usage, | ||
| } as T; | ||
| } | ||
|
|
||
| return response as T; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.