Package Exports
- @umituz/react-native-ai-grok-provider
- @umituz/react-native-ai-grok-provider/src/index.ts
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@umituz/react-native-ai-grok-provider) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@umituz/react-native-ai-grok-provider
Grok AI provider for React Native applications - implements unified AI generation interface with comprehensive text and image generation capabilities.
🚀 Features
- Text Generation: Advanced AI-powered text generation with Grok models
- Function Calling: Execute functions and tools with AI assistance
- Web Search: Real-time web search and data retrieval
- Image Generation: High-quality image generation using Grok Vision
- Audio Processing: Speech-to-text, text-to-speech, and audio analysis
- Streaming Support: Real-time streaming responses for better UX
- Multimodal: Support for text, image, and audio inputs together
- X/Twitter Integration: Real-time social media data and trends
- Stock Data: Live stock market information
- Weather Data: Current weather information and forecasts
- News: Real-time news articles and analysis
- Performance Optimization: Request batching, caching, and smart retries
- Error Handling: Comprehensive error handling with circuit breakers
- Telemetry: Performance tracking and analytics
- TypeScript: Full TypeScript support with strict typing
- React Hooks: Easy-to-use React hooks for integration
- Example Components: Ready-to-use demo components
📦 Installation
npm install @umituz/react-native-ai-grok-provider🔧 Setup
1. Get API Key
First, get your Grok API key from X AI Platform.
2. Initialize Provider
import { useGrok } from '@umituz/react-native-ai-grok-provider';
function MyComponent() {
const grok = useGrok({
config: {
apiKey: 'your-api-key-here',
model: 'grok-2', // Optional, defaults to 'grok-2'
},
autoInitialize: true,
});
// ... rest of your component
}🎯 Basic Usage
Text Generation
import { useGrok } from '@umituz/react-native-ai-grok-provider';
function ChatComponent() {
const { generateTextSimple, isLoading, error } = useGrok({
config: { apiKey: 'your-api-key' },
autoInitialize: true,
});
const handleGenerateText = async () => {
const response = await generateTextSimple(
'Write a short story about a robot learning to paint.'
);
if (response) {
console.log('Generated text:', response);
}
};
return (
<View>
<Button
title="Generate Text"
onPress={handleGenerateText}
disabled={isLoading}
/>
{error && <Text>Error: {error.message}</Text>}
</View>
);
}Advanced Text Generation
import { useGrok, createTextMessage, buildTextGenerationRequest } from '@umituz/react-native-ai-grok-provider';
function AdvancedChatComponent() {
const { generateText, isLoading } = useGrok({
config: { apiKey: 'your-api-key' },
autoInitialize: true,
});
const handleAdvancedGeneration = async () => {
const messages = [
createTextMessage('system', 'You are a helpful writing assistant.'),
createTextMessage('user', 'Help me write a poem about nature.'),
];
const request = buildTextGenerationRequest('grok-2', messages, {
maxTokens: 500,
temperature: 0.8,
topP: 0.9,
});
const response = await generateText(request);
if (response) {
const text = response.choices[0]?.message?.content;
console.log('Generated text:', text);
}
};
return (
<Button
title="Generate Advanced Text"
onPress={handleAdvancedGeneration}
disabled={isLoading}
/>
);
}Streaming Text Generation
import { useGrok, createTextMessage, buildTextGenerationRequest } from '@umituz/react-native-ai-grok-provider';
function StreamingChatComponent() {
const [streamedText, setStreamedText] = useState('');
const { generateTextStream, isLoading } = useGrok({
config: { apiKey: 'your-api-key' },
autoInitialize: true,
});
const handleStreamingGeneration = async () => {
setStreamedText('');
const messages = [createTextMessage('user', 'Tell me a story.')];
const request = buildTextGenerationRequest('grok-2', messages);
await generateTextStream(request, (chunk) => {
const content = chunk.choices[0]?.delta?.content || '';
setStreamedText(prev => prev + content);
});
};
return (
<View>
<Button
title="Generate Streaming Text"
onPress={handleStreamingGeneration}
disabled={isLoading}
/>
<Text>{streamedText}</Text>
</View>
);
}Image Generation
import { useGrok } from '@umituz/react-native-ai-grok-provider';
function ImageGenerationComponent() {
const { generateImagesSimple, isLoading } = useGrok({
config: { apiKey: 'your-api-key' },
autoInitialize: true,
});
const handleGenerateImage = async () => {
const images = await generateImagesSimple(
'A beautiful sunset over mountains',
2 // Generate 2 images
);
if (images && images.length > 0) {
console.log('Generated images:', images);
// You can use these URLs to display images
}
};
return (
<Button
title="Generate Images"
onPress={handleGenerateImage}
disabled={isLoading}
/>
);
}Multimodal (Text + Image)
import { useGrok, createImageMessage, buildTextGenerationRequest } from '@umituz/react-native-ai-grok-provider';
function MultimodalComponent() {
const { generateText } = useGrok({
config: { apiKey: 'your-api-key' },
autoInitialize: true,
});
const handleMultimodalGeneration = async () => {
const messages = [
createImageMessage(
'user',
'What do you see in this image?',
'https://example.com/image.jpg',
'high'
),
];
const request = buildTextGenerationRequest('grok-vision', messages);
const response = await generateText(request);
if (response) {
const description = response.choices[0]?.message?.content;
console.log('Image description:', description);
}
};
return (
<Button
title="Analyze Image"
onPress={handleMultimodalGeneration}
/>
);
}🔧 Configuration
GrokConfig Options
interface GrokConfig {
apiKey: string; // Required: Your Grok API key
baseURL?: string; // Optional: Custom base URL
timeout?: number; // Optional: Request timeout in ms
maxRetries?: number; // Optional: Maximum retry attempts
model?: string; // Optional: Default model
}Available Models
grok-2: Advanced AI model with enhanced reasoning capabilitiesgrok-2-mini: Lightweight version for faster responsesgrok-vision: Specialized model for image understanding and generation
Feature-Specific Models
The provider includes optimized configurations for different use cases:
import { GROK_FEATURE_MODELS } from '@umituz/react-native-ai-grok-provider';
// Use pre-configured models
GROK_FEATURE_MODELS.TEXT_GENERATION // Balanced text generation
GROK_FEATURE_MODELS.FAST_RESPONSE // Fast responses for simple tasks
GROK_FEATURE_MODELS.CREATIVE_WRITING // Higher creativity
GROK_FEATURE_MODELS.CODE_GENERATION // Optimized for code
GROK_FEATURE_MODELS.ANALYSIS // Analytical responses
GROK_FEATURE_MODELS.IMAGE_GENERATION // Image generation🛠️ Error Handling
The provider includes comprehensive error handling:
import { useGrok, GrokErrorType } from '@umituz/react-native-ai-grok-provider';
function ErrorHandlingComponent() {
const { generateTextSimple, error, clearError } = useGrok({
config: { apiKey: 'your-api-key' },
autoInitialize: true,
onError: (error) => {
switch (error.type) {
case GrokErrorType.INVALID_API_KEY:
console.log('Invalid API key provided');
break;
case GrokErrorType.RATE_LIMIT:
console.log('Rate limit exceeded. Please wait.');
break;
case GrokErrorType.MODEL_NOT_FOUND:
console.log('Model not found');
break;
// ... other error types
}
},
});
return (
<View>
{error && (
<View>
<Text>Error: {error.message}</Text>
<Button title="Clear Error" onPress={clearError} />
</View>
)}
<Button title="Generate" onPress={() => generateTextSimple('Hello')} />
</View>
);
}📊 Performance & Monitoring
Telemetry
Built-in telemetry for performance tracking:
import { grokTelemetryService } from '@umituz/react-native-ai-grok-provider';
// Get performance metrics
const avgTextGeneration = grokTelemetryService.getAveragePerformance('text_generation');
const errorSummary = grokTelemetryService.getErrorSummary();
const eventCounts = grokTelemetryService.getEventCounts();Logging
Comprehensive logging for debugging:
import { grokLogger, LogLevel } from '@umituz/react-native-ai-grok-provider';
// Adjust log level
grokLogger.setMinLevel(LogLevel.DEBUG);
// Get recent logs
const recentLogs = grokLogger.getRecentLogs(50);
const errorLogs = grokLogger.getLogsByLevel(LogLevel.ERROR);🎨 Advanced Usage
Custom HTTP Client
import { createGrokProvider } from '@umituz/react-native-ai-grok-provider';
const customProvider = createGrokProvider(
customHttpClient, // Your custom HTTP client
customCache, // Your custom cache
customTelemetry, // Your custom telemetry
customLogger // Your custom logger
);Utility Functions
import {
estimateGrokTokens,
createTextMessage,
createImageMessage,
buildTextGenerationRequest,
buildImageGenerationRequest,
debounce,
throttle
} from '@umituz/react-native-ai-grok-provider';
// Estimate tokens
const tokenCount = estimateGrokTokens('Your text here');
// Create messages
const textMsg = createTextMessage('user', 'Hello!');
const imageMsg = createImageMessage('user', 'What is this?', imageUrl);
// Build requests
const textRequest = buildTextGenerationRequest('grok-2', [textMsg]);
const imageRequest = buildImageGenerationRequest('Beautiful sunset');🔒 Security Best Practices
- Never expose API keys in client-side code - Use environment variables
- Use rate limiting - Implement client-side rate limiting
- Validate inputs - Always validate user inputs before sending to API
- Handle errors gracefully - Never expose sensitive error information
- Use caching wisely - Cache responses but respect data privacy
📝 TypeScript Support
Full TypeScript support with comprehensive types:
import type {
GrokConfig,
GrokGenerationRequest,
GrokGenerationResponse,
GrokImageGenerationRequest,
GrokImageGenerationResponse,
GrokError,
GrokErrorType,
GrokModel
} from '@umituz/react-native-ai-grok-provider';🤝 Contributing
- Follow the existing code style and patterns
- Ensure all functions have proper TypeScript types
- Add comprehensive error handling
- Include performance tracking where appropriate
- Write clear documentation for new features
📄 License
MIT License - see LICENSE file for details.
🔗 Related Packages
@umituz/react-native-ai-generation-content- Base AI generation interface@umituz/react-native-ai-gemini-provider- Google Gemini AI provider@umituz/react-native-ai-fal-provider- FAL AI provider
📞 Support
For issues and support:
- Create an issue on GitHub
- Check the documentation
- Review example implementations