Cookbook

Ready-to-use code recipes and implementation patterns for common use cases

Full Stack
Intermediate
Real-time Chat Application
15 min
RunAs Team
4.8(124)
Build a complete chat application with WebSocket support and message history
websocket
chat
real-time
react
// Real-time chat with RunAs AI
import { RunAsAI } from '@runas/ai-sdk'
import { WebSocket } from 'ws'

const client = new RunAsAI({
  apiKey: process.env.RUNAS_API_KEY
})

// Initialize WebSocket connection
const ws = new WebSocket('wss://api.runas.ai/chat')

ws.on('message', async (data) => {
  const message = JSON.parse(data)
  
  // Generate AI response
  const response = await client.chat.completions.create({
    messages: [{ role: 'user', content: message.text }],
    model: 'gpt-4',
    stream: true
  })
  
  // Stream response back to client
  for await (const chunk of response) {
    ws.send(JSON.stringify({
      type: 'response',
      content: chunk.choices[0]?.delta?.content || ''
    }))
  }
})
Data Processing
Advanced
Document Analysis Pipeline
20 min
Data Team
4.9(89)
Extract insights from documents using AI-powered analysis and summarization
document
analysis
nlp
python
# Document analysis with RunAs AI
import runas_ai
from pathlib import Path

client = runas_ai.Client(api_key="your-api-key")

def analyze_document(file_path):
    # Read document
    document = Path(file_path).read_text()
    
    # Extract key information
    analysis = client.analyze.document({
        "text": document,
        "tasks": [
            "summarize",
            "extract_entities",
            "sentiment_analysis",
            "key_topics"
        ]
    })
    
    return {
        "summary": analysis.summary,
        "entities": analysis.entities,
        "sentiment": analysis.sentiment,
        "topics": analysis.topics
    }

# Process multiple documents
results = []
for doc in Path("documents/").glob("*.txt"):
    result = analyze_document(doc)
    results.append(result)
Backend
Intermediate
API Rate Limiting with Redis
12 min
Backend Team
4.7(156)
Implement robust rate limiting for your API using Redis and sliding window
rate-limiting
redis
api
nodejs
// Rate limiting with Redis
const redis = require('redis')
const client = redis.createClient()

class RateLimiter {
  constructor(windowMs = 60000, maxRequests = 100) {
    this.windowMs = windowMs
    this.maxRequests = maxRequests
  }
  
  async checkLimit(userId) {
    const now = Date.now()
    const window = Math.floor(now / this.windowMs)
    const key = `rate_limit:${userId}:${window}`
    
    const current = await client.incr(key)
    
    if (current === 1) {
      await client.expire(key, Math.ceil(this.windowMs / 1000))
    }
    
    return {
      allowed: current <= this.maxRequests,
      remaining: Math.max(0, this.maxRequests - current),
      resetTime: (window + 1) * this.windowMs
    }
  }
}

// Usage in Express middleware
const limiter = new RateLimiter(60000, 100) // 100 requests per minute

app.use(async (req, res, next) => {
  const result = await limiter.checkLimit(req.user.id)
  
  if (!result.allowed) {
    return res.status(429).json({
      error: 'Rate limit exceeded',
      resetTime: result.resetTime
    })
  }
  
  res.set({
    'X-RateLimit-Remaining': result.remaining,
    'X-RateLimit-Reset': result.resetTime
  })
  
  next()
})
Serverless
Beginner
Serverless AI Image Generator
10 min
DevOps Team
4.6(203)
Deploy an AI image generation service using serverless functions
serverless
images
ai
vercel
// Serverless AI image generation
import { RunAsAI } from '@runas/ai-sdk'

const client = new RunAsAI({
  apiKey: process.env.RUNAS_API_KEY
})

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' })
  }
  
  const { prompt, size = '1024x1024', style = 'natural' } = req.body
  
  try {
    const response = await client.images.generate({
      prompt,
      size,
      style,
      n: 1
    })
    
    const imageUrl = response.data[0].url
    
    res.status(200).json({
      success: true,
      imageUrl,
      prompt
    })
  } catch (error) {
    res.status(500).json({
      error: 'Failed to generate image',
      message: error.message
    })
  }
}
Internationalization
Intermediate
Multi-language Content Translation
18 min
I18n Team
4.5(78)
Automatically translate content across multiple languages with context awareness
translation
i18n
multilingual
content
// Multi-language translation service
import { RunAsAI } from '@runas/ai-sdk'

class TranslationService {
  constructor(apiKey) {
    this.client = new RunAsAI({ apiKey })
    this.supportedLanguages = [
      'en', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'ja', 'ko', 'zh'
    ]
  }
  
  async translateContent(content, targetLanguages, context = '') {
    const translations = {}
    
    for (const lang of targetLanguages) {
      if (!this.supportedLanguages.includes(lang)) {
        throw new Error(`Unsupported language: ${lang}`)
      }
      
      const response = await this.client.chat.completions.create({
        messages: [
          {
            role: 'system',
            content: `You are a professional translator. Translate the following content to ${lang} while maintaining context and tone. Context: ${context}`
          },
          {
            role: 'user',
            content: content
          }
        ],
        model: 'gpt-4'
      })
      
      translations[lang] = response.choices[0].message.content
    }
    
    return translations
  }
  
  async batchTranslate(contents, targetLanguages) {
    const results = []
    
    for (const content of contents) {
      const translations = await this.translateContent(
        content.text,
        targetLanguages,
        content.context
      )
      
      results.push({
        id: content.id,
        original: content.text,
        translations
      })
    }
    
    return results
  }
}

// Usage example
const translator = new TranslationService(process.env.RUNAS_API_KEY)

const content = [
  {
    id: 1,
    text: "Welcome to our platform!",
    context: "Homepage greeting"
  },
  {
    id: 2,
    text: "Your order has been confirmed.",
    context: "E-commerce confirmation"
  }
]

const results = await translator.batchTranslate(
  content,
  ['es', 'fr', 'de']
)
Developer Tools
Advanced
Smart Code Review Assistant
25 min
DevTools Team
4.9(167)
Automated code review system that provides intelligent feedback and suggestions
code-review
automation
github
ci-cd
// Smart code review assistant
import { RunAsAI } from '@runas/ai-sdk'
import { Octokit } from '@octokit/rest'

class CodeReviewAssistant {
  constructor(runasApiKey, githubToken) {
    this.ai = new RunAsAI({ apiKey: runasApiKey })
    this.github = new Octokit({ auth: githubToken })
  }
  
  async reviewPullRequest(owner, repo, pullNumber) {
    // Get PR diff
    const { data: pr } = await this.github.pulls.get({
      owner,
      repo,
      pull_number: pullNumber
    })
    
    const { data: files } = await this.github.pulls.listFiles({
      owner,
      repo,
      pull_number: pullNumber
    })
    
    const reviews = []
    
    for (const file of files) {
      if (file.patch) {
        const review = await this.reviewFile(file)
        reviews.push(review)
      }
    }
    
    // Post review comments
    await this.postReviewComments(owner, repo, pullNumber, reviews)
    
    return reviews
  }
  
  async reviewFile(file) {
    const response = await this.ai.chat.completions.create({
      messages: [
        {
          role: 'system',
          content: `You are an expert code reviewer. Analyze the following code changes and provide constructive feedback focusing on:
          - Code quality and best practices
          - Potential bugs or security issues
          - Performance improvements
          - Maintainability concerns
          
          Format your response as JSON with 'issues' array containing objects with 'line', 'type', 'message', and 'suggestion' fields.`
        },
        {
          role: 'user',
          content: `File: ${file.filename}
          
Changes:
${file.patch}`
        }
      ],
      model: 'gpt-4'
    })
    
    try {
      return {
        filename: file.filename,
        issues: JSON.parse(response.choices[0].message.content).issues
      }
    } catch (error) {
      return {
        filename: file.filename,
        issues: []
      }
    }
  }
  
  async postReviewComments(owner, repo, pullNumber, reviews) {
    const comments = []
    
    for (const review of reviews) {
      for (const issue of review.issues) {
        comments.push({
          path: review.filename,
          line: issue.line,
          body: `**${issue.type}**: ${issue.message}

${issue.suggestion ? `**Suggestion**: ${issue.suggestion}` : ''}`
        })
      }
    }
    
    if (comments.length > 0) {
      await this.github.pulls.createReview({
        owner,
        repo,
        pull_number: pullNumber,
        event: 'COMMENT',
        comments
      })
    }
  }
}

// GitHub Action usage
const assistant = new CodeReviewAssistant(
  process.env.RUNAS_API_KEY,
  process.env.GITHUB_TOKEN
)

// Trigger on PR
if (process.env.GITHUB_EVENT_NAME === 'pull_request') {
  const { owner, repo } = process.env.GITHUB_REPOSITORY.split('/')
  const pullNumber = process.env.GITHUB_EVENT_PULL_REQUEST_NUMBER
  
  await assistant.reviewPullRequest(owner, repo, pullNumber)
}

Share Your Recipe

Have a great implementation pattern? Share it with the community