获取openapikey

#!pip install python-dotenv

#!pip install openai
import osimport openai
​
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key = os.environ['OPENAI_API_KEY']
# account for deprecation of LLM model
import datetime
# Get the current date
current_date = datetime.datetime.now().date()
​
# Define the date after which the model should be set to "gpt-3.5-turbo"
target_date = datetime.date(2024, 6, 12)
​
# Set the model variable based on the current date
if current_date > target_date:llm_model = "gpt-3.5-turbo"
else:llm_model = "gpt-3.5-turbo-0301"

Chat API : OpenAI

调用openapi

def get_completion(prompt, model=llm_model):messages = [{"role": "user", "content": prompt}]response = openai.ChatCompletion.create(model=model,messages=messages,temperature=0, )return response.choices[0].message["content"]
​get_completion("What is 1+1?")customer_email = """
Arrr, I be fuming that me blender lid \
flew off and splattered me kitchen walls \
with smoothie! And to make matters worse,\
the warranty don't cover the cost of \
cleaning up me kitchen. I need yer help \
right now, matey!
"""
style = """American English \
in a calm and respectful tone
"""prompt = f"""Translate the text \
that is delimited by triple backticks 
into a style that is {style}.
text: ```{customer_email}```
"""
​
print(prompt)
response = get_completion(prompt)response

deepseek

import requests
import json# DeepSeek API 配置
DEEPSEEK_API_KEY = "替换为您的实际API密钥"  # 替换为您的实际API密钥
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"def get_deepseek_completion(prompt, model="deepseek-chat"):"""使用 DeepSeek API 获取回复"""headers = {"Authorization": f"Bearer {DEEPSEEK_API_KEY}","Content-Type": "application/json"}payload = {"model": model,"messages": [{"role": "user", "content": prompt}],"temperature": 0}try:response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload)response.raise_for_status()  # 检查HTTP错误result = response.json()return result['choices'][0]['message']['content']except requests.exceptions.RequestException as e:print(f"API请求错误: {e}")return Noneexcept (KeyError, IndexError) as e:print(f"解析响应错误: {e}")return Nonecustomer_email = """
Arrr, I be fuming that me blender lid \
flew off and splattered me kitchen walls \
with smoothie! And to make matters worse,\
the warranty don't cover the cost of \
cleaning up me kitchen. I need yer help \
right now, matey!
"""style = """American English \
in a calm and respectful tone
"""prompt = f"""Translate the text \
that is delimited by triple backticks 
into a style that is {style}.
text: ```{customer_email}```
"""# 获取并打印翻译结果
translation = get_deepseek_completion(prompt)
if translation:print("\n翻译结果:")print(translation)

OpenAI 方式​

​DeepSeek 方式​

openai.ChatCompletion.create()

requests.post()发送HTTP请求

直接返回对象

解析JSON响应

LangChain+openapi

Let's try how we can do the same using LangChain.

#!pip install --upgrade langchain
from langchain.chat_models import ChatOpenAI# To control the randomness and creativity of the generated
# text by an LLM, use temperature = 0.0
chat = ChatOpenAI(temperature=0.0, model=llm_model)template_string = """Translate the text \
that is delimited by triple backticks \
into a style that is {style}. \
text: ```{text}```
"""from langchain.prompts import ChatPromptTemplate
​
prompt_template = ChatPromptTemplate.from_template(template_string)customer_style = """American English \
in a calm and respectful tone
"""customer_email = """
Arrr, I be fuming that me blender lid \
flew off and splattered me kitchen walls \
with smoothie! And to make matters worse, \
the warranty don't cover the cost of \
cleaning up me kitchen. I need yer help \
right now, matey!
"""customer_messages = prompt_template.format_messages(style=customer_style,text=customer_email)# Call the LLM to translate to the style of the customer message
customer_response = chat(customer_messages)
print(customer_response.content)service_reply = """Hey there customer, \
the warranty does not cover \
cleaning expenses for your kitchen \
because it's your fault that \
you misused your blender \
by forgetting to put the lid on before \
starting the blender. \
Tough luck! See ya!
"""
service_style_pirate = """\
a polite tone \
that speaks in English Pirate\
"""service_messages = prompt_template.format_messages(style=service_style_pirate,text=service_reply)
​
print(service_messages[0].content)
service_response = chat(service_messages)
print(service_response.content)

Langchain+deepseek

from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate# 配置 DeepSeek AI
DEEPSEEK_API_KEY = " # 替换为您的实际API密钥" 
DEEPSEEK_API_BASE = "https://api.deepseek.com/v1"# 创建 DeepSeek 聊天模型
chat = ChatOpenAI(temperature=0.0,model="deepseek-chat",  # DeepSeek 模型名称openai_api_key=DEEPSEEK_API_KEY,openai_api_base=DEEPSEEK_API_BASE
)# 翻译模板
template_string = """Translate the text \
that is delimited by triple backticks \
into a style that is {style}. \
text: ```{text}```
"""# 创建提示模板
prompt_template = ChatPromptTemplate.from_template(template_string)# 第一部分:客户邮件翻译
customer_style = """American English in a calm and respectful tone"""
customer_email = """
Arrr, I be fuming that me blender lid \
flew off and splattered me kitchen walls \
with smoothie! And to make matters worse, \
the warranty don't cover the cost of \
cleaning up me kitchen. I need yer help \
right now, matey!
"""# 格式化消息
customer_messages = prompt_template.format_messages(style=customer_style,text=customer_email
)# 调用 DeepSeek 翻译
customer_response = chat(customer_messages)
print("客户邮件翻译结果:")
print(customer_response.content)
print("\n" + "-"*50 + "\n")# 第二部分:服务回复翻译
service_reply = """Hey there customer, \
the warranty does not cover \
cleaning expenses for your kitchen \
because it's your fault that \
you misused your blender \
by forgetting to put the lid on before \
starting the blender. \
Tough luck! See ya!
"""service_style_pirate = """a polite tone that speaks in English Pirate"""# 格式化消息
service_messages = prompt_template.format_messages(style=service_style_pirate,text=service_reply
)# 打印格式化后的提示
print("服务回复提示内容:")
print(service_messages[0].content)
print("\n" + "-"*50 + "\n")# 调用 DeepSeek 翻译
service_response = chat(service_messages)
print("服务回复翻译结果:")
print(service_response.content)

Output Parsers

{"gift": False,"delivery_days": 5,"price_value": "pretty affordable!"
}
customer_review = """\
This leaf blower is pretty amazing.  It has four settings:\
candle blower, gentle breeze, windy city, and tornado. \
It arrived in two days, just in time for my wife's \
anniversary present. \
I think my wife liked it so much she was speechless. \
So far I've been the only one using it, and I've been \
using it every other morning to clear the leaves on our lawn. \
It's slightly more expensive than the other leaf blowers \
out there, but I think it's worth it for the extra features.
"""review_template = """\
For the following text, extract the following information:gift: Was the item purchased as a gift for someone else? \
Answer True if yes, False if not or unknown.delivery_days: How many days did it take for the product \
to arrive? If this information is not found, output -1.price_value: Extract any sentences about the value or price,\
and output them as a comma separated Python list.Format the output as JSON with the following keys:
gift
delivery_days
price_valuetext: {text}
"""
from langchain.prompts import ChatPromptTemplateprompt_template = ChatPromptTemplate.from_template(review_template)
print(prompt_template)
messages = prompt_template.format_messages(text=customer_review)
chat = ChatOpenAI(temperature=0.0, model=llm_model)
response = chat(messages)
print(response.content)
type(response.content)
# You will get an error by running this line of code 
# because'gift' is not a dictionary
# 'gift' is a string
response.content.get('gift')

Parse the LLM output string into a Python dictionary

from langchain.output_parsers import ResponseSchema
from langchain.output_parsers import StructuredOutputParser
gift_schema = ResponseSchema(name="gift",description="Was the item purchased\as a gift for someone else? \Answer True if yes,\False if not or unknown.")
delivery_days_schema = ResponseSchema(name="delivery_days",description="How many days\did it take for the product\to arrive? If this \information is not found,\output -1.")
price_value_schema = ResponseSchema(name="price_value",description="Extract any\sentences about the value or \price, and output them as a \comma separated Python list.")response_schemas = [gift_schema, delivery_days_schema,price_value_schema]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
format_instructions = output_parser.get_format_instructions()
print(format_instructions)
review_template_2 = """\
For the following text, extract the following information:gift: Was the item purchased as a gift for someone else? \
Answer True if yes, False if not or unknown.delivery_days: How many days did it take for the product\
to arrive? If this information is not found, output -1.price_value: Extract any sentences about the value or price,\
and output them as a comma separated Python list.text: {text}{format_instructions}
"""prompt = ChatPromptTemplate.from_template(template=review_template_2)messages = prompt.format_messages(text=customer_review, format_instructions=format_instructions)
print(messages[0].content)
response = chat(messages)
print(response.content)
output_dict = output_parser.parse(response.content)
type(output_dict)
output_dict.get('delivery_days')

参考:LangChain for LLM Application Development - DeepLearning.AI

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/98042.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/98042.shtml
英文地址,请注明出处:http://en.pswp.cn/diannao/98042.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ACMESSL自动续签教程

目录 1、选择申请证书 ​编辑2、选择CA机构 ​编辑3、选择自动验签 ​编辑4、证书续签设置 5、自动发布设置 本教程实现ACMESSL自动续签,请按照此教程实现。 1、选择申请证书 点击快捷入口或者订单或证书列表中的【创建证书】按钮: 2、选择CA机构 …

基于飞算JavaAI的在线图书借阅平台设计实现

项目概述与需求分析 1.1 项目背景与意义 随着数字化时代的快速发展,传统图书馆管理模式已无法满足现代读者的需求。在线图书借阅平台通过互联网技术将图书资源数字化,为读者提供便捷的检索、借阅和管理服务,有效解决了传统图书馆开放时间有…

通过API接口管理企业微信通讯录案例

1.开始前需要登录企业微信管理员后台,开启通讯录同步,同时添加企业可信IP地址,记录下Secret信息和企业ID,后面的程序会用到这两个参数。2.下面是用python写的创建企业微信账号的具体案例。#!/usr/bin/env python3 # -*- coding: u…

硬件开发_基于物联网的自动售卖机系统

一.系统概述 物联网自动售卖机系统的主要功能如下: 核心控制器:采用STM32单片机作为系统核心,负责整体数据处理和各设备的统一控制。商品选择:支持语音识别及按键方式,方便用户在售卖机内选择商品。语音播报&#xff1…

AGENTS.md: AI编码代理的开放标准

每个项目都有一个 README.md 文件供人类阅读。但随着 AI 编码代理和 AI 辅助开发的兴起,我们需要一个新标准:AGENTS.md。这个 Markdown 文件定义了代理如何构建、测试和协作。 这就是 AGENTS.md 的作用。 它是一个简单的 Markdown 文件,告诉 AI 助手如何在你的项目中操作:…

如何解决 OutOfMemoryError 内存溢出 —— 原因、定位与解决方案

网罗开发(小红书、快手、视频号同名)大家好,我是 展菲,目前在上市企业从事人工智能项目研发管理工作,平时热衷于分享各种编程领域的软硬技能知识以及前沿技术,包括iOS、前端、Harmony OS、Java、Python等方…

阿里云服务器配置ssl-docker nginx

# 切换到您当前的目录 cd /AAAAAAAAAAAA# 创建存放nginx配置、证书和日志的目录结构 mkdir -p nginx-config/conf.d nginx-ssl nginx-logs# 为挂载做准备,您可能需要将当前dist目录内容移动到新的html目录 # 首先查看当前dist目录的内容 ls -la dist/# 如果html目录…

2025全球生成式引擎优化(GEO)服务商发展趋势与企业赋能白皮书

引言:人工智能技术的迅猛发展,特别是在生成式AI领域的突破,正以前所未有的力量重塑商业世界的竞争格局。对于寻求提升在线可见性、优化品牌互动及实现可持续增长的企业而言,生成式引擎优化(GEO)已然成为数字…

海康威视工业相机SDK开发实战:使用C/C++实现软件触发图像采集(含详细中文注释代码)

一、前言 在机器视觉、自动化检测、智能制造等领域,工业相机是获取图像数据的核心设备。海康威视作为国内领先的机器视觉厂商,其工业相机产品线丰富,广泛应用于各类工业场景。 本文将带你从零开始,使用 海康MVS SDK(Ma…

Modbus RTU 协议介绍

Modbus RTU 协议介绍 异步串行传输方式,采用二进制格式,适用于串行通讯(如RS-485),效率高,是工业现场的主流选择。 主站是Master,从站是Slave。 Modbus RTU 协议格式 帧结构 地址码&#xf…

TCP/IP函数——sendmsg

sendmsg() 是 POSIX 标准中一个高级套接字发送函数,属于系统调用(由操作系统内核实现),定义在 <sys/socket.h> 头文件中。它的核心特点是支持复杂消息结构,不仅能发送常规数据,还能附加控制信息(如辅助数据、IP 选项等),适用于 TCP、UDP 等多种协议,功能比 sen…

运动控制中的插值运动(插补运动):原理、实现与应用

在自动化设备中,从起点到终点的精准轨迹控制是核心需求。当目标轨迹是直线、圆弧或复杂曲线时,仅通过离散的目标点无法实现平滑运动,这就需要插值运动(Interpolation Motion)技术 —— 通过控制算法在已知路径点之间计算出连续的中间点,使运动部件沿预定轨迹平滑移动。本…

GMT——用于人形全身控制的通用运动跟踪:两阶段师生训练框架下,全身基于单一策略,且自适应采样、MoE架构

前言 如此文《KungfuBot——基于物理约束和自适应运动追踪的人形全身控制PBHC&#xff0c;用于学习打拳或跳舞(即RL下的动作模仿和运控)》的开头所说 如此&#xff0c;便关注到最新出来的三个工作 第一个是GMT: General Motion Tracking for Humanoid Whole-Body Control第二个…

matlab版本粒子群算法(PSO)在路径规划中的应用

基于粒子群优化&#xff08;PSO&#xff09;算法的路径规划 MATLAB代码实现 1. 初始化环境和参数 % 初始化环境参数 mapSize [10, 10]; % 地图大小 startPoint [1, 1]; % 起点 endPoint [9, 9]; % 终点 obstacles [3, 3; 5, 5; 7, 7]; % 障碍物位置% PSO参数 numParticles …

Go语言面试:传值与传引用的区别及选择指南

在Go语言中&#xff0c;函数参数的传递方式有两种&#xff1a;传值&#xff08;pass-by-value&#xff09;和传引用&#xff08;pass-by-reference&#xff09;。理解这两种方式的区别及其适用场景&#xff0c;是成为Go语言开发高手的必备技能。本文将深入探讨Go语言中传值与传…

数据无言,网关有声 耐达讯自动化RS485转Profinet让千年液位数据“开口说话”

在能源行业的数字化转型浪潮中&#xff0c;你是否曾面临这样的困境&#xff1a; 现场大量采用RS485接口的液位计&#xff0c;数据孤立如信息孤岛&#xff0c;无法接入Profinet高速网络&#xff1f; 模拟信号传输距离受限&#xff0c;抗干扰能力弱&#xff0c;导致液位测量误差…

出口退税新政大提速:企业如何抓住政策红利,提升最高13%纯利?

近年来&#xff0c;出口退税政策的优化与升级&#xff0c;正在成为外贸企业提升资金周转率和利润率的关键。国家税务总局发布的 2022年第9号公告&#xff08;简称“9号公告”&#xff09;落地执行已两年&#xff0c;外贸行业普遍感受到退税速度显著加快&#xff0c;平均退税周期…

使用pytorch创建/训练/推理OCR模型

一、任务描述 从手写数字图像中自动识别出对应的数字&#xff08;0-9&#xff09;” 的问题&#xff0c;属于单标签图像分类任务&#xff08;每张图像仅对应一个类别&#xff0c;即 0-9 中的一个数字&#xff09; 1、任务的核心定义&#xff1a;输入与输出 输入&#xff1a;28…

新启航开启深孔测量新纪元:激光频率梳技术攻克光学遮挡,达 130mm 深度 2μm 精度

摘要&#xff1a;本文聚焦于深孔测量领域&#xff0c;介绍了一种创新的激光频率梳技术。该技术成功攻克传统测量中的光学遮挡难题&#xff0c;在深孔测量深度达 130mm 时&#xff0c;可实现 2μm 的高精度测量&#xff0c;为深孔测量开启了新的发展篇章。关键词&#xff1a;激光…

GEO优化推荐:AI搜索新纪元下的品牌内容权威构建

引言&#xff1a;AI搜索引擎崛起与GEO策略的战略重心转移2025年&#xff0c;以ChatGPT、百度文心一言、DeepSeek为代表的AI搜索引擎已深入成为公众信息获取的核心渠道。这标志着品牌营销策略的重心&#xff0c;正从传统的搜索引擎优化&#xff08;SEO&#xff09;加速向生成式引…