活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

掌握Python中ChatGPT函数使用技巧构建智能应用

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-24 13:20:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在人工智能快速发展的今天,将ChatGPT的能力集成到Python应用程序中已成为开发者们的重要技能。本文将详细介绍如何利用Python中的ChatGPT函数和相关库来构建各种智能应用,从基础设置到高级技巧,全面覆盖您需要了解的知识点。

1. 引言:ChatGPT与Python的强强联合

ChatGPT是由OpenAI开发的大型语言模型,它能够理解和生成人类语言,为各种应用场景提供智能对话能力。而Python作为最受欢迎的编程语言之一,拥有丰富的库和框架,使得开发者能够轻松地将ChatGPT集成到自己的应用中。

通过结合Python的灵活性和ChatGPT的智能,我们可以构建聊天机器人、内容生成工具、智能助手、代码辅助系统等各种创新应用。本文将带您深入了解这一过程,从基础设置到高级应用技巧。

2. 准备工作:环境配置与API设置

在开始使用ChatGPT函数之前,我们需要完成一些准备工作:

2.1 安装必要的库

首先,我们需要安装OpenAI的Python库,这是与ChatGPT API交互的主要工具:
  1. pip install openai
复制代码

此外,根据您的应用需求,可能还需要安装其他辅助库:
  1. pip install python-dotenv  # 用于环境变量管理
  2. pip install requests       # 用于HTTP请求
  3. pip install flask          # 用于Web应用开发
  4. pip install pandas         # 用于数据处理
复制代码

2.2 获取OpenAI API密钥

要使用ChatGPT API,您需要一个有效的API密钥:

1. 访问OpenAI官网并注册/登录您的账户
2. 转到API密钥管理页面
3. 创建一个新的API密钥

2.3 安全地存储API密钥

为了安全地管理您的API密钥,建议使用环境变量而不是直接在代码中硬编码:

创建一个.env文件:
  1. OPENAI_API_KEY=your_api_key_here
复制代码

然后在Python中加载:
  1. import os
  2. from dotenv import load_dotenv
  3. # 加载环境变量
  4. load_dotenv()
  5. # 获取API密钥
  6. api_key = os.getenv("OPENAI_API_KEY")
复制代码

3. 基础使用:调用ChatGPT API

3.1 初始化OpenAI客户端

首先,我们需要初始化OpenAI客户端:
  1. import openai
  2. # 设置API密钥
  3. openai.api_key = api_key
  4. # 或者使用新的客户端方式(推荐)
  5. from openai import OpenAI
  6. client = OpenAI(api_key=api_key)
复制代码

3.2 基本的文本生成

使用ChatGPT生成文本是最基本的功能:
  1. def generate_text(prompt, model="gpt-3.5-turbo"):
  2.     """
  3.     使用ChatGPT生成文本
  4.    
  5.     参数:
  6.         prompt (str): 提示文本
  7.         model (str): 使用的模型,默认为gpt-3.5-turbo
  8.    
  9.     返回:
  10.         str: 生成的文本
  11.     """
  12.     try:
  13.         # 使用新的客户端API
  14.         response = client.chat.completions.create(
  15.             model=model,
  16.             messages=[
  17.                 {"role": "user", "content": prompt}
  18.             ]
  19.         )
  20.         return response.choices[0].message.content
  21.     except Exception as e:
  22.         return f"发生错误: {str(e)}"
  23. # 使用示例
  24. prompt = "请解释什么是量子计算,用简单的语言。"
  25. response = generate_text(prompt)
  26. print(response)
复制代码

3.3 对话管理

ChatGPT的强大之处在于它能够维护上下文,进行多轮对话:
  1. class ChatManager:
  2.     """
  3.     管理与ChatGPT的对话
  4.     """
  5.     def __init__(self, model="gpt-3.5-turbo"):
  6.         self.model = model
  7.         self.messages = []
  8.    
  9.     def add_message(self, role, content):
  10.         """
  11.         添加消息到对话历史
  12.         
  13.         参数:
  14.             role (str): 角色,可以是"system", "user", 或"assistant"
  15.             content (str): 消息内容
  16.         """
  17.         self.messages.append({"role": role, "content": content})
  18.    
  19.     def get_response(self):
  20.         """
  21.         获取ChatGPT的响应
  22.         
  23.         返回:
  24.             str: ChatGPT的响应文本
  25.         """
  26.         try:
  27.             response = client.chat.completions.create(
  28.                 model=self.model,
  29.                 messages=self.messages
  30.             )
  31.             assistant_message = response.choices[0].message.content
  32.             self.add_message("assistant", assistant_message)
  33.             return assistant_message
  34.         except Exception as e:
  35.             return f"发生错误: {str(e)}"
  36.    
  37.     def reset(self):
  38.         """重置对话历史"""
  39.         self.messages = []
  40. # 使用示例
  41. chat = ChatManager()
  42. chat.add_message("system", "你是一个友好的助手,总是用简洁的语言回答问题。")
  43. chat.add_message("user", "你好,能告诉我Python是什么吗?")
  44. response = chat.get_response()
  45. print(response)
  46. chat.add_message("user", "能给我一个简单的Python例子吗?")
  47. response = chat.get_response()
  48. print(response)
复制代码

4. 高级技巧:提升ChatGPT应用效果

4.1 提示工程(Prompt Engineering)

有效的提示是获取高质量响应的关键。以下是一些提示工程的技巧:
  1. def get_expert_response(topic, question):
  2.     """
  3.     获取特定领域专家的回答
  4.    
  5.     参数:
  6.         topic (str): 专业领域
  7.         question (str): 问题
  8.    
  9.     返回:
  10.         str: 专家回答
  11.     """
  12.     prompt = f"""
  13.     你是一个在{topic}领域有多年经验的专家。请以专业且易于理解的方式回答以下问题:
  14.    
  15.     问题:{question}
  16.     """
  17.    
  18.     response = client.chat.completions.create(
  19.         model="gpt-3.5-turbo",
  20.         messages=[
  21.             {"role": "system", "content": "你是一个专业、有知识且乐于助人的专家。"},
  22.             {"role": "user", "content": prompt}
  23.         ]
  24.     )
  25.     return response.choices[0].message.content
  26. # 使用示例
  27. response = get_expert_response("机器学习", "什么是过拟合,如何避免它?")
  28. print(response)
复制代码
  1. def get_structured_response(prompt, output_format):
  2.     """
  3.     获取结构化的响应
  4.    
  5.     参数:
  6.         prompt (str): 提示文本
  7.         output_format (str): 期望的输出格式描述
  8.    
  9.     返回:
  10.         str: 结构化响应
  11.     """
  12.     full_prompt = f"""
  13.     {prompt}
  14.    
  15.     请按照以下格式提供你的回答:
  16.     {output_format}
  17.     """
  18.    
  19.     response = client.chat.completions.create(
  20.         model="gpt-3.5-turbo",
  21.         messages=[
  22.             {"role": "system", "content": "你是一个擅长提供结构化回答的助手。"},
  23.             {"role": "user", "content": full_prompt}
  24.         ]
  25.     )
  26.     return response.choices[0].message.content
  27. # 使用示例
  28. prompt = "分析全球变暖的主要原因和影响"
  29. format = """
  30. 1. 原因:
  31.    - 原因1:[详细说明]
  32.    - 原因2:[详细说明]
  33.    
  34. 2. 影响:
  35.    - 影响1:[详细说明]
  36.    - 影响2:[详细说明]
  37. """
  38. response = get_structured_response(prompt, format)
  39. print(response)
复制代码

4.2 流式响应

对于较长的响应,使用流式处理可以提升用户体验:
  1. def stream_response(prompt):
  2.     """
  3.     流式获取ChatGPT的响应
  4.    
  5.     参数:
  6.         prompt (str): 提示文本
  7.     """
  8.     try:
  9.         stream = client.chat.completions.create(
  10.             model="gpt-3.5-turbo",
  11.             messages=[{"role": "user", "content": prompt}],
  12.             stream=True
  13.         )
  14.         
  15.         print("ChatGPT响应:")
  16.         for chunk in stream:
  17.             if chunk.choices[0].delta.content is not None:
  18.                 print(chunk.choices[0].delta.content, end="")
  19.         print()  # 换行
  20.     except Exception as e:
  21.         print(f"发生错误: {str(e)}")
  22. # 使用示例
  23. stream_response("请详细解释人工智能的发展历史,从1950年代到现在。")
复制代码

4.3 函数调用(Function Calling)

ChatGPT可以调用外部函数,扩展其能力:
  1. # 定义一些示例函数
  2. def get_current_weather(location, unit="celsius"):
  3.     """
  4.     获取当前天气(模拟函数)
  5.    
  6.     参数:
  7.         location (str): 位置
  8.         unit (str): 温度单位,可以是"celsius"或"fahrenheit"
  9.    
  10.     返回:
  11.         dict: 天气信息
  12.     """
  13.     # 在实际应用中,这里会调用天气API
  14.     return {
  15.         "location": location,
  16.         "temperature": "25",
  17.         "unit": unit,
  18.         "description": "晴朗"
  19.     }
  20. def get_stock_price(symbol):
  21.     """
  22.     获取股票价格(模拟函数)
  23.    
  24.     参数:
  25.         symbol (str): 股票代码
  26.    
  27.     返回:
  28.         dict: 股票价格信息
  29.     """
  30.     # 在实际应用中,这里会调用股票API
  31.     return {
  32.         "symbol": symbol,
  33.         "price": "150.25",
  34.         "change": "+2.5%"
  35.     }
  36. # 定义函数描述,供ChatGPT理解
  37. functions = [
  38.     {
  39.         "name": "get_current_weather",
  40.         "description": "获取指定位置的当前天气",
  41.         "parameters": {
  42.             "type": "object",
  43.             "properties": {
  44.                 "location": {
  45.                     "type": "string",
  46.                     "description": "城市或地区名称,例如:北京、伦敦"
  47.                 },
  48.                 "unit": {
  49.                     "type": "string",
  50.                     "enum": ["celsius", "fahrenheit"],
  51.                     "description": "温度单位,默认为摄氏度"
  52.                 }
  53.             },
  54.             "required": ["location"]
  55.         }
  56.     },
  57.     {
  58.         "name": "get_stock_price",
  59.         "description": "获取指定股票的当前价格",
  60.         "parameters": {
  61.             "type": "object",
  62.             "properties": {
  63.                 "symbol": {
  64.                     "type": "string",
  65.                     "description": "股票代码,例如:AAPL, MSFT"
  66.                 }
  67.             },
  68.             "required": ["symbol"]
  69.         }
  70.     }
  71. ]
  72. def function_calling_example(prompt):
  73.     """
  74.     函数调用示例
  75.    
  76.     参数:
  77.         prompt (str): 用户输入
  78.     """
  79.     # 第一次调用,判断是否需要调用函数
  80.     response = client.chat.completions.create(
  81.         model="gpt-3.5-turbo",
  82.         messages=[{"role": "user", "content": prompt}],
  83.         functions=functions,
  84.         function_call="auto"
  85.     )
  86.    
  87.     response_message = response.choices[0].message
  88.    
  89.     # 检查是否需要调用函数
  90.     if response_message.function_call:
  91.         # 获取函数名和参数
  92.         function_name = response_message.function_call.name
  93.         function_args = json.loads(response_message.function_call.arguments)
  94.         
  95.         print(f"ChatGPT决定调用函数: {function_name}")
  96.         print(f"函数参数: {function_args}")
  97.         
  98.         # 调用相应的函数
  99.         if function_name == "get_current_weather":
  100.             function_response = get_current_weather(
  101.                 location=function_args.get("location"),
  102.                 unit=function_args.get("unit", "celsius")
  103.             )
  104.         elif function_name == "get_stock_price":
  105.             function_response = get_stock_price(symbol=function_args.get("symbol"))
  106.         
  107.         print(f"函数返回结果: {function_response}")
  108.         
  109.         # 第二次调用,将函数结果提供给ChatGPT
  110.         second_response = client.chat.completions.create(
  111.             model="gpt-3.5-turbo",
  112.             messages=[
  113.                 {"role": "user", "content": prompt},
  114.                 response_message,
  115.                 {
  116.                     "role": "function",
  117.                     "name": function_name,
  118.                     "content": json.dumps(function_response)
  119.                 }
  120.             ]
  121.         )
  122.         
  123.         return second_response.choices[0].message.content
  124.     else:
  125.         # 不需要调用函数,直接返回结果
  126.         return response_message.content
  127. # 使用示例
  128. import json
  129. prompt1 = "北京的天气怎么样?"
  130. response1 = function_calling_example(prompt1)
  131. print("\n最终回答:")
  132. print(response1)
  133. prompt2 = "苹果公司的股票价格是多少?"
  134. response2 = function_calling_example(prompt2)
  135. print("\n最终回答:")
  136. print(response2)
复制代码

4.4 错误处理和重试机制

在实际应用中,良好的错误处理和重试机制非常重要:
  1. import time
  2. from openai import RateLimitError, APIConnectionError, APIError
  3. def robust_chat_completion(messages, model="gpt-3.5-turbo", max_retries=3, initial_delay=1):
  4.     """
  5.     带有错误处理和重试机制的ChatGPT调用
  6.    
  7.     参数:
  8.         messages (list): 消息列表
  9.         model (str): 使用的模型
  10.         max_retries (int): 最大重试次数
  11.         initial_delay (float): 初始延迟时间(秒)
  12.    
  13.     返回:
  14.         str: ChatGPT的响应或错误信息
  15.     """
  16.     retry_count = 0
  17.     delay = initial_delay
  18.    
  19.     while retry_count <= max_retries:
  20.         try:
  21.             response = client.chat.completions.create(
  22.                 model=model,
  23.                 messages=messages
  24.             )
  25.             return response.choices[0].message.content
  26.         except RateLimitError:
  27.             print(f"达到速率限制,等待 {delay} 秒后重试...")
  28.             time.sleep(delay)
  29.             delay *= 2  # 指数退避
  30.             retry_count += 1
  31.         except APIConnectionError:
  32.             print(f"连接错误,等待 {delay} 秒后重试...")
  33.             time.sleep(delay)
  34.             delay *= 2
  35.             retry_count += 1
  36.         except APIError as e:
  37.             print(f"API错误: {str(e)}")
  38.             if "maximum context length" in str(e):
  39.                 return "错误:输入文本过长,请缩短后重试。"
  40.             retry_count += 1
  41.         except Exception as e:
  42.             print(f"未知错误: {str(e)}")
  43.             return f"发生错误: {str(e)}"
  44.    
  45.     return f"在 {max_retries} 次重试后仍然失败,请稍后再试。"
  46. # 使用示例
  47. messages = [
  48.     {"role": "system", "content": "你是一个有用的助手。"},
  49.     {"role": "user", "content": "请解释什么是黑洞。"}
  50. ]
  51. response = robust_chat_completion(messages)
  52. print(response)
复制代码

5. 实际应用案例

5.1 智能客服机器人
  1. class CustomerServiceBot:
  2.     """
  3.     智能客服机器人
  4.     """
  5.     def __init__(self, company_name, product_info):
  6.         self.company_name = company_name
  7.         self.product_info = product_info
  8.         self.client = OpenAI(api_key=api_key)
  9.         self.conversation_history = []
  10.         
  11.         # 初始化系统提示
  12.         system_prompt = f"""
  13.         你是{self.company_name}的客服代表。你的任务是帮助客户解决问题,回答关于产品的问题。
  14.         
  15.         产品信息:
  16.         {self.product_info}
  17.         
  18.         请始终以友好、专业的态度回答,并尽力解决客户的问题。
  19.         如果遇到无法解决的问题,请建议客户联系人工客服。
  20.         """
  21.         
  22.         self.conversation_history.append({"role": "system", "content": system_prompt})
  23.    
  24.     def respond(self, user_input):
  25.         """
  26.         回应用户输入
  27.         
  28.         参数:
  29.             user_input (str): 用户输入
  30.             
  31.         返回:
  32.             str: 机器人的回应
  33.         """
  34.         # 添加用户消息到对话历史
  35.         self.conversation_history.append({"role": "user", "content": user_input})
  36.         
  37.         try:
  38.             # 获取ChatGPT的回应
  39.             response = self.client.chat.completions.create(
  40.                 model="gpt-3.5-turbo",
  41.                 messages=self.conversation_history
  42.             )
  43.             
  44.             assistant_message = response.choices[0].message.content
  45.             
  46.             # 添加助手回应到对话历史
  47.             self.conversation_history.append({"role": "assistant", "content": assistant_message})
  48.             
  49.             return assistant_message
  50.         except Exception as e:
  51.             return f"抱歉,我遇到了一些技术问题:{str(e)}。请稍后再试或联系人工客服。"
  52.    
  53.     def reset(self):
  54.         """重置对话历史"""
  55.         self.conversation_history = []
  56.         # 重新添加系统提示
  57.         system_prompt = f"""
  58.         你是{self.company_name}的客服代表。你的任务是帮助客户解决问题,回答关于产品的问题。
  59.         
  60.         产品信息:
  61.         {self.product_info}
  62.         
  63.         请始终以友好、专业的态度回答,并尽力解决客户的问题。
  64.         如果遇到无法解决的问题,请建议客户联系人工客服。
  65.         """
  66.         self.conversation_history.append({"role": "system", "content": system_prompt})
  67. # 使用示例
  68. company_name = "智能电子公司"
  69. product_info = """
  70. 产品名称:智能手表X1
  71. 功能:心率监测、睡眠追踪、运动记录、消息通知
  72. 价格:¥1299
  73. 保修期:1年
  74. 常见问题:
  75. - 电池续航:正常使用约7天
  76. - 防水等级:IP68,可游泳
  77. - 兼容性:支持Android 8.0+和iOS 12.0+
  78. """
  79. bot = CustomerServiceBot(company_name, product_info)
  80. # 模拟客户对话
  81. print("客服机器人已启动,输入'退出'结束对话。")
  82. while True:
  83.     user_input = input("\n客户: ")
  84.     if user_input.lower() in ["退出", "exit", "quit"]:
  85.         print("客服: 感谢您的咨询,再见!")
  86.         break
  87.    
  88.     response = bot.respond(user_input)
  89.     print(f"客服: {response}")
复制代码

5.2 内容生成工具
  1. class ContentGenerator:
  2.     """
  3.     内容生成工具
  4.     """
  5.     def __init__(self):
  6.         self.client = OpenAI(api_key=api_key)
  7.    
  8.     def generate_blog_post(self, topic, target_audience, tone="informative", length="medium"):
  9.         """
  10.         生成博客文章
  11.         
  12.         参数:
  13.             topic (str): 主题
  14.             target_audience (str): 目标受众
  15.             tone (str): 语气,可以是"informative", "casual", "formal"等
  16.             length (str): 长度,可以是"short", "medium", "long"
  17.             
  18.         返回:
  19.             str: 生成的博客文章
  20.         """
  21.         length_guidelines = {
  22.             "short": "300-500字",
  23.             "medium": "500-800字",
  24.             "long": "800-1200字"
  25.         }
  26.         
  27.         prompt = f"""
  28.         请为一篇关于"{topic}"的博客文章撰写内容。
  29.         
  30.         目标受众: {target_audience}
  31.         语气: {tone}
  32.         长度要求: {length_guidelines.get(length, "500-800字")}
  33.         
  34.         请确保文章:
  35.         1. 有吸引人的标题
  36.         2. 包含简短的介绍
  37.         3. 有3-5个主要段落,每个段落有明确的主题
  38.         4. 以总结或号召性用语结束
  39.         
  40.         请直接返回文章内容,不需要额外解释。
  41.         """
  42.         
  43.         try:
  44.             response = self.client.chat.completions.create(
  45.                 model="gpt-3.5-turbo",
  46.                 messages=[
  47.                     {"role": "system", "content": "你是一个专业的内容创作者,擅长撰写引人入胜的博客文章。"},
  48.                     {"role": "user", "content": prompt}
  49.                 ]
  50.             )
  51.             return response.choices[0].message.content
  52.         except Exception as e:
  53.             return f"生成内容时出错: {str(e)}"
  54.    
  55.     def generate_social_media_posts(self, topic, platform="general", count=3):
  56.         """
  57.         生成社交媒体帖子
  58.         
  59.         参数:
  60.             topic (str): 主题
  61.             platform (str): 平台,可以是"general", "twitter", "facebook", "instagram", "linkedin"
  62.             count (int): 生成帖子数量
  63.             
  64.         返回:
  65.             list: 生成的社交媒体帖子列表
  66.         """
  67.         platform_guidelines = {
  68.             "general": "适用于大多数社交媒体平台",
  69.             "twitter": "不超过280字符,可使用话题标签",
  70.             "facebook": "可以稍长,更详细",
  71.             "instagram": "视觉友好,可使用表情符号和话题标签",
  72.             "linkedin": "专业语气,适合商业内容"
  73.         }
  74.         
  75.         prompt = f"""
  76.         请为"{topic}"创建{count}个不同的社交媒体帖子。
  77.         
  78.         平台: {platform}
  79.         平台特点: {platform_guidelines.get(platform, "适用于大多数社交媒体平台")}
  80.         
  81.         每个帖子应该:
  82.         1. 有吸引人的开头
  83.         2. 包含相关内容
  84.         3. 适合平台的特点和长度
  85.         4. 如适用,包含相关话题标签
  86.         
  87.         请以编号列表形式返回这些帖子,每个帖子之间用空行分隔。
  88.         """
  89.         
  90.         try:
  91.             response = self.client.chat.completions.create(
  92.                 model="gpt-3.5-turbo",
  93.                 messages=[
  94.                     {"role": "system", "content": "你是一个社交媒体专家,擅长创建引人注目的社交媒体内容。"},
  95.                     {"role": "user", "content": prompt}
  96.                 ]
  97.             )
  98.             
  99.             # 将返回的文本分割成单独的帖子
  100.             posts_text = response.choices[0].message.content
  101.             posts = [post.strip() for post in posts_text.split('\n\n') if post.strip()]
  102.             
  103.             return posts
  104.         except Exception as e:
  105.             return [f"生成社交媒体帖子时出错: {str(e)}"]
  106.    
  107.     def generate_product_description(self, product_name, features, target_audience, tone="persuasive"):
  108.         """
  109.         生成产品描述
  110.         
  111.         参数:
  112.             product_name (str): 产品名称
  113.             features (list): 产品特性列表
  114.             target_audience (str): 目标受众
  115.             tone (str): 语气,可以是"persuasive", "informative", "casual"等
  116.             
  117.         返回:
  118.             str: 生成的产品描述
  119.         """
  120.         features_text = "\n".join([f"- {feature}" for feature in features])
  121.         
  122.         prompt = f"""
  123.         请为以下产品撰写一个吸引人的产品描述:
  124.         
  125.         产品名称: {product_name}
  126.         
  127.         产品特性:
  128.         {features_text}
  129.         
  130.         目标受众: {target_audience}
  131.         语气: {tone}
  132.         
  133.         请确保描述:
  134.         1. 有吸引人的标题
  135.         2. 突出产品的主要优势和独特卖点
  136.         3. 针对目标受众的需求和痛点
  137.         4. 包含一个强有力的号召性用语
  138.         
  139.         请直接返回产品描述,不需要额外解释。
  140.         """
  141.         
  142.         try:
  143.             response = self.client.chat.completions.create(
  144.                 model="gpt-3.5-turbo",
  145.                 messages=[
  146.                     {"role": "system", "content": "你是一个专业的营销文案撰写人,擅长创建有说服力的产品描述。"},
  147.                     {"role": "user", "content": prompt}
  148.                 ]
  149.             )
  150.             return response.choices[0].message.content
  151.         except Exception as e:
  152.             return f"生成产品描述时出错: {str(e)}"
  153. # 使用示例
  154. generator = ContentGenerator()
  155. # 生成博客文章
  156. blog_post = generator.generate_blog_post(
  157.     topic="远程工作的优势与挑战",
  158.     target_audience="职场专业人士",
  159.     tone="informative",
  160.     length="medium"
  161. )
  162. print("\n生成的博客文章:")
  163. print(blog_post)
  164. # 生成社交媒体帖子
  165. social_posts = generator.generate_social_media_posts(
  166.     topic="环保生活方式",
  167.     platform="instagram",
  168.     count=2
  169. )
  170. print("\n生成的社交媒体帖子:")
  171. for i, post in enumerate(social_posts, 1):
  172.     print(f"\n帖子 {i}:")
  173.     print(post)
  174. # 生成产品描述
  175. product_desc = generator.generate_product_description(
  176.     product_name="智能空气净化器Pro",
  177.     features=["HEPA高效过滤", "智能空气质量监测", "手机APP远程控制", "静音模式", "节能设计"],
  178.     target_audience="注重健康的家庭用户",
  179.     tone="persuasive"
  180. )
  181. print("\n生成的产品描述:")
  182. print(product_desc)
复制代码

5.3 代码辅助工具
  1. class CodeAssistant:
  2.     """
  3.     代码辅助工具
  4.     """
  5.     def __init__(self):
  6.         self.client = OpenAI(api_key=api_key)
  7.    
  8.     def generate_code(self, description, language="python", include_comments=True):
  9.         """
  10.         根据描述生成代码
  11.         
  12.         参数:
  13.             description (str): 代码功能描述
  14.             language (str): 编程语言
  15.             include_comments (bool): 是否包含注释
  16.             
  17.         返回:
  18.             str: 生成的代码
  19.         """
  20.         prompt = f"""
  21.         请用{language}编写代码来实现以下功能:
  22.         
  23.         {description}
  24.         
  25.         {"请包含详细的注释,解释代码的工作原理。" if include_comments else ""}
  26.         
  27.         请只返回代码,不需要额外解释。
  28.         """
  29.         
  30.         try:
  31.             response = self.client.chat.completions.create(
  32.                 model="gpt-3.5-turbo",
  33.                 messages=[
  34.                     {"role": "system", "content": f"你是一个专业的{language}程序员,擅长编写清晰、高效的代码。"},
  35.                     {"role": "user", "content": prompt}
  36.                 ]
  37.             )
  38.             return response.choices[0].message.content
  39.         except Exception as e:
  40.             return f"生成代码时出错: {str(e)}"
  41.    
  42.     def explain_code(self, code, detail_level="medium"):
  43.         """
  44.         解释代码的功能和工作原理
  45.         
  46.         参数:
  47.             code (str): 要解释的代码
  48.             detail_level (str): 详细程度,可以是"basic", "medium", "detailed"
  49.             
  50.         返回:
  51.             str: 代码解释
  52.         """
  53.         detail_guidelines = {
  54.             "basic": "提供简单概述,适合初学者",
  55.             "medium": "提供中等详细程度的解释",
  56.             "detailed": "提供详细的解释,包括技术细节"
  57.         }
  58.         
  59.         prompt = f"""
  60.         请解释以下代码的功能和工作原理:
  61.         
  62.         ```python
  63.         {code}
  64.         ```
  65.         
  66.         解释详细程度: {detail_guidelines.get(detail_level, "中等详细程度")}
  67.         
  68.         请确保解释:
  69.         1. 代码的整体目的
  70.         2. 主要组件和它们的作用
  71.         3. 代码的执行流程
  72.         4. 如适用,解释任何复杂或特别值得注意的部分
  73.         """
  74.         
  75.         try:
  76.             response = self.client.chat.completions.create(
  77.                 model="gpt-3.5-turbo",
  78.                 messages=[
  79.                     {"role": "system", "content": "你是一个经验丰富的编程教练,擅长用清晰易懂的方式解释代码。"},
  80.                     {"role": "user", "content": prompt}
  81.                 ]
  82.             )
  83.             return response.choices[0].message.content
  84.         except Exception as e:
  85.             return f"解释代码时出错: {str(e)}"
  86.    
  87.     def debug_code(self, code, error_message=None):
  88.         """
  89.         帮助调试代码
  90.         
  91.         参数:
  92.             code (str): 有问题的代码
  93.             error_message (str): 错误信息(可选)
  94.             
  95.         返回:
  96.             str: 调试建议和修复后的代码
  97.         """
  98.         error_info = f"\n\n错误信息: {error_message}" if error_message else ""
  99.         
  100.         prompt = f"""
  101.         请帮助调试以下代码:
  102.         
  103.         ```python
  104.         {code}
  105.         ```
  106.         {error_info}
  107.         
  108.         请提供:
  109.         1. 问题分析:解释代码中可能存在的问题
  110.         2. 修复建议:如何修复这些问题
  111.         3. 修复后的代码:提供修复后的完整代码
  112.         
  113.         请确保修复后的代码保持原有功能,同时解决问题。
  114.         """
  115.         
  116.         try:
  117.             response = self.client.chat.completions.create(
  118.                 model="gpt-3.5-turbo",
  119.                 messages=[
  120.                     {"role": "system", "content": "你是一个专业的调试专家,擅长识别和修复代码中的问题。"},
  121.                     {"role": "user", "content": prompt}
  122.                 ]
  123.             )
  124.             return response.choices[0].message.content
  125.         except Exception as e:
  126.             return f"调试代码时出错: {str(e)}"
  127.    
  128.     def optimize_code(self, code, optimization_goal="performance"):
  129.         """
  130.         优化代码
  131.         
  132.         参数:
  133.             code (str): 要优化的代码
  134.             optimization_goal (str): 优化目标,可以是"performance", "readability", "both"
  135.             
  136.         返回:
  137.             str: 优化后的代码和优化说明
  138.         """
  139.         goal_descriptions = {
  140.             "performance": "提高执行效率和性能",
  141.             "readability": "提高代码可读性和可维护性",
  142.             "both": "同时提高性能和可读性"
  143.         }
  144.         
  145.         prompt = f"""
  146.         请优化以下代码:
  147.         
  148.         ```python
  149.         {code}
  150.         ```
  151.         
  152.         优化目标: {goal_descriptions.get(optimization_goal, "提高性能和可读性")}
  153.         
  154.         请提供:
  155.         1. 优化分析:解释代码中可以改进的地方
  156.         2. 优化策略:说明你将采取的优化方法
  157.         3. 优化后的代码:提供优化后的完整代码
  158.         4. 优化效果:解释优化后的改进
  159.         
  160.         请确保优化后的代码保持原有功能。
  161.         """
  162.         
  163.         try:
  164.             response = self.client.chat.completions.create(
  165.                 model="gpt-3.5-turbo",
  166.                 messages=[
  167.                     {"role": "system", "content": "你是一个代码优化专家,擅长提高代码的性能和可读性。"},
  168.                     {"role": "user", "content": prompt}
  169.                 ]
  170.             )
  171.             return response.choices[0].message.content
  172.         except Exception as e:
  173.             return f"优化代码时出错: {str(e)}"
  174. # 使用示例
  175. assistant = CodeAssistant()
  176. # 生成代码
  177. code_desc = "一个函数,接收一个数字列表,返回其中的偶数,并按升序排序"
  178. generated_code = assistant.generate_code(code_desc, language="python", include_comments=True)
  179. print("\n生成的代码:")
  180. print(generated_code)
  181. # 解释代码
  182. code_to_explain = """
  183. def fibonacci(n):
  184.     if n <= 1:
  185.         return n
  186.     else:
  187.         return fibonacci(n-1) + fibonacci(n-2)
  188. """
  189. explanation = assistant.explain_code(code_to_explain, detail_level="medium")
  190. print("\n代码解释:")
  191. print(explanation)
  192. # 调试代码
  193. buggy_code = """
  194. def find_max(numbers):
  195.     max_num = 0
  196.     for num in numbers:
  197.         if num > max_num:
  198.             max_num = num
  199.     return max_num
  200. """
  201. debug_result = assistant.debug_code(buggy_code, error_message="当输入所有负数时,返回0而不是最大负数")
  202. print("\n调试结果:")
  203. print(debug_result)
  204. # 优化代码
  205. code_to_optimize = """
  206. def is_prime(n):
  207.     if n <= 1:
  208.         return False
  209.     for i in range(2, n):
  210.         if n % i == 0:
  211.             return False
  212.     return True
  213. """
  214. optimization = assistant.optimize_code(code_to_optimize, optimization_goal="performance")
  215. print("\n优化结果:")
  216. print(optimization)
复制代码

6. 最佳实践和注意事项

6.1 API使用成本管理

使用ChatGPT API会产生费用,因此合理管理使用量很重要:
  1. class APIUsageTracker:
  2.     """
  3.     API使用量跟踪器
  4.     """
  5.     def __init__(self, budget_limit=None):
  6.         self.client = OpenAI(api_key=api_key)
  7.         self.total_tokens_used = 0
  8.         self.total_cost = 0
  9.         self.budget_limit = budget_limit
  10.         self.usage_history = []
  11.         
  12.         # 不同模型的价格(每1000个token)
  13.         self.model_prices = {
  14.             "gpt-3.5-turbo": 0.002,
  15.             "gpt-4": 0.03,
  16.             "gpt-4-32k": 0.06
  17.         }
  18.    
  19.     def track_usage(self, model, messages):
  20.         """
  21.         跟踪API使用情况
  22.         
  23.         参数:
  24.             model (str): 使用的模型
  25.             messages (list): 消息列表
  26.             
  27.         返回:
  28.             tuple: (响应内容, 使用的token数, 成本)
  29.         """
  30.         try:
  31.             # 检查预算限制
  32.             if self.budget_limit and self.total_cost >= self.budget_limit:
  33.                 return None, 0, 0
  34.             
  35.             # 获取响应
  36.             response = self.client.chat.completions.create(
  37.                 model=model,
  38.                 messages=messages
  39.             )
  40.             
  41.             # 计算使用的token数
  42.             prompt_tokens = response.usage.prompt_tokens
  43.             completion_tokens = response.usage.completion_tokens
  44.             total_tokens = prompt_tokens + completion_tokens
  45.             
  46.             # 计算成本
  47.             price_per_1k = self.model_prices.get(model, 0.002)
  48.             cost = (total_tokens / 1000) * price_per_1k
  49.             
  50.             # 更新总计
  51.             self.total_tokens_used += total_tokens
  52.             self.total_cost += cost
  53.             
  54.             # 记录使用历史
  55.             usage_record = {
  56.                 "timestamp": time.time(),
  57.                 "model": model,
  58.                 "prompt_tokens": prompt_tokens,
  59.                 "completion_tokens": completion_tokens,
  60.                 "total_tokens": total_tokens,
  61.                 "cost": cost
  62.             }
  63.             self.usage_history.append(usage_record)
  64.             
  65.             # 返回响应内容和使用情况
  66.             return response.choices[0].message.content, total_tokens, cost
  67.             
  68.         except Exception as e:
  69.             print(f"API调用出错: {str(e)}")
  70.             return None, 0, 0
  71.    
  72.     def get_usage_summary(self):
  73.         """
  74.         获取使用情况摘要
  75.         
  76.         返回:
  77.             dict: 使用情况摘要
  78.         """
  79.         return {
  80.             "total_tokens_used": self.total_tokens_used,
  81.             "total_cost": self.total_cost,
  82.             "budget_limit": self.budget_limit,
  83.             "remaining_budget": self.budget_limit - self.total_cost if self.budget_limit else None,
  84.             "total_requests": len(self.usage_history)
  85.         }
  86.    
  87.     def get_usage_by_model(self):
  88.         """
  89.         按模型获取使用情况
  90.         
  91.         返回:
  92.             dict: 按模型分类的使用情况
  93.         """
  94.         usage_by_model = {}
  95.         
  96.         for record in self.usage_history:
  97.             model = record["model"]
  98.             if model not in usage_by_model:
  99.                 usage_by_model[model] = {
  100.                     "requests": 0,
  101.                     "tokens": 0,
  102.                     "cost": 0
  103.                 }
  104.             
  105.             usage_by_model[model]["requests"] += 1
  106.             usage_by_model[model]["tokens"] += record["total_tokens"]
  107.             usage_by_model[model]["cost"] += record["cost"]
  108.         
  109.         return usage_by_model
  110. # 使用示例
  111. import time
  112. tracker = APIUsageTracker(budget_limit=1.0)  # 设置1美元的预算限制
  113. # 模拟几次API调用
  114. for i in range(3):
  115.     messages = [
  116.         {"role": "system", "content": "你是一个有用的助手。"},
  117.         {"role": "user", "content": f"请解释什么是人工智能?这是第{i+1}次询问。"}
  118.     ]
  119.    
  120.     content, tokens, cost = tracker.track_usage("gpt-3.5-turbo", messages)
  121.    
  122.     if content:
  123.         print(f"\n请求 {i+1}:")
  124.         print(f"使用的token数: {tokens}")
  125.         print(f"成本: ${cost:.6f}")
  126.         print(f"响应长度: {len(content)} 字符")
  127.     else:
  128.         print(f"\n请求 {i+1}: 已达到预算限制")
  129.         break
  130. # 获取使用情况摘要
  131. summary = tracker.get_usage_summary()
  132. print("\n使用情况摘要:")
  133. print(f"总token数: {summary['total_tokens_used']}")
  134. print(f"总成本: ${summary['total_cost']:.6f}")
  135. print(f"预算限制: ${summary['budget_limit']}")
  136. print(f"剩余预算: ${summary['remaining_budget']:.6f}")
  137. print(f"总请求数: {summary['total_requests']}")
  138. # 获取按模型分类的使用情况
  139. usage_by_model = tracker.get_usage_by_model()
  140. print("\n按模型分类的使用情况:")
  141. for model, usage in usage_by_model.items():
  142.     print(f"\n模型: {model}")
  143.     print(f"请求数: {usage['requests']}")
  144.     print(f"token数: {usage['tokens']}")
  145.     print(f"成本: ${usage['cost']:.6f}")
复制代码

6.2 数据安全和隐私保护

在使用ChatGPT API时,保护用户数据和安全非常重要:
  1. class SecureChatGPT:
  2.     """
  3.     安全的ChatGPT客户端,包含数据保护措施
  4.     """
  5.     def __init__(self, api_key):
  6.         self.client = OpenAI(api_key=api_key)
  7.         
  8.         # 敏感信息模式
  9.         self.sensitive_patterns = {
  10.             "email": r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
  11.             "phone": r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b',
  12.             "ssn": r'\b\d{3}-\d{2}-\d{4}\b',
  13.             "credit_card": r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b'
  14.         }
  15.         
  16.         # 需要屏蔽的敏感词
  17.         self.sensitive_words = [
  18.             "password", "passwd", "pwd",
  19.             "secret", "token", "api_key",
  20.             "credentials", "auth"
  21.         ]
  22.    
  23.     def detect_and_mask_sensitive_data(self, text):
  24.         """
  25.         检测并屏蔽敏感数据
  26.         
  27.         参数:
  28.             text (str): 要检查的文本
  29.             
  30.         返回:
  31.             tuple: (处理后的文本, 检测到的敏感信息列表)
  32.         """
  33.         import re
  34.         
  35.         detected_sensitive = []
  36.         masked_text = text
  37.         
  38.         # 检查敏感词
  39.         for word in self.sensitive_words:
  40.             pattern = r'\b' + re.escape(word) + r'\b'
  41.             matches = re.finditer(pattern, text, re.IGNORECASE)
  42.             for match in matches:
  43.                 detected_sensitive.append({
  44.                     "type": "sensitive_word",
  45.                     "value": match.group(),
  46.                     "position": match.span()
  47.                 })
  48.                 # 屏蔽敏感词
  49.                 masked_text = masked_text[:match.start()] + "[REDACTED]" + masked_text[match.end():]
  50.         
  51.         # 检查敏感模式
  52.         for data_type, pattern in self.sensitive_patterns.items():
  53.             matches = re.finditer(pattern, text)
  54.             for match in matches:
  55.                 detected_sensitive.append({
  56.                     "type": data_type,
  57.                     "value": match.group(),
  58.                     "position": match.span()
  59.                 })
  60.                 # 屏蔽敏感数据
  61.                 masked_text = masked_text[:match.start()] + f"[{data_type.upper()}]" + masked_text[match.end():]
  62.         
  63.         return masked_text, detected_sensitive
  64.    
  65.     def safe_completion(self, messages, model="gpt-3.5-turbo", detect_sensitive=True):
  66.         """
  67.         安全地获取ChatGPT响应
  68.         
  69.         参数:
  70.             messages (list): 消息列表
  71.             model (str): 使用的模型
  72.             detect_sensitive (bool): 是否检测敏感信息
  73.             
  74.         返回:
  75.             dict: 包含响应和敏感信息检测结果的字典
  76.         """
  77.         result = {
  78.             "response": None,
  79.             "sensitive_data_detected": False,
  80.             "detected_items": []
  81.         }
  82.         
  83.         # 处理每条消息,检测敏感信息
  84.         processed_messages = []
  85.         all_detected_items = []
  86.         
  87.         for message in messages:
  88.             content = message["content"]
  89.             
  90.             if detect_sensitive:
  91.                 masked_content, detected_items = self.detect_and_mask_sensitive_data(content)
  92.                 processed_messages.append({
  93.                     "role": message["role"],
  94.                     "content": masked_content
  95.                 })
  96.                 all_detected_items.extend(detected_items)
  97.             else:
  98.                 processed_messages.append(message)
  99.         
  100.         # 如果检测到敏感信息,记录在结果中
  101.         if all_detected_items:
  102.             result["sensitive_data_detected"] = True
  103.             result["detected_items"] = all_detected_items
  104.             print("警告: 检测到敏感信息,已进行屏蔽处理")
  105.         
  106.         try:
  107.             # 获取响应
  108.             response = self.client.chat.completions.create(
  109.                 model=model,
  110.                 messages=processed_messages
  111.             )
  112.             
  113.             response_content = response.choices[0].message.content
  114.             
  115.             # 检查响应中是否包含敏感信息
  116.             if detect_sensitive:
  117.                 masked_response, response_detected_items = self.detect_and_mask_sensitive_data(response_content)
  118.                 result["response"] = masked_response
  119.                
  120.                 if response_detected_items:
  121.                     result["sensitive_data_detected"] = True
  122.                     result["detected_items"].extend(response_detected_items)
  123.                     print("警告: 响应中包含敏感信息,已进行屏蔽处理")
  124.             else:
  125.                 result["response"] = response_content
  126.             
  127.             return result
  128.             
  129.         except Exception as e:
  130.             result["error"] = str(e)
  131.             return result
  132.    
  133.     def anonymize_examples(self, examples):
  134.         """
  135.         匿名化示例数据
  136.         
  137.         参数:
  138.             examples (list): 示例数据列表
  139.             
  140.         返回:
  141.             list: 匿名化后的示例数据
  142.         """
  143.         anonymized_examples = []
  144.         
  145.         for example in examples:
  146.             # 为每个示例创建一个新的匿名版本
  147.             anonymized = example.copy()
  148.             
  149.             # 检测并替换敏感信息
  150.             masked_content, _ = self.detect_and_mask_sensitive_data(example.get("content", ""))
  151.             anonymized["content"] = masked_content
  152.             
  153.             anonymized_examples.append(anonymized)
  154.         
  155.         return anonymized_examples
  156. # 使用示例
  157. secure_chat = SecureChatGPT(api_key)
  158. # 包含敏感信息的消息
  159. messages = [
  160.     {"role": "system", "content": "你是一个客服助手。"},
  161.     {"role": "user", "content": "你好,我的邮箱是john.doe@example.com,电话是123-456-7890。我的密码是secret123,能帮我重置账户吗?"}
  162. ]
  163. # 安全地获取响应
  164. result = secure_chat.safe_completion(messages, detect_sensitive=True)
  165. print("\n响应内容:")
  166. print(result["response"])
  167. if result["sensitive_data_detected"]:
  168.     print("\n检测到的敏感信息:")
  169.     for item in result["detected_items"]:
  170.         print(f"类型: {item['type']}, 值: {item['value']}")
复制代码

6.3 性能优化

优化ChatGPT API的使用可以提高应用性能并降低成本:
  1. import asyncio
  2. from concurrent.futures import ThreadPoolExecutor
  3. import time
  4. class OptimizedChatGPT:
  5.     """
  6.     优化的ChatGPT客户端,提供性能优化功能
  7.     """
  8.     def __init__(self, api_key, max_workers=5):
  9.         self.client = OpenAI(api_key=api_key)
  10.         self.executor = ThreadPoolExecutor(max_workers=max_workers)
  11.         
  12.         # 缓存常见问题的响应
  13.         self.response_cache = {}
  14.         
  15.         # 预定义的系统提示
  16.         self.system_prompts = {
  17.             "default": "你是一个有用的AI助手。",
  18.             "translator": "你是一个专业的翻译,准确翻译文本并保持原文风格。",
  19.             "summarizer": "你是一个专业的总结者,能够简洁明了地总结长文本。",
  20.             "coder": "你是一个专业的程序员,擅长编写清晰、高效的代码。"
  21.         }
  22.    
  23.     def cached_completion(self, messages, model="gpt-3.5-turbo", use_cache=True):
  24.         """
  25.         使用缓存的补全功能
  26.         
  27.         参数:
  28.             messages (list): 消息列表
  29.             model (str): 使用的模型
  30.             use_cache (bool): 是否使用缓存
  31.             
  32.         返回:
  33.             str: ChatGPT的响应
  34.         """
  35.         # 如果使用缓存,检查是否有缓存的响应
  36.         if use_cache:
  37.             # 创建一个简单的键,基于消息内容
  38.             cache_key = hash(str(messages))
  39.             
  40.             if cache_key in self.response_cache:
  41.                 print("使用缓存的响应")
  42.                 return self.response_cache[cache_key]
  43.         
  44.         # 没有缓存或不使用缓存,调用API
  45.         try:
  46.             response = self.client.chat.completions.create(
  47.                 model=model,
  48.                 messages=messages
  49.             )
  50.             
  51.             response_content = response.choices[0].message.content
  52.             
  53.             # 如果使用缓存,保存响应
  54.             if use_cache:
  55.                 self.response_cache[cache_key] = response_content
  56.             
  57.             return response_content
  58.         except Exception as e:
  59.             return f"发生错误: {str(e)}"
  60.    
  61.     def batch_completions(self, messages_list, model="gpt-3.5-turbo"):
  62.         """
  63.         批量处理多个补全请求
  64.         
  65.         参数:
  66.             messages_list (list): 消息列表的列表
  67.             model (str): 使用的模型
  68.             
  69.         返回:
  70.             list: 响应列表
  71.         """
  72.         def single_completion(messages):
  73.             try:
  74.                 response = self.client.chat.completions.create(
  75.                     model=model,
  76.                     messages=messages
  77.                 )
  78.                 return response.choices[0].message.content
  79.             except Exception as e:
  80.                 return f"发生错误: {str(e)}"
  81.         
  82.         # 使用线程池并行处理
  83.         results = list(self.executor.map(single_completion, messages_list))
  84.         return results
  85.    
  86.     async def async_completion(self, messages, model="gpt-3.5-turbo"):
  87.         """
  88.         异步获取补全
  89.         
  90.         参数:
  91.             messages (list): 消息列表
  92.             model (str): 使用的模型
  93.             
  94.         返回:
  95.             str: ChatGPT的响应
  96.         """
  97.         loop = asyncio.get_event_loop()
  98.         
  99.         # 在线程池中运行同步的API调用
  100.         return await loop.run_in_executor(
  101.             self.executor,
  102.             lambda: self.client.chat.completions.create(
  103.                 model=model,
  104.                 messages=messages
  105.             ).choices[0].message.content
  106.         )
  107.    
  108.     async def batch_async_completions(self, messages_list, model="gpt-3.5-turbo"):
  109.         """
  110.         批量异步处理多个补全请求
  111.         
  112.         参数:
  113.             messages_list (list): 消息列表的列表
  114.             model (str): 使用的模型
  115.             
  116.         返回:
  117.             list: 响应列表
  118.         """
  119.         tasks = [self.async_completion(messages, model) for messages in messages_list]
  120.         return await asyncio.gather(*tasks)
  121.    
  122.     def get_system_prompt(self, prompt_type="default"):
  123.         """
  124.         获取预定义的系统提示
  125.         
  126.         参数:
  127.             prompt_type (str): 提示类型
  128.             
  129.         返回:
  130.             str: 系统提示
  131.         """
  132.         return self.system_prompts.get(prompt_type, self.system_prompts["default"])
  133.    
  134.     def clear_cache(self):
  135.         """清空响应缓存"""
  136.         self.response_cache.clear()
  137.         print("响应缓存已清空")
  138. # 使用示例
  139. optimized_chat = OptimizedChatGPT(api_key)
  140. # 测试缓存功能
  141. messages = [
  142.     {"role": "system", "content": optimized_chat.get_system_prompt("default")},
  143.     {"role": "user", "content": "什么是人工智能?"}
  144. ]
  145. print("\n第一次请求(不使用缓存):")
  146. start_time = time.time()
  147. response1 = optimized_chat.cached_completion(messages, use_cache=False)
  148. end_time = time.time()
  149. print(f"响应: {response1[:100]}...")
  150. print(f"耗时: {end_time - start_time:.2f}秒")
  151. print("\n第二次请求(使用缓存):")
  152. start_time = time.time()
  153. response2 = optimized_chat.cached_completion(messages, use_cache=True)
  154. end_time = time.time()
  155. print(f"响应: {response2[:100]}...")
  156. print(f"耗时: {end_time - start_time:.2f}秒")
  157. # 测试批量处理
  158. print("\n批量处理测试:")
  159. batch_messages = [
  160.     [
  161.         {"role": "system", "content": optimized_chat.get_system_prompt("default")},
  162.         {"role": "user", "content": f"什么是机器学习?问题{i+1}"}
  163.     ]
  164.     for i in range(3)
  165. ]
  166. start_time = time.time()
  167. batch_responses = optimized_chat.batch_completions(batch_messages)
  168. end_time = time.time()
  169. for i, response in enumerate(batch_responses, 1):
  170.     print(f"\n响应 {i}: {response[:100]}...")
  171. print(f"\n批量处理总耗时: {end_time - start_time:.2f}秒")
  172. # 测试异步处理
  173. async def test_async():
  174.     print("\n异步批量处理测试:")
  175.     start_time = time.time()
  176.     async_responses = await optimized_chat.batch_async_completions(batch_messages)
  177.     end_time = time.time()
  178.    
  179.     for i, response in enumerate(async_responses, 1):
  180.         print(f"\n异步响应 {i}: {response[:100]}...")
  181.    
  182.     print(f"\n异步批量处理总耗时: {end_time - start_time:.2f}秒")
  183. # 运行异步测试
  184. asyncio.run(test_async())
复制代码

7. 结论:构建更智能的应用

通过本文的介绍,我们深入了解了如何在Python中使用ChatGPT函数和相关库来构建各种智能应用。从基础的API调用到高级的函数调用、流式响应和错误处理,再到实际的应用案例,我们已经掌握了构建智能应用所需的核心技能。

7.1 关键要点回顾

1. 环境设置与API集成:正确设置环境并安全地管理API密钥是使用ChatGPT的第一步。
2. 基本使用技巧:了解如何发送请求、处理响应以及管理对话历史是构建应用的基础。
3. 高级功能:函数调用、流式响应和提示工程等高级技巧可以显著提升应用的能力和用户体验。
4. 实际应用案例:智能客服、内容生成工具和代码辅助工具等案例展示了ChatGPT在不同领域的应用潜力。
5. 最佳实践:API使用成本管理、数据安全和性能优化是构建可靠、高效应用的关键。

环境设置与API集成:正确设置环境并安全地管理API密钥是使用ChatGPT的第一步。

基本使用技巧:了解如何发送请求、处理响应以及管理对话历史是构建应用的基础。

高级功能:函数调用、流式响应和提示工程等高级技巧可以显著提升应用的能力和用户体验。

实际应用案例:智能客服、内容生成工具和代码辅助工具等案例展示了ChatGPT在不同领域的应用潜力。

最佳实践:API使用成本管理、数据安全和性能优化是构建可靠、高效应用的关键。

7.2 未来发展方向

随着AI技术的不断发展,ChatGPT和相关API的能力也在持续提升。未来,我们可以期待:

1. 更多模型选择:更多专业化和优化的模型将满足不同应用场景的需求。
2. 更强大的函数调用能力:更复杂、更灵活的函数调用将使AI能够更好地与外部系统和数据交互。
3. 更好的多模态支持:结合文本、图像、音频等多种模态的AI应用将成为可能。
4. 更低的成本和更高的效率:随着技术的进步,使用AI的成本将进一步降低,效率将进一步提高。

更多模型选择:更多专业化和优化的模型将满足不同应用场景的需求。

更强大的函数调用能力:更复杂、更灵活的函数调用将使AI能够更好地与外部系统和数据交互。

更好的多模态支持:结合文本、图像、音频等多种模态的AI应用将成为可能。

更低的成本和更高的效率:随着技术的进步,使用AI的成本将进一步降低,效率将进一步提高。

7.3 持续学习与探索

要充分利用ChatGPT和Python构建智能应用,持续学习和探索是非常重要的:

1. 关注OpenAI的更新:定期查看OpenAI的官方文档和博客,了解最新的API更新和最佳实践。
2. 参与社区讨论:加入相关的开发者社区,与其他开发者交流经验和技巧。
3. 实践和实验:通过实际项目来应用所学知识,不断尝试新的想法和方法。
4. 学习相关技术:深入学习与AI应用开发相关的其他技术,如数据处理、Web开发、云计算等。

关注OpenAI的更新:定期查看OpenAI的官方文档和博客,了解最新的API更新和最佳实践。

参与社区讨论:加入相关的开发者社区,与其他开发者交流经验和技巧。

实践和实验:通过实际项目来应用所学知识,不断尝试新的想法和方法。

学习相关技术:深入学习与AI应用开发相关的其他技术,如数据处理、Web开发、云计算等。

通过掌握Python中ChatGPT函数的使用技巧,您可以构建出各种创新的智能应用,为用户提供更好的体验和服务。希望本文能够帮助您在这一旅程中取得成功!
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则