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-betaInitialization
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
Token Management
- Monitor token usage through response metadata
- Set appropriate limits for your use case
- Handle token limit errors gracefully
Error Handling
- Always wrap API calls in try-catch blocks
- Provide meaningful error feedback to users
- Implement proper retry logic for transient failures
Performance Optimization
- Use streaming for long responses
- Implement proper pagination for threads and assistants
- Cache frequently accessed data when appropriate
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:
- Open an issue on our GitHub repository
- Visit our Support Portal
