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

【大模型入门】访问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.xdnf.cn/news/14981.html

相关文章:

  • 数据挖掘:深度解析与实战应用
  • 谷歌浏览器安全输入控件-allWebSafeInput控件
  • 深度学习6(多分类+交叉熵损失原理+手写数字识别案例TensorFlow)
  • Android 应用开发 | 一种限制拷贝速率解决因 IO 过高导致系统卡顿的方法
  • C#使用Qdrant实现向量存储及检索
  • 内存池(C++)v1
  • CICD[导航]、docker+gitlab+harbor+jenkins从安装到部署
  • .NET9 实现字符串拼接(StringConcatenation)性能测试
  • 【机器学习笔记 Ⅱ】2 神经网络中的层
  • ch03 部分题目思路
  • 深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
  • 深度学习篇---简单果实分类网络
  • 软件工程中耦合度
  • 如何正确规范的开发术语自己的TYPECHO插件
  • 条件渲染 v-show与v-if
  • Web开发安全 之 信息加密
  • Spring Boot 集成 Thymeleaf​​ 的快速实现示例,无法渲染页面问题解决
  • 基于Flask和机器学习开发的米其林餐厅数据可视化平台
  • Peek-Ubuntu上Gif录制工具-24.04LTS可装
  • ClickHouse 全生命周期性能优化
  • Java零基础笔记01(JKD及开发工具IDEA安装配置)
  • 数据库学习笔记(十七)--触发器的使用
  • Chat Model API
  • centos 7.6安装mysql8
  • MySQL GROUP_CONCAT函数实现列转行
  • Python实例题:基于 Python 的简单聊天机器人
  • 基于Java+SpringBoot的三国之家网站
  • HTML网页应用打包Android App 完整实践指南
  • IM即时通讯系统设计——TIO 作为技术框架
  • .NET9 实现斐波那契数列(FibonacciSequence)性能测试