当前位置:首页 > AI > 正文内容

ChatGPT API 开发实战 - 从入门到商业化应用

廖万里11小时前AI3

# ChatGPT API 开发实战 - 从入门到商业化应用

> OpenAI 的 ChatGPT API 是构建 AI 应用的核心能力。本文从 API 基础到实战项目,带你掌握 ChatGPT API 开发的完整流程。

---

🚀 快速开始

获取 API Key

1. 访问 https://platform.openai.com/api-keys 2. 创建新的 API Key 3. 保存好 Key(只显示一次)

安装 SDK

`bash pip install openai `

第一个请求

`python from openai import OpenAI

client = OpenAI(api_key="your-api-key")

response = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "user", "content": "你好,请介绍一下你自己"} ] )

print(response.choices[0].message.content) `

---

📚 核心概念

模型选择

| 模型 | 特点 | 价格 | 适用场景 | |------|------|------|----------| | gpt-4o | 最新最强 | $5/1M tokens | 复杂任务 | | gpt-4o-mini | 高性价比 | $0.15/1M tokens | 日常使用 | | gpt-4-turbo | 长文本 | $10/1M tokens | 文档分析 | | gpt-3.5-turbo | 便宜快速 | $0.5/1M tokens | 简单对话 |

消息格式

`python messages = [ {"role": "system", "content": "你是一个专业的Python工程师"}, {"role": "user", "content": "如何读取Excel文件?"}, {"role": "assistant", "content": "可以使用pandas库..."}, {"role": "user", "content": "能举个例子吗?"} ] `

Token 计算

`python import tiktoken

def count_tokens(text, model="gpt-4o-mini"): encoding = tiktoken.encoding_for_model(model) return len(encoding.encode(text))

text = "这是一段需要计算token数量的文本" print(f"Token数量: {count_tokens(text)}") `

---

💡 进阶技巧

1. 流式输出

实时显示 AI 回复,提升用户体验:

`python def chat_stream(prompt): stream = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], stream=True ) full_response = "" for chunk in stream: if chunk.choices[0].delta.content: content = chunk.choices[0].delta.content print(content, end="", flush=True) full_response += content return full_response

# 使用示例 chat_stream("写一首关于春天的诗") `

2. 函数调用(Function Calling)

让 AI 调用你定义的函数:

`python import json

# 定义可用函数 tools = [ { "type": "function", "function": { "name": "get_weather", "description": "获取指定城市的天气", "parameters": { "type": "object", "properties": { "city": {"type": "string", "description": "城市名称"} }, "required": ["city"] } } } ]

def get_weather(city): # 实际应用中调用天气API return {"city": city, "temperature": 25, "weather": "晴天"}

# 对话 response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "北京今天天气怎么样?"}], tools=tools )

# 处理函数调用 if response.choices[0].message.tool_calls: tool_call = response.choices[0].message.tool_calls[0] if tool_call.function.name == "get_weather": args = json.loads(tool_call.function.arguments) result = get_weather(args["city"]) print(f"北京天气: {result['weather']}, 温度: {result['temperature']}°C") `

3. 多轮对话管理

维护对话历史:

`python class ChatSession: def __init__(self, system_prompt="你是一个有帮助的AI助手"): self.messages = [{"role": "system", "content": system_prompt}] def chat(self, user_input): self.messages.append({"role": "user", "content": user_input}) response = client.chat.completions.create( model="gpt-4o-mini", messages=self.messages ) assistant_message = response.choices[0].message.content self.messages.append({"role": "assistant", "content": assistant_message}) return assistant_message def clear(self): self.messages = [self.messages[0]] # 保留system消息

# 使用示例 session = ChatSession("你是一个Python专家") print(session.chat("如何读取CSV文件?")) print(session.chat "能详细解释一下吗?")) `

4. 图片理解(Vision)

分析图片内容:

`python import base64

def analyze_image(image_path, question): with open(image_path, "rb") as f: image_data = base64.b64encode(f.read()).decode() response = client.chat.completions.create( model="gpt-4o", messages=[ { "role": "user", "content": [ {"type": "text", "text": question}, { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{image_data}" } } ] } ] ) return response.choices[0].message.content

# 使用示例 result = analyze_image("screenshot.png", "这张图片显示了什么?") print(result) `

---

🛠️ 实战项目:智能客服机器人

结合以上技巧,构建一个完整的客服机器人:

`python from openai import OpenAI import json from datetime import datetime

class CustomerServiceBot: def __init__(self, api_key, company_info): self.client = OpenAI(api_key=api_key) self.company_info = company_info self.system_prompt = f"""你是一个专业的客服机器人,代表 {company_info['name']}。

公司信息:

  • 名称:{company_info['name']}
  • 业务:{company_info['business']}
  • 联系方式:{company_info['contact']}
回答要求: 1. 友好专业 2. 简洁明了 3. 不确定的问题引导联系人工客服 """ self.messages = [{"role": "system", "content": self.system_prompt}] # 可用工具 self.tools = [ { "type": "function", "function": { "name": "check_order", "description": "查询订单状态", "parameters": { "type": "object", "properties": { "order_id": {"type": "string", "description": "订单号"} }, "required": ["order_id"] } } }, { "type": "function", "function": { "name": "transfer_human", "description": "转人工客服", "parameters": { "type": "object", "properties": { "reason": {"type": "string", "description": "转接原因"} }, "required": ["reason"] } } } ] def check_order(self, order_id): # 模拟订单查询 orders = { "12345": {"status": "已发货", "express": "顺丰", "tracking": "SF123456"}, "67890": {"status": "处理中", "express": None, "tracking": None} } return orders.get(order_id, {"status": "未找到订单"}) def chat(self, user_input): self.messages.append({"role": "user", "content": user_input}) response = self.client.chat.completions.create( model="gpt-4o-mini", messages=self.messages, tools=self.tools ) # 处理工具调用 if response.choices[0].message.tool_calls: tool_call = response.choices[0].message.tool_calls[0] func_name = tool_call.function.name args = json.loads(tool_call.function.arguments) if func_name == "check_order": result = self.check_order(args["order_id"]) return f"订单查询结果:{result}" elif func_name == "transfer_human": return f"正在为您转接人工客服,原因:{args['reason']}" assistant_message = response.choices[0].message.content self.messages.append({"role": "assistant", "content": assistant_message}) return assistant_message

# 使用示例 bot = CustomerServiceBot( api_key="your-api-key", company_info={ "name": "万策云网络工作室", "business": "AI数字人、网站建设、系统开发", "contact": "电话: 18811555785, 邮箱: kkkliao@88.com" } )

print(bot.chat("你们公司做什么业务的?")) print(bot.chat("帮我查一下订单12345的状态")) `

---

⚠️ 常见问题与解决方案

1. Token 超限

`python # 解决方案:截断历史对话 def truncate_messages(messages, max_tokens=4000): total = 0 truncated = [] for msg in reversed(messages): tokens = count_tokens(msg["content"]) if total + tokens > max_tokens: break truncated.insert(0, msg) total += tokens return truncated `

2. 请求超时

`python # 解决方案:设置超时和重试 from tenacity import retry, stop_after_attempt, wait_exponential

@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10)) def chat_with_retry(prompt): return client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], timeout=30 ) `

3. 成本控制

`python # 解决方案:使用缓存 import hashlib

cache = {}

def chat_with_cache(prompt): key = hashlib.md5(prompt.encode()).hexdigest() if key in cache: return cache[key] response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}] ) cache[key] = response.choices[0].message.content return cache[key] `

---

💰 商业化建议

1. 选择合适的模型:简单任务用 gpt-4o-mini,复杂任务用 gpt-4o 2. 实现缓存机制:相同问题不重复请求 3. 监控 API 用量:设置预算告警 4. 优化提示词:减少无效 token 消耗 5. 考虑备用方案:API 故障时降级处理

---

📊 成本估算

假设每天处理 1000 次请求,每次平均 500 tokens:

  • gpt-4o-mini:1000 × 500 × 30 = 15M tokens/月 → $2.25/月
  • gpt-4o:同样用量 → $75/月
选择合适的模型能节省 97% 的成本!

---

> 掌握 ChatGPT API,让你的应用拥有 AI 大脑! > > 下一篇预告:DALL·E 3 API 实战 - AI 绘图自动化

---

作者:廖万里 发布时间:2026年3月16日

本文链接:https://www.kkkliao.cn/?id=642 转载需授权!

分享到:

版权声明:本文由廖万里的博客发布,如需转载请注明出处。


发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。