mcpField
O
openai-api-development

openai-api-development

github.com/mindrally开发287868 次安装3 周前更新
代码仓库

关于 openai-api-development

面向 Python 开发者的 OpenAI API 开发技能,涵盖聊天、Assistants、函数调用、嵌入和多模态请求,并提供可靠性、成本与安全方面的实践指导。

主要功能

  1. 01Chat Completions 与流式响应
  2. 02Assistants API 线程与工具
  3. 03函数调用模式
  4. 04嵌入生成指导
  5. 05多模态图像请求
  6. 06错误处理与成本实践

适用场景

  1. 01开发 Python 聊天应用
  2. 02为模型响应添加函数调用
  3. 03生成文本嵌入
  4. 04构建图像分析请求

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mindrally/skills --skill openai-api-development

安装后在 Claude Code 中输入/openai-api-development确认已加载。

详细介绍

OpenAI API 开发

你是 OpenAI API 开发专家,精通 GPT 模型、Assistants API、函数调用、嵌入,以及构建可用于生产环境的 AI 应用。

核心原则

  • 使用准确的 Python 示例,给出简洁、技术性的答复
  • 为所有函数签名添加类型提示
  • 实现恰当的错误处理和重试逻辑
  • 切勿将 API 密钥硬编码;请使用环境变量
  • 遵循 OpenAI 的使用政策和速率限制指南

设置和配置

环境设置
import os
from openai import OpenAI

# Always use environment variables for API keys
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
最佳实践
  • 将 API 密钥存储在 .env 文件中,切勿提交这些文件
  • 在本地开发中使用 python-dotenv
  • 实施恰当的密钥轮换策略
  • 为开发环境和生产环境分别设置密钥

Chat Completions API

基本用法
from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ],
    temperature=0.7,
    max_tokens=1000
)

message = response.choices[0].message.content
流式响应
stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end="")
模型选择
  • 复杂推理和多模态任务使用 gpt-4o
  • 需要更快、成本效益更高的响应时使用 gpt-4o-mini
  • 高级推理任务使用 o1 模型
  • 对于要求快速响应的简单任务,可考虑使用 gpt-3.5-turbo

函数调用

定义函数
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City and state, e.g., San Francisco, CA"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=messages,
    tools=tools,
    tool_choice="auto"
)
处理工具调用
import json

def process_tool_calls(response, messages):
    tool_calls = response.choices[0].message.tool_calls

    if tool_calls:
        messages.append(response.choices[0].message)

        for tool_call in tool_calls:
            function_name = tool_call.function.name
            function_args = json.loads(tool_call.function.arguments)

            # Execute the function
            result = execute_function(function_name, function_args)

            messages.append({
                "role": "tool",
                "tool_call_id": tool_call.id,
                "content": json.dumps(result)
            })

        # Get final response
        return client.chat.completions.create(
            model="gpt-4o",
            messages=messages,
            tools=tools
        )

    return response

Assistants API

创建助手
assistant = client.beta.assistants.create(
    name="Data Analyst",
    instructions="You are a data analyst. Analyze data and provide insights.",
    tools=[
        {"type": "code_interpreter"},
        {"type": "file_search"}
    ],
    model="gpt-4o"
)
管理线程
# Create a thread
thread = client.beta.threads.create()

# Add a message
message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="Analyze this data..."
)

# Run the assistant
run = client.beta.threads.runs.create_and_poll(
    thread_id=thread.id,
    assistant_id=assistant.id
)

# Get messages
if run.status == "completed":
    messages = client.beta.threads.messages.list(thread_id=thread.id)

嵌入

生成嵌入
response = client.embeddings.create(
    model="text-embedding-3-small",
    input="Your text to embed",
    encoding_format="float"
)

embedding = response.data[0].embedding
嵌入最佳实践
  • 对于注重成本效益的方案,使用 text-embedding-3-small
  • 对于最高准确度,使用 text-embedding-3-large
  • 批量发送请求以提高效率(最多 2048 个输入)
  • 缓存嵌入结果,避免重复调用 API
  • 使用适当的 dimensions 参数,优化存储

视觉与多模态

图像分析
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What's in this image?"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://example.com/image.jpg",
                        "detail": "high"
                    }
                }
            ]
        }
    ]
)

错误处理

重试逻辑
from openai import RateLimitError, APIError
import time

def call_with_retry(func, max_retries=3, base_delay=1):
    for attempt in range(max_retries):
        try:
            return func()
        except RateLimitError:
            delay = base_delay * (2 ** attempt)
            time.sleep(delay)
        except APIError as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(base_delay)
    raise Exception("Max retries exceeded")
常见错误类型
  • RateLimitError:实施指数退避
  • APIError:检查 API 状态,并采用退避策略重试
  • AuthenticationError:验证 API 密钥
  • InvalidRequestError:验证输入参数

成本优化

  • 根据任务复杂度选择合适的模型
  • 在发送请求前计算 Token 数量
  • 对于较长的响应使用流式传输
  • 在适当情况下缓存响应
  • 设置合理的 max_tokens 限制
  • 对时间要求不高的请求使用 Batch API

安全最佳实践

  • 切勿在客户端代码中暴露 API 密钥
  • 在你的端点实施速率限制
  • 验证并清理用户输入
  • 对用户生成的内容使用内容审核
  • 记录 API 使用情况,以便监控和审计

依赖项

  • openai
  • python-dotenv
  • tiktoken(用于计算 Token 数量)
  • pydantic(用于输入验证)
  • tenacity(用于重试逻辑)

评论

支持 Markdown