Giter VIP home page Giter VIP logo

Comments (5)

dosubot avatar dosubot commented on August 16, 2024 2

Hey @kaiwinut! 👋 I'm here to help you with bug fixes, answer questions, and even guide you on becoming a contributor. If you need assistance, feel free to ask.

To resolve the issue with initializing ChatWebLLM due to the renaming of the Engine class to MLCEngine in the @mlc-ai/web-llm package, you need to update your code to use MLCEngine instead of Engine. Here is the updated code:

import { ChatWebLLM } from '@langchain/community/chat_models/webllm';
import * as webllm from "@mlc-ai/web-llm";

webllmModel = new ChatWebLLM({
    model: 'Phi2-q4f32_1',
    chatOptions: {
        temperature: 0.1
    }
});
await webllmModel.initialize();

Additionally, ensure that your ChatWebLLM class is updated to use MLCEngine as shown in the libs/langchain-community/src/chat_models/webllm.ts file:

import * as webllm from "@mlc-ai/web-llm";

export class ChatWebLLM extends SimpleChatModel<WebLLMCallOptions> {
  protected engine: webllm.MLCEngine;

  async initialize(progressCallback?: webllm.InitProgressCallback) {
    this.engine = new webllm.MLCEngine();
    if (progressCallback !== undefined) {
      this.engine.setInitProgressCallback(progressCallback);
    }
    await this.reload(this.model, this.chatOptions, this.appConfig);
    this.engine.setInitProgressCallback(() => {});
  }

  async reload(
    modelId: string,
    newAppConfig?: webllm.AppConfig,
    newChatOpts?: webllm.ChatOptions
  ) {
    if (this.engine !== undefined) {
      await this.engine.reload(modelId, newAppConfig, newChatOpts);
    } else {
      throw new Error("Initialize model before reloading.");
    }
  }

  async *_streamResponseChunks(
    messages: BaseMessage[],
    options: this["ParsedCallOptions"],
    runManager?: CallbackManagerForLLMRun
  ): AsyncGenerator<ChatGenerationChunk> {
    await this.initialize();

    const messagesInput: ChatCompletionMessageParam[] = messages.map(
      (message) => {
        if (typeof message.content !== "string") {
          throw new Error(
            "ChatWebLLM does not support non-string message content in sessions."
          );
        }
        const langChainType = message._getType();
        let role;
        if (langChainType === "ai") {
          role = "assistant" as const;
        } else if (langChainType === "human") {
          role = "user" as const;
        } else if (langChainType === "system") {
          role = "system" as const;
        } else {
          throw new Error(
            "Function, tool, and generic messages are not supported."
          );
        }
        return {
          role,
          content: message.content,
        };
      }
    );

    const stream = this.engine.chatCompletionAsyncChunkGenerator(
      {
        stream: true,
        messages: messagesInput,
        stop: options.stop,
        logprobs: true,
      },
      {}
    );
    for await (const chunk of stream) {
      const text = chunk.choices[0].delta.content ?? "";
      yield new ChatGenerationChunk({
        text,
        message: new AIMessageChunk({
          content: text,
          additional_kwargs: {
            logprobs: chunk.choices[0].logprobs,
            finish_reason: chunk.choices[0].finish_reason,
          },
        }),
      });
      await runManager?.handleLLMNewToken(text ?? "");
    }
  }

  async _call(
    messages: BaseMessage[],
    options: this["ParsedCallOptions"],
    runManager?: CallbackManagerForLLMRun
  ): Promise<string> {
    const chunks = [];
    for await (const chunk of this._streamResponseChunks(
      messages,
      options,
      runManager
    )) {
      chunks.push(chunk.text);
    }
    return chunks.join("");
  }
}

This change updates the ChatWebLLM class to use MLCEngine instead of Engine, aligning with the recent renaming in the @mlc-ai/web-llm package [1].

To continue talking to Dosu, mention @dosu.

from langchainjs.

jacoblee93 avatar jacoblee93 commented on August 16, 2024 2

Live in community 0.2.6

from langchainjs.

kaiwinut avatar kaiwinut commented on August 16, 2024

Sorry, just figured that there's already a related PR #5637 ...

from langchainjs.

jacoblee93 avatar jacoblee93 commented on August 16, 2024

Merged that one, will ship community today!

from langchainjs.

kaiwinut avatar kaiwinut commented on August 16, 2024

Thanks a lot for the great work!
I found out some other tiny issues in the code and example.
Just created a PR #5671 to fix them.

from langchainjs.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.