npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

dragonfly-sdk-beta

v1.3.6

Published

- [Installation](#installation) - [Initialization](#initialization) - [Authentication](#authentication) - [Features](#features) - [Chat](#chat) - [Audio Transcription](#audio-transcription) - [Models](#models) - [Threads](#threads) - [As

Readme

Dragonfly AI SDK Documentation

Table of Contents

Installation

npm install dragonfly-sdk-beta
# or
yarn add dragonfly-sdk-beta

Initialization

import { dragonfly } from 'dragonfly-sdk-beta';

dragonfly.init({
  apiKey: "YOUR_API_KEY",
  defaultModel: "chatgpt-4o-latest",  // Optional default model
});

Authentication

The SDK provides a simple authentication hook that handles login requests and returns the authentication response for you to manage:

import { useAuth } from 'dragonfly-sdk-beta';

interface AuthResponse {
  token: string;        // JWT authentication token
  expires_at: string;   // Token expiration timestamp
  user: {
    id: string;
    email: string;
    profileImage: string;
    firstName: string;
    roles: string[];
  };
}

function LoginComponent() {
  const { login, isLoading, error } = useAuth();

  const handleLogin = async (email: string, password: string) => {
    try {
      const response = await login(email, password);
      
      // Handle the authentication response
      // Store token and user info according to your needs
      saveAuthToken(response.token);            // Your token storage implementation
      saveUserInfo(response.user);              // Your user info storage implementation
      handleTokenExpiration(response.expires_at); // Your expiration handling
      
    } catch (error) {
      // Handle login errors
      console.error('Login failed:', error);
    }
  };

  return (
    <form onSubmit={handleLogin}>
      {/* Your login form */}
      {isLoading && <LoadingSpinner />}
      {error && <ErrorMessage error={error} />}
    </form>
  );
}

Features

Chat

The SDK provides two modes for chat interaction:

Regular Chat

const { useChat } = require('dragonfly-sdk-beta');

function ChatComponent() {
  const { sendMessage, isLoading, error } = useChat();

  const handleMessage = async () => {
    const options = {
      model: "chatgpt-4o-latest",      // Optional: specific model
      assistantId: "assistant-id",      // Optional: specific assistant
      temperature: 0.7,                 // Optional: controls randomness (0-1)
      topP: 1,                         // Optional: controls diversity
      promptSystem: "Custom prompt",    // Optional: system instructions
      threadId: "thread-id",           // Optional: continue conversation
      files: [fileObject],             // Optional: file attachments
      images: ["base64-image"]         // Optional: image attachments
    };

    try {
      const response = await sendMessage("Hello!", options);
      console.log(response);
    } catch (error) {
      console.error(error);
    }
  };
}

Response structure:

{
  text: string;             // AI response
  usage: {
    prompt_tokens: number;    // Tokens in prompt
    completion_tokens: number; // Tokens in response
    total_tokens: number;     // Total tokens used
  };
  threadId: string;         // Conversation ID
  createdTime: number;      // Response timestamp
  usedModel: string;        // Model used
  refusal?: string | null;  // If request was refused
}

Streaming Chat

const { useChatStream } = require('dragonfly-sdk-beta');

function StreamingChatComponent() {
  const { streamMessage, isStreaming, error } = useChatStream();

  const handleStream = async () => {
    try {
      for await (const chunk of streamMessage("Hello!", {
        assistantId: "assistant-id",
        temperature: 0.7
      })) {
        console.log(chunk.text);  // Process each chunk
      }
    } catch (error) {
      console.error(error);
    }
  };
}

Stream chunk structure:

{
  text: string;      // Chunk of response
  done: boolean;     // Is this the last chunk
  threadId: string;  // Conversation ID
  model: string;     // Model being used
  created: number;   // Timestamp
  usage?: {          // Token usage (in final chunk)
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  }
}

Audio Transcription

const { useAudio } = require('dragonfly-sdk-beta');

function AudioComponent() {
  const { transcribeAudio, transcription, isLoading, error } = useAudio();

  const handleAudioUpload = async (file) => {
    try {
      const result = await transcribeAudio(file);
      console.log(result.transcription);
    } catch (error) {
      console.error('Transcription failed:', error);
    }
  };
}

Models

const { useModel } = require('dragonfly-sdk-beta');

function ModelsComponent() {
  const { models, fetchModels, isLoading, error } = useModel();

  useEffect(() => {
    fetchModels();  // Fetches available models
  }, []);

  // Models are grouped by provider
  // {
  //   host: string;        // Provider name
  //   icon: string;        // Provider icon
  //   position: number;    // Display order
  //   models: [{
  //     id: number;
  //     name: string;
  //     max_token: number;
  //     context_window: number;
  //   }]
  // }
}

Threads

The SDK provides comprehensive thread management:

const { useThread } = require('dragonfly-sdk-beta');

function ThreadComponent() {
  const { listThreads, getThread, isLoading, error } = useThread();

  const loadThreads = async () => {
    const options = {
      page: 1,              // Optional: page number
      itemsPerPage: 10,     // Optional: items per page
      search: "keyword"     // Optional: search term
    };

    const threads = await listThreads(options);
    console.log(threads);
    // {
    //   threads: [{
    //     id: string;
    //     firstMessage: string;
    //     createdAt: string;
    //   }],
    //   totalItems: number;
    //   currentPage: number;
    // }
  };

  const viewThread = async (threadId) => {
    const thread = await getThread(threadId);
    console.log(thread);
    // {
    //   id: string;
    //   messages: [{
    //     id: string;
    //     text: string;
    //     sender: 'user' | 'ai';
    //     timestamp: number;
    //     ...
    //   }];
    //   assistantInfo: {
    //     name: string;
    //     id: string;
    //     openAiId: string;
    //     model: string;
    //   };
    //   usage: {
    //     totalTokens: string;
    //     inputTokens: string;
    //     outputTokens: string;
    //   };
    //   timestamps: {
    //     created: string;
    //     updated: string;
    //   };
    // }
  };
}

Assistants

Manage AI assistants:

const { useAssistant } = require('dragonfly-sdk-beta');

function AssistantComponent() {
  const { 
    listAssistants, 
    getAssistant, 
    duplicateAssistant,
    isLoading, 
    error 
  } = useAssistant();

  const loadAssistants = async () => {
    const options = {
      page: 1,
      itemsPerPage: 10
    };

    const result = await listAssistants(options);
    console.log(result.assistants);
  };

  const viewAssistant = async (assistantId) => {
    const assistant = await getAssistant(assistantId);
    console.log(assistant);
    // {
    //   id: string;
    //   name: string;
    //   description: string;
    //   image: string;
    //   assistantId: string;
    //   activeScript: boolean;
    //   tools: any[];
    //   modelAi: string;
    //   modelAiName: string;
    //   promptSystem: string;
    // }
  };

  const createCopy = async (assistantId, newName) => {
    const newAssistant = await duplicateAssistant(assistantId, newName);
    console.log(newAssistant);
  };
}

Types Reference

Chat Options

interface ChatOptions {
  model?: string;          // Model ID
  assistantId?: string;    // Assistant ID
  temperature?: number;    // Randomness (0-1)
  topP?: number;          // Diversity control
  promptSystem?: string;  // System instructions
  stream?: boolean;       // Enable streaming
  threadId?: string;      // Thread ID
  files?: File[];        // File attachments
  images?: string[];     // Base64 images
}

Message Content

interface MessageContent {
  type: 'text' | 'image_url';
  text?: string;
  image_url?: {
    url: string;  // Base64 or URL
  };
}

Thread Message

interface ThreadMessage {
  id: string | number;
  text: string;
  sender: 'user' | 'ai';
  senderInfo: {
    senderImageUrl: string;
    senderName: string;
  };
  timestamp: number;
  fileNames: string[];
  imageData: string[];
  isNewAIMessage: boolean;
  toolCalls: any[];
  finish_reason?: string;
  model?: string;
  responseId?: string;
  usage?: TokenUsage;
  thread_id?: string;
}

Examples

Complete Chat Application Example

import React, { useState, useEffect } from 'react';
import { useChat, useAssistant, useThread } from 'dragonfly-sdk-beta';

function ChatApp() {
  const [message, setMessage] = useState('');
  const [selectedAssistant, setSelectedAssistant] = useState(null);
  const [currentThread, setCurrentThread] = useState(null);
  const [chatHistory, setChatHistory] = useState([]);
  
  const { sendMessage, isLoading } = useChat();
  const { listAssistants } = useAssistant();
  const { getThread } = useThread();

  // Load assistants on mount
  useEffect(() => {
    const loadAssistants = async () => {
      const result = await listAssistants();
      if (result.assistants.length > 0) {
        setSelectedAssistant(result.assistants[0].id);
      }
    };
    loadAssistants();
  }, []);

  // Load thread history
  const loadThread = async (threadId) => {
    const thread = await getThread(threadId);
    setCurrentThread(threadId);
    setChatHistory(thread.messages);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!message.trim() || isLoading) return;

    try {
      const response = await sendMessage(message, {
        assistantId: selectedAssistant,
        threadId: currentThread
      });

      setChatHistory(prev => [...prev, {
        id: Date.now(),
        text: message,
        sender: 'user'
      }, {
        id: response.id,
        text: response.text,
        sender: 'ai'
      }]);

      setMessage('');
      setCurrentThread(response.threadId);
    } catch (error) {
      console.error('Error:', error);
    }
  };

  return (
    <div className="chat-container">
      <div className="chat-history">
        {chatHistory.map(msg => (
          <div key={msg.id} className={`message ${msg.sender}`}>
            <p>{msg.text}</p>
          </div>
        ))}
      </div>

      <form onSubmit={handleSubmit}>
        <input
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          placeholder="Type your message..."
          disabled={isLoading}
        />
        <button type="submit" disabled={isLoading}>
          {isLoading ? 'Sending...' : 'Send'}
        </button>
      </form>
    </div>
  );
}

Audio Transcription with File Upload

import React, { useState } from 'react';
import { useAudio } from 'dragonfly-sdk-beta';

function AudioTranscriptionApp() {
  const [file, setFile] = useState(null);
  const { transcribeAudio, transcription, isLoading, error } = useAudio();

  const handleFileChange = (e) => {
    const audioFile = e.target.files[0];
    if (audioFile) {
      setFile(audioFile);
    }
  };

  const handleTranscribe = async () => {
    if (!file) return;

    try {
      await transcribeAudio(file);
    } catch (error) {
      console.error('Transcription failed:', error);
    }
  };

  return (
    <div className="audio-container">
      <input
        type="file"
        accept="audio/*"
        onChange={handleFileChange}
        disabled={isLoading}
      />
      
      <button 
        onClick={handleTranscribe}
        disabled={!file || isLoading}
      >
        {isLoading ? 'Transcribing...' : 'Transcribe Audio'}
      </button>

      {error && (
        <div className="error">
          Error: {error.message}
        </div>
      )}

      {transcription && (
        <div className="transcription">
          <h3>Transcription:</h3>
          <p>{transcription}</p>
        </div>
      )}
    </div>
  );
}

Thread Management Example

import React, { useState, useEffect } from 'react';
import { useThread } from 'dragonfly-sdk-beta';

function ThreadManagerApp() {
  const [threads, setThreads] = useState([]);
  const [selectedThread, setSelectedThread] = useState(null);
  const { listThreads, getThread, isLoading } = useThread();

  useEffect(() => {
    loadThreads();
  }, []);

  const loadThreads = async () => {
    try {
      const result = await listThreads({
        itemsPerPage: 20,
        page: 1
      });
      setThreads(result.threads);
    } catch (error) {
      console.error('Error loading threads:', error);
    }
  };

  const viewThread = async (threadId) => {
    try {
      const thread = await getThread(threadId);
      setSelectedThread(thread);
    } catch (error) {
      console.error('Error loading thread:', error);
    }
  };

  return (
    <div className="thread-manager">
      <div className="thread-list">
        {threads.map(thread => (
          <div 
            key={thread.id}
            className="thread-item"
            onClick={() => viewThread(thread.id)}
          >
            <p>{thread.firstMessage}</p>
            <small>{new Date(thread.createdAt).toLocaleString()}</small>
          </div>
        ))}
      </div>

      {selectedThread && (
        <div className="thread-view">
          <h3>Thread Messages:</h3>
          {selectedThread.messages.map(msg => (
            <div key={msg.id} className="message">
              <p>{msg.text}</p>
              <small>{msg.sender}</small>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Advanced Usage

Custom Message Formatting

const { useChat } = require('dragonfly-sdk-beta');

function CustomChatComponent() {
  const { sendMessage } = useChat();

  const sendMultiModalMessage = async () => {
    const messages = [
      {
        role: 'user',
        content: [
          {
            type: 'text',
            text: 'Analyze this image:'
          },
          {
            type: 'image_url',
            image_url: {
              url: 'data:image/jpeg;base64,...' // Base64 image data
            }
          }
        ]
      }
    ];

    try {
      const response = await sendMessage(messages, {
        model: 'chatgpt-4o-latest',
        temperature: 0.7
      });
      console.log(response);
    } catch (error) {
      console.error(error);
    }
  };
}

Error Handling

The SDK provides detailed error information:

try {
  const response = await sendMessage("Hello");
} catch (error) {
  if (error.status === 401) {
    console.error('Authentication failed. Please check your API key.');
  } else if (error.status === 400) {
    console.error('Invalid request:', error.message);
  } else if (error.status === 429) {
    console.error('Rate limit exceeded. Please try again later.');
  } else {
    console.error('Unexpected error:', error);
  }
}

Best Practices

  1. Token Management

    • Monitor token usage through response metadata
    • Set appropriate limits for your use case
    • Handle token limit errors gracefully
  2. Error Handling

    • Always wrap API calls in try-catch blocks
    • Provide meaningful error feedback to users
    • Implement proper retry logic for transient failures
  3. Performance Optimization

    • Use streaming for long responses
    • Implement proper pagination for threads and assistants
    • Cache frequently accessed data when appropriate
  4. Security

    • Never expose your API key in client-side code
    • Validate and sanitize user input
    • Implement proper access controls
    • Handle sensitive information appropriately

For more detailed API documentation, visit our API Reference.

Support

For support, questions, or feature requests:

  1. Open an issue on our GitHub repository
  2. Visit our Support Portal