{"meta":{"title":"处理 API 速率限制","intro":"副驾驶聊天 可以通过建议检测速率限制并实现重试逻辑的代码，来帮助处理 API 速率限制问题。","product":"GitHub Copilot","breadcrumbs":[{"href":"/zh/copilot","title":"GitHub Copilot"},{"href":"/zh/copilot/tutorials","title":"教程"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook","title":"GitHub Copilot Chat 指南"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook/debug-errors","title":"调试中出现的错误"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook/debug-errors/handle-api-rate-limits","title":"处理 API 速率限制"}],"documentType":"article"},"body":"# 处理 API 速率限制\n\n副驾驶聊天 可以通过建议检测速率限制并实现重试逻辑的代码，来帮助处理 API 速率限制问题。\n\n向 API 发出请求时，通常会遇到速率限制的情况，即限制你在特定时间段内可以进行的调用次数。 GitHub Copilot 聊天功能 可以通过建议检测速率限制响应并在延迟后自动重试请求的代码，帮助你处理这些限制。\n\n## 示例方案\n\n以下 Python 代码从外部 API 提取天气数据。 如果 API 存在速率限制，那么当超出限制时，请求可能会失败，而你的应用可能需要通过实现重试逻辑来妥善处理这些响应。\n\n```python id=rate-limit-example\nfrom flask import Flask, request\nimport requests\n\napp = Flask(__name__)\n\nWEATHER_API_URL = \"https://api.example.com/weather\"\n\n@app.route('/get_weather', methods=['GET'])\ndef get_weather():\n    city = request.args.get('city')\n    # Simulate an API request to the external weather service\n    response = requests.get(WEATHER_API_URL, params={\"city\": city})\n    weather_data = response.json()\n\n    return weather_data\n```\n\n## 示例提示\n\n```copilot copy prompt ref=rate-limit-example\nHow can I handle API rate limits within get_weather().\n```\n\n## 示例响应\n\n> \\[!NOTE] 以下响应是示例。 副驾驶聊天 的回答是不确定的，因此你可能会得到与这里所显示的不同的回答。\n\nCopilot 可能会建议实现带有指数退避的重试机制的代码，以限制重试尝试的频率。\n\n例如：\n\n```python\nimport requests\nfrom flask import Flask, request\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\n\napp = Flask(__name__)\n\nWEATHER_API_URL = \"https://api.example.com/weather\"\n\ndef requests_retry_session(\n    retries=3,\n    backoff_factor=0.3,\n    status_forcelist=(500, 502, 504),\n    session=None,\n):\n    session = session or requests.Session()\n    retry = Retry(\n        total=retries,\n        read=retries,\n        connect=retries,\n        backoff_factor=backoff_factor,\n        status_forcelist=status_forcelist,\n    )\n    adapter = HTTPAdapter(max_retries=retry)\n    session.mount(\"http://\", adapter)\n    session.mount(\"https://\", adapter)\n    return session\n\n@app.route('/get_weather', methods=['GET'])\ndef get_weather():\n    city = request.args.get('city')\n    try:\n        response = requests_retry_session().get(WEATHER_API_URL, params={\"city\": city})\n        response.raise_for_status()\n        weather_data = response.json()\n    except requests.exceptions.RequestException as e:\n        return {\"error\": str(e)}, 500\n\n    return weather_data\n```\n\n在这个示例中，Copilot 的建议包括设置一个重试会话，以便当请求由于特定状态代码（500、502、504）而失败时，代码能够自动重试这些请求。\n`backoff_factor` 会逐渐增加重试之间的延迟，有助于避免进一步超出 API 的速率限制。\n\n## 其他阅读材料\n\n* [GitHub Copilot 对话助手的提示设计](/zh/copilot/using-github-copilot/prompt-engineering-for-github-copilot)\n* [使用 GitHub Copilot 的最佳做法](/zh/copilot/using-github-copilot/best-practices-for-using-github-copilot)"}