Guides
Step-by-step tutorials and best practices for using the Portal platform.
Tutorials
Building a Chatbot
Learn how to build a conversational AI chatbot using our API.
import { PortalClient } from 'portal-sdk';
const client = new PortalClient({
apiKey: process.env.PORTAL_API_KEY,
});
async function chat(userMessage: string) {
const response = await client.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: userMessage }
],
});
return response.choices[0].message.content;
}
File Processing
Upload and process documents with AI:
async function processDocument(file: File) {
// 1. Upload file
const uploadResult = await client.files.upload(file);
// 2. Extract text
const text = await client.files.extract(uploadResult.key);
// 3. Analyze with AI
const analysis = await client.chat.completions.create({
model: 'gpt-4',
messages: [
{
role: 'user',
content: `Summarize this document: ${text}`
}
],
});
return analysis.choices[0].message.content;
}
Streaming Responses
Handle real-time streaming responses:
const stream = await client.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Write a story' }],
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}
Best Practices
Prompt Engineering
- Be Specific: Clear instructions lead to better results
- Provide Context: Include relevant background information
- Use Examples: Show the model what you want
- Iterate: Test and refine your prompts
Cost Optimization
- Use appropriate models for your task
- Implement caching for repeated queries
- Set max_tokens to control costs
- Use streaming for better UX without extra cost
Error Handling
Always implement proper error handling:
try {
const response = await client.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello' }],
});
} catch (error) {
if (error.status === 429) {
// Rate limit - implement backoff
} else if (error.status === 500) {
// Server error - retry
} else {
// Other errors
}
}