跳转到主要内容

学习高级功能

探索文档

构建真实应用

1. 聊天机器人

构建智能聊天机器人:
from openai import OpenAI

client = OpenAI(
    base_url="https://ai.megallm.io/v1",
    api_key="your-key"
)

def chatbot(user_message, history=[]):
    history.append({"role": "user", "content": user_message})

    response = client.chat.completions.create(
        model="gpt-4",
        messages=history
    )

    assistant_message = response.choices[0].message.content
    history.append({"role": "assistant", "content": assistant_message})

    return assistant_message, history

2. 内容生成器

生成博客文章、电子邮件或社交媒体内容:
def generate_content(topic, content_type="blog"):
    prompts = {
        "blog": f"写一篇关于 {topic} 的综合博客文章",
        "email": f"写一封关于 {topic} 的专业电子邮件",
        "tweet": f"写一条关于 {topic} 的引人入胜的推文"
    }

    response = client.chat.completions.create(
        model="claude-3.5-sonnet",
        messages=[{"role": "user", "content": prompts[content_type]}],
        temperature=0.7
    )

    return response.choices[0].message.content

3. 代码助手

构建编程助手:
def code_assistant(task, language="python"):
    prompt = f"编写 {language} 代码来 {task}。包括注释和错误处理。"

    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.2  # 较低的 temperature 以获得更确定的代码
    )

    return response.choices[0].message.content

4. 数据分析器

分析数据并生成见解:
def analyze_data(data_description):
    prompt = f"""
    分析这些数据并提供见解:
    {data_description}

    提供:
    1. 关键发现
    2. 趋势
    3. 建议
    """

    response = client.chat.completions.create(
        model="claude-opus-4-1-20250805",  # 最适合分析
        messages=[{"role": "user", "content": prompt}]
    )

    return response.choices[0].message.content

最佳实践

  • GPT-4: 最适合复杂推理
  • GPT-3.5 Turbo: 快速且经济实惠
  • Claude Opus: 出色的分析和长上下文处理
  • Claude Sonnet: 平衡的性能
  • Gemini Pro: 强大的多模态能力
查看模型目录了解详细比较。
  • 从较便宜的模型开始测试
  • 使用 max_tokens 限制响应长度
  • 尽可能缓存响应
  • 使用流式传输改善感知性能
  • 在仪表板中监控使用情况
from openai import OpenAI, AuthenticationError, RateLimitError
import time

def make_request_with_retry(messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="gpt-4",
                messages=messages
            )
        except RateLimitError:
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # 指数退避
            else:
                raise
        except AuthenticationError:
            print("API 密钥无效")
            raise
  • 具体且清晰
  • 需要时提供示例
  • 使用系统消息设置上下文
  • 将复杂任务分解为步骤
  • 测试不同的 temperature 设置
  • 跟踪对话历史
  • 限制历史以避免令牌限制
  • 如需要,总结旧消息
  • 对重复内容使用提示词缓存

生产考虑因素

安全性

  • 在环境变量中存储 API 密钥
  • 永远不要将密钥提交到版本控制
  • 为开发/测试/生产使用不同的密钥
  • 定期轮换密钥
  • 监控使用异常

性能

  • 使用流式传输获得更好的用户体验
  • 在适当的地方实施缓存
  • 添加指数退避的重试逻辑
  • 监控响应时间
  • 考虑使用 webhooks 进行异步操作

监控

  • 跟踪令牌使用情况
  • 监控错误率
  • 记录 API 请求(不包含敏感数据)
  • 设置配额限制警报
  • 定期审查成本

扩展

  • 实施速率限制
  • 为高容量请求使用队列
  • 缓存常见响应
  • 考虑批量请求
  • 规划故障转移策略

加入社区

获取帮助

大多数常见问题在我们的常见问题中都有答案。
开发者文档中提供了全面的指南。
通过 support@megallm.io 向我们发送电子邮件以获取技术协助。
发现错误?在 GitHub 上报告。

有用的资源

准备好构建了吗?

今天就开始构建您的 AI 应用程序。如果您需要帮助,我们随时为您服务!