OpenAI Integration
Add powerful AI capabilities to your app using OpenAI’s GPT models. Create chatbots, generate content, analyze text, and more.What You Can Build
- AI Chat — Conversational interfaces
- Content Generation — Write text, summarize, translate
- Q&A Bots — Answer questions about your content
- Creative Tools — Story writing, brainstorming
- Analysis — Sentiment analysis, categorization
Prerequisites
- OpenAI account with API access
- API key from OpenAI dashboard
- Credit balance (new accounts get $5 free)
Getting Your API Key
Create OpenAI account
Go to platform.openai.com and sign up
Setting Up in Nativeline
Tell Nativeline about your API:Building an AI Chat
Basic Chat Interface
Connecting to OpenAI
OpenAI Models
| Model | Best For | Speed | Cost |
|---|---|---|---|
gpt-4o | Complex tasks, reasoning | Medium | Higher |
gpt-4o-mini | Simple tasks, chat | Fast | Lower |
gpt-3.5-turbo | Basic chat, cost-sensitive | Fast | Lowest |
Choosing a Model
API Parameters
Temperature
Controls randomness (0 = focused, 1 = creative):Max Tokens
Limits response length:System Prompt
Sets the AI’s behavior:Example Use Cases
Chatbot
Content Generator
Summarizer
Writing Assistant
Handling Conversations
Maintaining Context
Include conversation history for context:Trimming History
For long conversations, trim old messages:Error Handling
Common Errors
| Error | Cause | Solution |
|---|---|---|
| Invalid API key | Wrong or expired key | Check key in OpenAI dashboard |
| Rate limited | Too many requests | Wait and retry with backoff |
| Insufficient quota | Out of credits | Add credits in OpenAI billing |
| Context too long | Too many tokens | Trim conversation history |
Handling in App
Cost Management
Monitoring Usage
Check usage at platform.openai.com/usageReducing Costs
- Use
gpt-4o-miniinstead ofgpt-4o - Set max tokens limit
- Cache common responses
- Trim conversation history
Setting Limits
In OpenAI dashboard:- Settings → Billing → Usage limits
- Set monthly budget
- Get notified before exceeding
Best Practices
Write good system prompts
Write good system prompts
Clear system prompts improve results:
- Define the AI’s role
- Specify tone and style
- Set boundaries
- Include examples
Handle rate limits
Handle rate limits
Implement exponential backoff:
- Wait 1 second, retry
- If fails, wait 2 seconds
- Then 4, 8, etc.
Show loading states
Show loading states
API calls take time. Show:
- Loading indicator
- “Thinking…” message
- Disable send button
Validate inputs
Validate inputs
Check user input before sending:
- Not empty
- Within length limits
- No obvious abuse
Advanced: Streaming
For longer responses, stream tokens as they arrive:DALL-E (Image Generation)
OpenAI also offers image generation:DALL-E has separate pricing. Check OpenAI pricing page for current rates.