nuxt-chatgpt

repository·master·Indexed 41 days ago

https://github.com/schnapsterdog/nuxt-chatgpt

A Nuxt 3 module providing a secure, type-safe integration for OpenAI's ChatGPT. It utilizes a Nitro Server proxy to protect API keys and provides the `useChatgpt()` composable for chat, completions, and image generation. Version 0.4.0 supports streaming responses via Server-Sent Events (SSE) and integrates with the openai library v4.0.0.

Tokens
5.8K
Snippets
21
Records
29
Agent score
51%

What's inside nuxt-chatgpt

  1. Overview of nuxt-chatgpt features

    master

    nuxt-chatgpt is a lightweight, type-safe module for Nuxt 3 that provides seamless ChatGPT integration.

    Key Capabilities:

    • Composable Access: Use the useChatgpt() composable to access core methods.
    • Core Methods: Includes chat, chatCompletion, and generateImage.
    • Streaming Support: Provides chatCompletionStream for real-time Server-Sent Events (SSE) responses.
    • Security: All requests are routed through a Nitro Server to prevent exposing your OpenAI API Key to the client side.
  2. What is the difference between chat and chatCompletion?

    master

    The primary difference lies in context:

    • chat: Designed for simple, single-turn interactions. You send a prompt, and the model provides a response. It is ideal for basic chatbots or single-question interfaces.
    • chatCompletion: Designed for multi-turn conversations. It accepts an array of messages (history), allowing the model to maintain context and provide responses consistent with previous parts of the conversation. This is necessary for building complex, natural conversational agents.
  3. What is the useChatgpt composable?

    master

    The useChatgpt() composable is the primary interface for interacting with ChatGPT within your Nuxt application. It provides type-safe access to the following methods:

    • chat: For standard chat interactions.
    • chatCompletion: For generating completions.
    • chatCompletionStream: For real-time streamed responses (SSE).
    • generateImage: For image generation tasks.
  4. Difference between chatCompletionStream and chatCompletion

    master

    When choosing between these two methods, consider your UI requirements:

    • chatCompletionStream: Returns the assistant response as a stream (token-by-token). Use this to build ChatGPT-like interfaces where text is displayed incrementally as it is generated.
    • chatCompletion: Returns the full response at once after generation is complete.
  5. Install and configure the nuxt-chatgpt module

    master

    To integrate ChatGPT into your Nuxt 3 project, add the nuxt-chatgpt dependency and register it in your nuxt.config.ts. The module uses the openai library (v4.0.0) under the hood and routes requests through a Nitro Server to keep your API Key secure.

    Prerequisites

    • Node.js: Minimum v18.20.5, recommended v20.19.0.

    Installation

    Run the following command to add the module:

    npx nuxt module add nuxt-chatgpt

    Configuration

    Add nuxt-chatgpt to your modules array in nuxt.config.ts. You can optionally provide your OpenAI apiKey within the chatgpt configuration object.

    export default defineNuxtConfig({
      modules: ["nuxt-chatgpt"],
    
      // entirely optional
      chatgpt: {
        apiKey: 'Your apiKey here goes here'
      },
    })
  6. Configure nuxt-chatgpt module options

    master

    The nuxt-chatgpt module can be configured in your Nuxt configuration file using the following options:

    NameTypeDefaultDescription
    apiKeyStringxxxxxxYour OpenAI API key
    isEnabledBooleantrueEnable or disable the module

    Note: isEnabled is true by default.

  7. Implement simple chat with chat()

    master

    Use chat() for simple, single-turn interactions where you only need to send a single string and get a response. By default, it uses the gpt-4o-mini model if unspecified.

    const { chat } = useChatgpt()
    const inputData = ref('')
    const data = ref('')
    
    async function sendMessage() {
      try {
        const response = await chat(inputData.value)
        data.value = response
      } catch(error) {
        alert(`Error: ${error}`)
      }
    }
  8. Generate images with generateImage()

    master

    Use generateImage() to create images from text prompts. The method returns an array of image objects. If the response format is b64_json, you will need to convert the base64 string to a Blob URL to display it in an <img> tag.

    const { generateImage } = useChatgpt()
    const images = ref([])
    const inputData = ref('')
    
    function b64ToBlobUrl(b64) {
      const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
      const blob = new Blob([bytes], { type: "image/png" });
      return URL.createObjectURL(blob);
    }
    
    async function sendPrompt() {
      try {
        const result = await generateImage(inputData.value);
        images.value = result.map((img) => ({
          url: b64ToBlobUrl(img.b64_json),
        }));
      } catch (error) {
        alert(`Error: ${error}`);
      }
    }
  9. Implement streaming responses with chatCompletionStream()

    master

    Use chatCompletionStream() to receive responses token-by-token. This requires providing a callback object with onToken, onDone, and onError handlers.

    Important: When managing a local chat history array, do not include the empty placeholder assistant message in the payload sent to the server; slice it out before calling the method.

    const { chatCompletionStream } = useChatgpt()
    const chatTree = ref([])
    const inputData = ref('')
    
    async function sendStreamedMessage() {
      try {
        const message = { role: 'user', content: inputData.value }
        chatTree.value.push(message)
    
        const assistantMessage = { role: 'assistant', content: '' }
        chatTree.value.push(assistantMessage)
    
        // Slice to remove the placeholder assistant message from the payload
        const payloadMessages = chatTree.value.slice(0, -1)
    
        await chatCompletionStream(payloadMessages, undefined, undefined, {
          onToken(token) {
            assistantMessage.content += token
          },
          onDone() {
            // streaming finished
          },
          onError(err) {
            alert(`Stream error: ${typeof err === 'string' ? err : err?.message || 'Unknown'}`)
          }
        })
      } catch(error) {
        alert(`Error: ${error}`)
      }
    }
  10. Implement conversational history with chatCompletion()

    master

    Use chatCompletion() when you need to maintain context. You must pass an array of message objects containing role and content to allow the model to understand the conversation history.

    const { chatCompletion } = useChatgpt()
    const chatTree = ref([])
    const inputData = ref('')
    
    async function sendMessage() {
      try {
        const message = {
          role: 'user',
          content: inputData.value,
        }
        chatTree.value.push(message)
    
        const response = await chatCompletion(chatTree.value)
        
        const responseMessage = {
          role: response[0].message.role,
          content: response[0].message.content
        }
        chatTree.value.push(responseMessage)
      } catch(error) {
        alert(`Error: ${error}`)
      }
    }
  11. Use the useChatgpt composable

    master

    To access the core functionality of the nuxt-chatgpt module, use the useChatgpt() composable. It provides access to the following methods:

    • chat(message, model?, options?): Sends a single text message and receives a response.
    • chatCompletion(messages, model?, options?): Sends an array of message objects (conversation history) and receives a response.
    • chatCompletionStream(messages, model?, options?, callbacks?): Sends an array of message objects and receives a streamed response via callbacks.
    • generateImage(message, model?, options?): Generates images based on a text description.
    const { chat, chatCompletion, chatCompletionStream, generateImage } = useChatgpt()
  12. Identify the Nuxt configuration key for nuxt-chatgpt

    master

    When configuring nuxt-chatgpt within your Nuxt application, use the key chatgpt to access the module's configuration options in your nuxt.config.ts or when accessing the module via runtime config.

    // Example usage in nuxt.config.ts
    export default defineNuxtConfig({
      chatgpt: {
        // your configuration here
      }
    })