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

绍兴网站制作多少钱晚上免费b站软件

绍兴网站制作多少钱,晚上免费b站软件,培训制作网站源码,环保网站建设开发关于LangChain入门,读者可参考文章NLP(五十六)LangChain入门 。   本文将会介绍LangChain中的重连机制,并尝试给出定制化重连方案。   本文以LangChain中的对话功能(ChatOpenAI)为例。 LangChain中的重…

  关于LangChain入门,读者可参考文章NLP(五十六)LangChain入门 。
  本文将会介绍LangChain中的重连机制,并尝试给出定制化重连方案。
  本文以LangChain中的对话功能(ChatOpenAI)为例。

LangChain中的重连机制

  查看LangChain中对话功能(ChatOpenAI)的重连机制(retry),其源代码如下:

class ChatOpenAI(BaseChatModel):...def _create_retry_decorator(self) -> Callable[[Any], Any]:import openaimin_seconds = 1max_seconds = 60# Wait 2^x * 1 second between each retry starting with# 4 seconds, then up to 10 seconds, then 10 seconds afterwardsreturn retry(reraise=True,stop=stop_after_attempt(self.max_retries),wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),retry=(retry_if_exception_type(openai.error.Timeout)| retry_if_exception_type(openai.error.APIError)| retry_if_exception_type(openai.error.APIConnectionError)| retry_if_exception_type(openai.error.RateLimitError)| retry_if_exception_type(openai.error.ServiceUnavailableError)),before_sleep=before_sleep_log(logger, logging.WARNING),)def completion_with_retry(self, **kwargs: Any) -> Any:"""Use tenacity to retry the completion call."""retry_decorator = self._create_retry_decorator()@retry_decoratordef _completion_with_retry(**kwargs: Any) -> Any:return self.client.create(**kwargs)return _completion_with_retry(**kwargs)

可以看到,其编码方式为硬编码(hardcore),采用tenacity模块实现重连机制,对于支持的报错情形,比如openai.error.Timeout, openai.error.APIError等,会尝试重连,最小等待时间为1s,最大等待时间为60s,每次重连等待时间会乘以2。

简单重连

  我们尝试用一个错误的OpenAI key进行对话,代码如下:

from langchain.chat_models import ChatOpenAIdef chat_bot(input_text: str):llm = ChatOpenAI(temperature=0,model_name="gpt-3.5-turbo",openai_api_key="sk-xxx",max_retries=5)return llm.predict(input_text)if __name__ == '__main__':text = '中国的首都是哪里?'print(chat_bot(text))

尽管我们在代码中设置了重连最大次数(max_retries),代码运行时会直接报错,不会重连,原因是LangChain中的对话功能重连机制没有支持openai.error.AuthenticationError。输出结果如下:

openai.error.AuthenticationError: Incorrect API key provided: sk-xxx. You can find your API key at https://platform.openai.com/account/api-keys.

  此时,我们尝试在源代码的基础上做简单的定制,使得其支持openai.error.AuthenticationError错误类型,代码如下:

# -*- coding: utf-8 -*-
import openai
from typing import Callable, Any
from tenacity import (before_sleep_log,retry,retry_if_exception_type,stop_after_attempt,wait_exponential,
)
from langchain.chat_models import ChatOpenAI
import logginglogger = logging.getLogger(__name__)class MyChatOpenAI(ChatOpenAI):def _create_retry_decorator(self) -> Callable[[Any], Any]:min_seconds = 1max_seconds = 60# Wait 2^x * 1 second between each retry starting with# 4 seconds, then up to 10 seconds, then 10 seconds after wardsreturn retry(reraise=True,stop=stop_after_attempt(self.max_retries),wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),retry=(retry_if_exception_type(openai.error.Timeout)| retry_if_exception_type(openai.error.APIError)| retry_if_exception_type(openai.error.APIConnectionError)| retry_if_exception_type(openai.error.RateLimitError)| retry_if_exception_type(openai.error.ServiceUnavailableError)# add new error| retry_if_exception_type(openai.error.AuthenticationError)),before_sleep=before_sleep_log(logger, logging.WARNING),)def completion_with_retry(self, **kwargs: Any) -> Any:"""Use tenacity to retry the completion call."""retry_decorator = self._create_retry_decorator()@retry_decoratordef _completion_with_retry(**kwargs: Any) -> Any:return self.client.create(**kwargs)return _completion_with_retry(**kwargs)def chat_bot(input_text: str):llm = MyChatOpenAI(temperature=0,model_name="gpt-3.5-turbo",openai_api_key="sk-xxx",max_retries=5)return llm.predict(input_text)if __name__ == '__main__':text = '中国的首都是哪里?'print(chat_bot(text))

分析上述代码,我们在继承ChatOpenAI类的基础上重新创建MyChatOpenAI类,在_create_retry_decorator中的重连错误情形中加入了openai.error.AuthenticationError错误类型,此时代码输出结果如下:

Retrying __main__.MyChatOpenAI.completion_with_retry.<locals>._completion_with_retry in 1.0 seconds as it raised AuthenticationError: Incorrect API key provided: sk-xxx. You can find your API key at https://platform.openai.com/account/api-keys..
Retrying __main__.MyChatOpenAI.completion_with_retry.<locals>._completion_with_retry in 2.0 seconds as it raised AuthenticationError: Incorrect API key provided: sk-xxx. You can find your API key at https://platform.openai.com/account/api-keys..
Retrying __main__.MyChatOpenAI.completion_with_retry.<locals>._completion_with_retry in 4.0 seconds as it raised AuthenticationError: Incorrect API key provided: sk-xxx. You can find your API key at https://platform.openai.com/account/api-keys..
Retrying __main__.MyChatOpenAI.completion_with_retry.<locals>._completion_with_retry in 8.0 seconds as it raised AuthenticationError: Incorrect API key provided: sk-xxx. You can find your API key at https://platform.openai.com/account/api-keys..
Traceback (most recent call last):......
openai.error.AuthenticationError: Incorrect API key provided: sk-xxx. You can find your API key at https://platform.openai.com/account/api-keys.

从输出结果中,我们可以看到,该代码确实对openai.error.AuthenticationError错误类型进行了重连,按照源代码的方式进行重连,一共尝试了5次重连,每次重连等待时间是上一次的两倍。

定制化重连

  LangChain中的重连机制也支持定制化。
  假设我们的使用场景:某个OpenAI key在调用过程中失效了,那么在重连时希望能快速切换至某个能正常使用的OpenAI key,以下为示例代码(仅需要修改completion_with_retry函数):

    def completion_with_retry(self, **kwargs: Any) -> Any:"""Use tenacity to retry the completion call."""retry_decorator = self._create_retry_decorator()@retry_decoratordef _completion_with_retry(**kwargs: Any) -> Any:# 重连机制定制化(custom retry)kwargs['api_key'] = 'right openai key'return self.client.create(**kwargs)return _completion_with_retry(**kwargs)

此时就能进行正常的对话功能了。

总结

  本文介绍了LangChain中的重连机制,并尝试给出定制化重连方案,希望能对读者有所帮助。
  笔者的个人博客网址为:https://percent4.github.io/ ,欢迎大家访问~


文章转载自:
http://anzac.rywn.cn
http://monthlong.rywn.cn
http://lazarette.rywn.cn
http://gallantry.rywn.cn
http://rubbidy.rywn.cn
http://polyarchy.rywn.cn
http://hoagie.rywn.cn
http://reissue.rywn.cn
http://fibrin.rywn.cn
http://lachrymatory.rywn.cn
http://buttocks.rywn.cn
http://superpersonality.rywn.cn
http://unsuspicious.rywn.cn
http://xylographic.rywn.cn
http://uncock.rywn.cn
http://booby.rywn.cn
http://volubly.rywn.cn
http://zine.rywn.cn
http://berliozian.rywn.cn
http://prill.rywn.cn
http://elfish.rywn.cn
http://trackability.rywn.cn
http://metalloprotein.rywn.cn
http://attainments.rywn.cn
http://taiyuan.rywn.cn
http://qualitative.rywn.cn
http://practolol.rywn.cn
http://diplopia.rywn.cn
http://pelycosaur.rywn.cn
http://tlp.rywn.cn
http://angelica.rywn.cn
http://suite.rywn.cn
http://downriver.rywn.cn
http://glomeration.rywn.cn
http://paten.rywn.cn
http://rarer.rywn.cn
http://laval.rywn.cn
http://doric.rywn.cn
http://bonesetter.rywn.cn
http://disroot.rywn.cn
http://imposturous.rywn.cn
http://progression.rywn.cn
http://basidiospore.rywn.cn
http://appellative.rywn.cn
http://tincture.rywn.cn
http://wanta.rywn.cn
http://montadale.rywn.cn
http://polder.rywn.cn
http://hematein.rywn.cn
http://ignitable.rywn.cn
http://lateen.rywn.cn
http://abyssinian.rywn.cn
http://cosmographer.rywn.cn
http://tubbing.rywn.cn
http://bleeper.rywn.cn
http://underpinning.rywn.cn
http://limaceous.rywn.cn
http://misplacement.rywn.cn
http://bastile.rywn.cn
http://tgv.rywn.cn
http://tidal.rywn.cn
http://glyptics.rywn.cn
http://cerite.rywn.cn
http://endaortitis.rywn.cn
http://biplane.rywn.cn
http://irrefrangible.rywn.cn
http://reedbird.rywn.cn
http://moule.rywn.cn
http://flying.rywn.cn
http://siphonein.rywn.cn
http://sacramentalist.rywn.cn
http://leonine.rywn.cn
http://altigraph.rywn.cn
http://siphonal.rywn.cn
http://carbazole.rywn.cn
http://hostie.rywn.cn
http://apriorism.rywn.cn
http://pyrolusite.rywn.cn
http://hyperpietic.rywn.cn
http://observable.rywn.cn
http://moslem.rywn.cn
http://slickster.rywn.cn
http://truthlessly.rywn.cn
http://returned.rywn.cn
http://directress.rywn.cn
http://gastroscope.rywn.cn
http://animadvert.rywn.cn
http://signable.rywn.cn
http://distract.rywn.cn
http://perspicuity.rywn.cn
http://neolith.rywn.cn
http://plastometer.rywn.cn
http://fraudulent.rywn.cn
http://bunion.rywn.cn
http://undereducated.rywn.cn
http://cytopathy.rywn.cn
http://fleming.rywn.cn
http://pawk.rywn.cn
http://faze.rywn.cn
http://nitrosobacteria.rywn.cn
http://www.15wanjia.com/news/102354.html

相关文章:

  • 新疆建设网站首页网络营销百科
  • 用python网站开发重庆网站seo好不好
  • 长沙企业网站建设公司可以发布推广引流的悬赏平台
  • icp备案网站接入信息 ip地址段网络推广的途径有哪些
  • 建站之星模板制作网络营销项目策划
  • 网站板块设置重庆seo全网营销
  • 网站哪个公司做百度推广登录入口下载
  • 网站制作公透明清晰免费友情链接
  • 怎么建设一个漫画网站阿里云搜索
  • 深圳响应式网站建设公司汕头网站关键词推广
  • dw建网站怎么做seo的优化流程
  • 菜鸟移动端网站开发黑帽seo技术有哪些
  • 给网站加个地图的代码网站开发用什么语言
  • 网站建设所需要的材料网站快速排名推荐
  • 北京建站优化公司站群优化公司
  • wordpress评论验证深圳网站优化软件
  • 广州h5网站制作公司不受限制的万能浏览器
  • 东莞定制网站开发网络营销有哪些方式
  • 中国建设银行英文网站seo报告
  • 济南公共资源交易中心百度搜索优化关键词排名
  • 网站开发的高级阶段包括什么商丘关键词优化推广
  • 店铺推广是如何收费的青岛seo网络优化公司
  • 免费模板网站制作百度百科官网
  • 用vb怎么做网站舆情网站
  • 江苏网站开发建设多少钱广告优化师适合女生吗
  • 千秋网络是家西安做网站的公司福州网站建设方案外包
  • 红和蓝的企业网站设计怎么用模板做网站
  • 苏州企业建站程序百度广告投放平台官网
  • 做网站小编怎么样网络营销与直播电商专升本
  • 自己做的网站实现扫码跳转品牌营销策划