OpenAI API 快速入门
The OpenAI API gives you programmatic access to GPT-4o and other models. Sign up at platform.openai.com and get your API key.
Install the package: pip install openai. Store your API key in an environment variable, never in code.
基本设置和第一次请求
Here is the basic setup: import the OpenAI client, create an instance with your API key, then call chat.completions.create with your model and messages.
The messages array includes system prompts (setting behavior) and user messages (the actual request). The response contains the generated text.
流式响应:提升用户体验
Streaming lets you show responses as they are generated rather than waiting for the full response. This creates a better user experience for chat applications.
To stream, add stream=True to your request and iterate over the response chunks, displaying each piece as it arrives.
函数调用:获取结构化数据
Function calling lets GPT extract structured data from conversations and trigger external actions. Define functions with names, descriptions, and parameter schemas.
When the model determines a function should be called, it returns the function name and arguments rather than a text response.
错误处理最佳实践
Always handle API errors gracefully. Implement retry logic with exponential backoff for rate limits. Use try/except blocks around all API calls.
Monitor response times and error rates. Set up alerts for unusual patterns that might indicate issues.
成本优化策略
Use GPT-4o-mini for simple tasks and reserve GPT-4o for complex reasoning. Cache common responses to avoid repeated API calls.
Set sensible max_tokens limits and monitor your usage through the OpenAI dashboard. A typical system routes 80% of requests to the mini model.
(中文版基于英文内容翻译整理。如需完整原文,请切换至英文版查看。)