#openai
43 snippets tagged with #openai
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
Best for: chatbot UI
Generate Text Embeddings with OpenAI
Create vector embeddings for semantic search and similarity matching using text-embedding-3-small.
Best for: semantic search
RAG Pipeline (Retrieve + Augment + Generate)
Minimal RAG implementation: embed a query, retrieve top-k chunks, inject into prompt.
Best for: document Q&A
OpenAI Tool Calling (Function Calling)
Define tools for GPT to call, parse the response, execute the function, and return results.
Best for: AI agents
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
Best for: prompt chaining
DALL·E 3 Image Generation
Generate images from a text prompt using the OpenAI DALL·E 3 API and return a URL.
Best for: AI art generation
OpenAI Structured Output with Zod
Force GPT-4o to return valid JSON matching a Zod schema using response_format structured output.
Best for: data extraction
Content Moderation with OpenAI
Check user input for harmful content using the OpenAI Moderation API before processing.
Best for: user input safety
Next.js AI Streaming Route Handler
Stream OpenAI responses from a Next.js App Router route handler using the Vercel AI SDK.
Best for: AI chatbot backend
OpenAI Assistants API with Threads
Create persistent conversation threads with OpenAI Assistants API for stateful multi-turn interactions.
Best for: Customer support bots
Token Counter with Tiktoken
Count tokens and estimate costs for OpenAI API calls using the tiktoken tokenizer library.
Best for: Cost estimation
OpenAI Text-to-Speech
Generate natural speech audio from text using OpenAI TTS API with multiple voice options and formats.
Best for: Audiobook generation
Batch Embeddings Processing
Generate embeddings for large document sets in batches with rate limiting and progress tracking.
Best for: Indexing large document collections for search
OpenAI Structured Output with Pydantic
Force GPT to return validated JSON matching a Pydantic schema.
Best for: Review analysis
OpenAI Function Calling / Tool Use
Let GPT call your functions by defining tool schemas and handling responses.
Best for: AI agents
Stream LLM Chat Responses
Stream OpenAI chat completions token-by-token for real-time UI updates.
Best for: Chat UIs
Prepare a Fine-Tuning Dataset for OpenAI
Format, validate, and upload training data for OpenAI model fine-tuning.
Best for: Model customization
OpenAI Vision API Image Analysis
Analyze images using GPT-4o vision capabilities with base64 and URL inputs.
Best for: image captioning
Async OpenAI Client in Python
Use the AsyncOpenAI client with asyncio to run concurrent chat completions without blocking.
Best for: concurrent LLM calls
OpenAI Batch API for Cost Reduction
Submit large workloads via the OpenAI Batch API for 50% cost reduction with async processing.
Best for: batch inference
Prepare Fine-Tuning Dataset for OpenAI
Build, validate, and upload a JSONL fine-tuning dataset for OpenAI GPT fine-tuning.
Best for: model customization
Whisper Audio Transcription Pipeline
Transcribe audio files to text using OpenAI Whisper API with language detection and timestamps.
Best for: meeting transcription
OpenAI DALL-E Image Generation
Generate and save images using the DALL-E 3 API with quality and style control.
Best for: AI image creation
LLM Retry with Model Fallback
Add resilient retry logic with exponential backoff and automatic model fallback for LLM calls.
Best for: production resilience
OpenAI Content Moderation API
Screen user-generated content for policy violations using the OpenAI moderation endpoint.
Best for: content safety
OpenAI Realtime API WebSocket
Connect to the OpenAI Realtime API via WebSocket for low-latency voice and text streaming.
Best for: voice AI
OpenAI Assistants API with File Search
Create a persistent AI assistant with file search capability using the Assistants API v2.
Best for: document Q&A
Token Counting with tiktoken
Count tokens, split text by token limits, and estimate API costs using the tiktoken library.
Best for: cost estimation
OpenAI JSON Mode Responses
Force JSON output from OpenAI models using response_format for reliable structured responses.
Best for: structured AI responses
Cache Embeddings in Redis
Cache expensive embedding API calls in Redis to avoid redundant computation and reduce costs.
Best for: cost reduction
OpenAI GPT-4 Vision Image Analysis
Analyse images from URLs or base64 with GPT-4 Vision for structured visual understanding.
Best for: visual Q&A
OpenAI Streaming with SSE in FastAPI
Stream OpenAI responses as Server-Sent Events from a FastAPI endpoint.
Best for: streaming AI APIs
OpenAI Function Calling with Pydantic
Define type-safe tools for OpenAI function calling using Pydantic models and auto-serialization.
Best for: structured tool calling
Batch Embedding Large Text Corpora
Embed thousands of documents efficiently by batching requests to the OpenAI Embeddings API.
Best for: corpus embedding
OpenAI Structured Outputs with JSON Schema
Use OpenAI's strict JSON schema mode to guarantee valid structured output from any model.
Best for: entity extraction
Multimodal RAG with Images and Text
Build a multimodal RAG pipeline that retrieves and answers questions about image+text documents.
Best for: visual document Q&A
GPT PDF Summarisation Pipeline
Extract text from PDFs and summarise each section using map-reduce with the OpenAI API.
Best for: document summarisation
Parallel Tool Calls with OpenAI
Execute multiple tool calls in parallel when OpenAI returns multiple function calls in one response.
Best for: parallel function calls
Prompt Caching with OpenAI API
Reduce costs by up to 50% using OpenAI's automatic prompt caching for repeated context prefixes.
Best for: cost reduction
Real-Time Translation Pipeline with OpenAI
Build a language detection and translation pipeline using GPT for multi-language support.
Best for: multilingual apps
Manual OpenAI Agent Loop in Python
Implement a bare-metal AI agent loop with tool execution and conversation management without frameworks.
Best for: custom agents
Stream OpenAI Responses with Tool Calls
Handle streaming responses that include tool calls by accumulating delta chunks from the OpenAI API.
Best for: streaming tool calls
OpenAI Text-to-Speech Synthesis
Convert text to natural-sounding speech using the OpenAI TTS API with voice selection and streaming.
Best for: text-to-speech