deep-chat

repository·main·Indexed 25 days ago

https://github.com/ovidijusparsiunas/deep-chat

A highly customizable AI chat component (version 2.5.0) designed for easy integration into websites. It supports direct connections to major AI APIs, custom backend services, and browser-hosted models. The library includes example server templates for Phoenix, Go, Spring Boot, NextJS (App and Pages Router), Express, NestJS, Node.js WebSockets, and Flask to act as proxies for services like OpenAI, HuggingFace, StabilityAI, and Cohere.

Tokens
79.8K
Snippets
251
Records
385
Agent score
81%

What's inside deep-chat

  1. Overview of Deep Chat

    main
    Deep Chat is a framework-agnostic web component designed to integrate AI services into any website. It is built to be highly customizable, allowing developers to modify both interactive features and styling details to meet unique API requirements and UX demands. It is shipped as a plug-and-play package compatible with various web frameworks.
  2. Setup the DeepChat Phoenix Example Server

    main

    To run the Phoenix LiveView template example for Deep Chat, follow these steps to install dependencies and start the server:

    1. Install Elixir dependencies: mix setup
    2. Install JavaScript dependencies (run this inside the assets folder): npm install
    3. Start the Phoenix server: mix phx.server (or iex -S mix phx.server to run within IEx)

    Once started, the server is accessible at http://localhost:4000.

    mix setup
    cd assets && npm install
    mix phx.server
  3. Implement Server-Sent Events (SSE) for Deep Chat in Phoenix

    main

    To support Server-Sent Events (SSE) in a Phoenix application for Deep Chat communication, implement the following:

    • Use Plug.Conn.send_chunked and Plug.Conn.chunk to handle the stream.
    • Configure the MIME type in config.exs:
      config :mime, :types, %{"text/event-stream" => ["sse"]}
    • Ensure your plug accepts the sse type: plug :accepts, ["json", "sse"].
    • Nginx Note: If deploying behind Nginx, you must disable buffering by adding the header put_resp_header("x-accel-buffering", "no") to your response.
  4. Connect to Alibaba Cloud Qwen via directConnection

    main

    Use the qwen property within directConnection to connect directly to Alibaba Cloud's Qwen API. You can provide a boolean true for default settings or an object to configure specific model parameters.

    Supported models include Qwen LMs, Qwen-VL, Qwen-Coder, Qwen-Omni, and Qwen-Math.

    Configuration Options:

    • key: Your Alibaba Cloud API key.
    • model: The name of the Qwen model (default: qwen-plus).
    • temperature: Controls randomness (0.0-2.0).
    • max_tokens: Maximum number of tokens to generate.
    • top_p: Nucleus sampling diversity (0.0-1.0).
    • frequency_penalty: Reduces repetition (-2.0 to 2.0).
    • presence_penalty: Controls token repetition (-2.0 to 2.0).
    • stop: Sequences where generation stops.
    • system_prompt: Defines the model's role/objective.
    • tools: Array of QwenTool declarations.
    • tool_choice: Controls tool usage ("auto" | "none" | {type: "function", function: {name: string}}).
    • function_handler: Callback for handling tool calls.
    <deep-chat
      directConnection='{
        "qwen": {
          "key": "placeholder key",
          "system_prompt": "You are a helpful assistant.",
          "temperature": 0.7
        }
      }'
    ></deep-chat>
  5. Implement Tool Calling with GeminiTool and FunctionHandler

    main

    Gemini supports function calling. To implement this, you must provide two things in the gemini configuration:

    1. tools (GeminiTool): An array of objects containing functionDeclarations. Each declaration includes a name, description, and parameters (defined using JSON Schema).
    2. function_handler (FunctionHandler): A function that receives functionsDetails (information about which tools to call) and returns either:
      • An array of objects { response: string }[] containing the results for each tool call to be fed back to the model.
      • An object { text: string } to immediately display text in the chat.

    Example Implementation:

    chatElementRef.directConnection = {
      gemini: {
        tools: [
          {
            functionDeclarations: [
              {
                name: 'get_current_weather',
                description: 'Get the current weather in a given location',
                parameters: {
                  type: 'object',
                  properties: {
                    location: {
                      type: 'string',
                      description: 'The city and state, e.g. San Francisco, CA',
                    },
                    unit: {type: 'string', enum: ['celsius', 'fahrenheit']},
                  },
                  required: ['location'],
                },
              },
            ],
          },
        ],
        function_handler: (functionsDetails) => {
          return functionsDetails.map((functionDetails) => {
            return {
              response: getCurrentWeather(functionDetails.arguments),
            };
          });
        },
        key: 'placeholder-key',
      },
    };
  6. Set up the Deep Chat NextJS App Router template locally

    main

    This template provides a NextJS App Router setup to communicate with the Deep Chat component. It includes endpoints that act as proxies for AI APIs like OpenAI, HuggingFace, StabilityAI, and Cohere.

    To set it up locally:

    1. Clone the repository (shallow clone recommended to reduce size).
    2. Install dependencies using npm install.
    3. Start the development server with npm run dev.

    To use the proxy functions (e.g., OpenAI), you must provide the necessary API keys via environment variables.

    git clone --depth 1 https://github.com/OvidijusParsiunas/deep-chat.git
    cd deep-chat/example-servers/nextjs/app-router
    npm install
    npm run dev
  7. Connect to Open WebUI via directConnection

    main

    You can connect the <deep-chat> component directly to an Open WebUI instance using the openWebUI property within directConnection. By default, it attempts to connect to http://localhost:3000/api/chat/completions.

    To connect to a remote instance, use the connect property to specify a custom url pointing to your Open WebUI Chat Completions API endpoint.

    <deep-chat
      directConnection='{"openWebUI": {"key": "placeholder key", "model": "llama3.2:latest"}}'
      connect='{"url": "https://your-openwebui-instance.com/api/chat/completions"}'
    ></deep-chat>
  8. Run a chat model in the browser using Web Model

    main

    The webModel feature allows you to run a chat model entirely within the user's browser without connecting to any external services. This provides privacy and reduces server costs.

    Setup

    1. Integrate the deep-chat-web-llm module into your project.
    2. Configure the webModel property on the <deep-chat> component.

    Configuration Options

    You can set webModel to true for default settings or provide an object to customize the behavior:

    • model (string): The name of the model to be used. (Default: "Llama-3.2-1B-Instruct-q4f16_1-MLC")
    • instruction (string): Directs how the model should respond.
    • urls (WebModelUrls): Defines the endpoints to retrieve the web model assets.
    • load (WebModelLoad): Defines how and when the model is loaded.
    • introMessage (WebModelIntro): Configuration for the introductory web model message.
    • worker (Worker): A Web Worker that can be used to enhance rendering performance.
    <deep-chat webModel="true"></deep-chat>