当前位置: 首页 > news >正文

【大模型入门】访问GPT_API实战案例

目录

0 前言

1 聊天机器人

2 翻译助手

3 联网搜索


0 前言

访问GPT_API的干货,见这篇blog:https://blog.csdn.net/m0_60121089/article/details/149104844?spm=1011.2415.3001.5331

1 聊天机器人

前置准备

import dotenv
from openai import OpenAI# 加载环境变量
dotenv.load_dotenv('.env')# 创建客户端
client = OpenAI()

单轮对话 

chat_response = client.chat.completions.create(# 模型model="gpt-3.5-turbo",# 消息messages=[# 角色扮演{"role": "system","content": "You are a helpful assistant."},# 用户消息{"role": "user","content": "Say this is a test."}],# 流式输出stream=True
)for chunk in chat_response:# 内容不为None就输出if chunk.choices[0].delta.content is not None:print(chunk.choices[0].delta.content,end='')# 内容为None(也就是输出结束时)退出循环else:break

输出:

多轮对话

while True:# 用户输入user_input = input('User:')# 用户输入为“quit”时退出while循环if user_input == "quit":breakchat_response = client.chat.completions.create(# 模型model="gpt-3.5-turbo",# 消息messages=[# 角色扮演{"role": "system","content": "You are a helpful assistant."},# 用户消息{"role": "user","content": user_input}],# 流式输出stream=True)print('GPT:',end='')for chunk in chat_response:# 内容不为None就输出if chunk.choices[0].delta.content is not None:print(chunk.choices[0].delta.content,end='')# 内容为None(也就是输出结束时)退出for循环else:breakprint()

可见此时的聊天机器人没有存储对话历史,还不具备记忆功能。

存储对话历史

存储对话历史,让聊天机器人具备记忆功能。

# 对话历史
chat_history = [{"role": "system","content": "You are a helpful assistant."}]
while True:# 用户输入user_input = input('User:')# 用户输入为“quit”时退出while循环if user_input == "quit":break# 对话历史中添加用户消息chat_history.append({"role": "user","content": user_input})chat_response = client.chat.completions.create(# 模型model="gpt-3.5-turbo",# 消息messages=chat_history,# 流式输出stream=True)print('GPT:',end='')# gpt回答gpt_answer = ''for chunk in chat_response:# 内容不为None就输出if chunk.choices[0].delta.content is not None:# 流式输出的每部分内容chunk_content = chunk.choices[0].delta.contentprint(chunk_content,end='')# 把流式输出的每部分内容累加起来,就是gpt回答gpt_answer += chunk_content# 内容为None(也就是输出结束时)退出for循环else:break# 对话历史中添加gpt回答chat_history.append({"role": "assistant","content": gpt_answer})print()

完整代码

import dotenv
from openai import OpenAI# 加载环境变量
dotenv.load_dotenv('.env')# 创建客户端
client = OpenAI()# 对话历史
chat_history = [{"role": "system","content": "You are a helpful assistant."}]while True:# 用户输入user_input = input('User:')# 用户输入为“quit”时退出while循环if user_input == "quit":break# 对话历史中添加用户消息chat_history.append({"role": "user","content": user_input})chat_response = client.chat.completions.create(# 模型model="gpt-3.5-turbo",# 消息messages=chat_history,# 流式输出stream=True)print('GPT:',end='')# gpt回答gpt_answer = ''for chunk in chat_response:# 内容不为None就输出if chunk.choices[0].delta.content is not None:# 流式输出的每部分内容chunk_content = chunk.choices[0].delta.contentprint(chunk_content,end='')# 把流式输出的每部分内容累加起来,就是gpt回答gpt_answer += chunk_content# 内容为None(也就是输出结束时)退出for循环else:break# 对话历史中添加gpt回答chat_history.append({"role": "assistant","content": gpt_answer})print()

2 翻译助手

import dotenv
from openai import OpenAI# 加载环境变量
dotenv.load_dotenv('.env')# 创建客户端
client = OpenAI()print('您好,我是您的翻译助手。有什么问题就问我吧。结束聊天对话请输入:quit')while True:# 用户输入user_input = input('User:')# 用户输入为“quit”时退出while循环if user_input == "quit":breakchat_response = client.chat.completions.create(# 模型model="gpt-3.5-turbo",# 消息messages=[# 角色扮演{"role": "system","content": "你是一个专业的中英翻译助手"},# 用户消息{"role": "user","content": user_input}],# 流式输出stream=True)print('GPT:',end='')for chunk in chat_response:# 内容不为None就输出if chunk.choices[0].delta.content is not None:print(chunk.choices[0].delta.content,end='')# 内容为None(也就是输出结束时)退出for循环else:breakprint()

3 联网搜索

联网搜索可以获取最新的数据,防止大模型根据旧数据胡编乱造,缓解大模型幻觉问题。

使用联网搜索前,先准备好以下两步:

1. 获取SerpApi Key

访问SerpApi注册页面(https://serpapi.com/users/sign_up)进行注册并获取你的API密钥。

2. 安装必要的Python库

安装google-search-results库以便进行API调用。运行以下命令:

pip install google-search-results

import os
from openai import OpenAI
from serpapi import GoogleSearch# 创建客户端
client = OpenAI(base_url = os.environ.get("OPENAI_BASE_URL"),api_key = os.environ.get("OPENAI_API_KEY")
)def get_search_results(query):# 参数params = {"q": query,"api_key": os.environ.get("SERPAPI_API_KEY")}# 传参,进行搜索search = GoogleSearch(params)# 转换成字典形式result = search.get_dict()# 返回搜索结果return result['organic_results'][0]['snippet']def chat(query,model_name="gpt-3.5-turbo"):prompt = get_search_results(query) + querychat_response = client.chat.completions.create(# 模型model="gpt-3.5-turbo",# 消息messages=[# 角色扮演{"role": "system","content": "You are a helpful assistant."},# 用户消息{"role": "user","content": prompt}],# 流式输出stream=True)for chunk in chat_response:# 内容不为None就输出if chunk.choices[0].delta.content is not None:print(chunk.choices[0].delta.content,end='')# 内容为None(也就是输出结束时)退出循环else:break

分析:

所以,传递给大模型的prompt,实际上是search_results + query,具体为:

2023年8月29日晚11点56分,易建联在其个人微博上宣布退役。 目录. 1 生平; 2 ... 最终火箭以91比83击败雄鹿,但两人的表现都不突出,姚明得到12分,而易建联则是在比赛中撞伤右肩 ...易建联是什么时候退役的?

http://www.dtcms.com/a/268245.html

相关文章:

  • 从LLM和MCP的协同过程看如何做优化
  • webUI平替应用,安装简单,功能齐全
  • 基于Java+springboot 的车险理赔信息管理系统
  • 基于udev规则固定相机名称
  • 计算机网络:(七)网络层(上)网络层中重要的概念与网际协议 IP
  • 深度学习图像分类数据集—濒危动物识别分类
  • 如何将 Java 项目打包为可执行 JAR 文件
  • Git使用教程
  • 软考(软件设计师)进程管理—进程基本概念,信号量与PV操作
  • centos7.9安装ffmpeg6.1和NASM、Yasm、x264、x265、fdk-aac、lame、opus解码器
  • 1.8 提示词优化
  • Tuning Language Models by Proxy
  • HBuilder提示”未检测到联盟快应用开发者工具”的问题无法发布快应用的解决方案-优雅草卓伊凡
  • 【第七章】全球卫星导航定位技术
  • 缺陷追踪流程
  • Vue+Openlayers加载OSM、加载天地图
  • Modbus_TCP_V5 新功能
  • 【机器学习深度学习】模型微调时的4大基础评估指标(1)
  • [netty5: WebSocketServerHandshaker WebSocketServerHandshakerFactory]-源码分析
  • 机器学习绪论
  • LeetCode 100题(1)(10题)
  • 线性代数--AI数学基础复习
  • 暑假算法日记第二天
  • DTW模版匹配:弹性对齐的时间序列相似度度量算法
  • 基于联合国国家指标 2025数据(UN Countries Metrics 2025: HDI, GDP, POP, AREA)的综合可视化分析
  • PDF转换工具,即开即用
  • BUUCTF在线评测-练习场-WebCTF习题[GXYCTF2019]BabyUpload1-flag获取、解析
  • 微前端架构在嵌入式BI中的集成实践与性能优化
  • Redis存储Cookie实现爬虫保持登录 requests | selenium
  • Python: 正则表达式