AI API Integration in Practice: Building Your First AI Feature with Claude/OpenAI API

The barrier to AI API integration has dropped dramatically by 2026 — a developer with basic programming skills can embed AI capabilities into their own web application in an afternoon. But achieving production-ready (not just demo-level) quality requires understanding a series of engineering details: streaming, error handling, cost control, and prompt management. This is a complete AI API integration guide for web developers.

Which API to Choose

OpenAI API: Most mature ecosystem, widest SDK support (Python, Node.js, Go, Java, etc.) — the default starting point for most developers. GPT-4o is the optimal cost/capability main model; Mini version suits cost-sensitive scenarios.

Anthropic API (Claude): Outstanding long-text processing and coding capability — often the better choice for applications handling large contexts (document analysis, code review), with a good reputation for API stability.

Price reference (2026): GPT-4o ~$5/million input tokens, $15/million output tokens; Claude Sonnet ~$3/million input, $15/million output; GPT-4o Mini ~$0.15/$0.60 — for high-frequency lightweight tasks, the Mini tier cost advantage is extremely significant. API price comparison.

Basic Integration (Python Example)

from anthropic import Anthropic

client = Anthropic()

def analyze_document(document_text: str, question: str) -> str: message = client.messages.create( model="claude-sonnet-4-6", max_tokens=1024, messages=[ { "role": "user", "content": f"Document content:\n{document_text}\n\nQuestion: {question}" } ] ) return message.content[0].text

# Usage example result = analyze_document("Contract text...", "What are Party A's main obligations?")

Streaming Responses: The Key to User Experience

For AI output visible to users (chat interfaces, document generation), streaming is a must-implement feature — letting users see AI “typing” rather than waiting several seconds for all text to appear at once.

# Streaming example
with client.messages.stream(
 model="claude-sonnet-4-6",
 max_tokens=1024,
 messages=[{"role": "user", "content": prompt}]
) as stream:
 for text in stream.text_stream:
 print(text, end="", flush=True)

Error Handling and Retry Strategy

Error types that must be handled in production: rate limits (429 Rate Limit), service unavailability (529 Overloaded), timeouts. The standard handling pattern is exponential backoff retry: first failure wait 1 second, second wait 2 seconds, third wait 4 seconds… typically capped at 5 retries.

Core Cost Control Methods

Caching (Prompt Caching): For requests with large amounts of unchanging content (system prompts, long documents), Anthropic’s Prompt Caching can reduce costs on repeated portions by 90%. Model tiering: Simple tasks (classification, summarization) use Mini/Haiku; complex reasoning uses Sonnet/GPT-4o; cost-extreme cases use open-source models (locally deployed Llama 4/Qwen 3). Output length control: Explicitly limit “response to under 200 words” in system prompts to prevent AI from generating content without bounds.

上一篇 Claude vs Codex vs Cursor:2026年开发者的真实差异
下一篇 AI 辅助写论文:哪些用法合规,哪些是学术不端(2026 视角)