python AutoGen接入开源模型xLAM-7b-fc-r,测试function calling的功能

AutoGen主打的是多智能体,对话和写代码,但是教程方面没有langchain丰富,我这里抛砖引玉提供一个autogen接入开源function calling模型的教程,我这里使用的开源repo是:https://github.com/SalesforceAIResearch/xLAM
开源模型是:https://huggingface.co/Salesforce/xLAM-7b-fc-r

1b的模型效果有点差,推荐使用7b的模型。首先使用vllm运行:

vllm serve Salesforce/xLAM-8x7b-r --host 0.0.0.0 --port 8000 --tensor-parallel-size 4

然后autogen代码示例:

import re
import json
import random
import time from typing import Literal
from pydantic import BaseModel, Field
from typing_extensions import Annotated
import autogen
from autogen.cache import Cache
from openai.types.completion import Completion
import openai
from xLAM.client import xLAMChatCompletion, xLAMConfig
from openai.types.chat import ChatCompletion, ChatCompletionMessageToolCall
from openai.types.chat.chat_completion import ChatCompletionMessage, Choice
from openai.types.completion_usage import CompletionUsagelocal_llm_config={"config_list": [{"model": "/<your_path>/xLAM-7b-fc-r", # Same as in vLLM command"api_key": "NotRequired", # Not needed"model_client_cls": "CustomModelClient","base_url": "http://localhost:8000/v1",  # Your vLLM URL, with '/v1' added"price": [0, 0],}],"cache_seed": None # Turns off caching, useful for testing different models
}TOOL_ENABLED = Trueclass CustomModelClient:def __init__(self, config, **kwargs):print(f"CustomModelClient config: {config}")gen_config_params = config.get("params", {})self.max_length = gen_config_params.get("max_length", 256)print(f"Loaded model {config['model']}")config = xLAMConfig(base_url=config["base_url"], model=config['model'])self.llm = xLAMChatCompletion.from_config(config)def create(self, params):if params.get("stream", False) and "messages" in params:raise NotImplementedError("Local models do not support streaming.")else:if "tools" in params:tools=[item['function'] for item in params["tools"]]response = self.llm.completion(params["messages"], tools=tools)if len(response['choices'][0]['message']['tool_calls'])>0:finish_reason='tool_calls'tool_results = response['choices'][0]['message']['tool_calls']if isinstance(tool_results, list) and isinstance(tool_results[0], list):tool_results = tool_results[0]tool_calls = []try:for tool_call in tool_results:tool_calls.append(ChatCompletionMessageToolCall(id=str(random.randint(0,2500)),function={"name": tool_call['name'], "arguments": json.dumps(tool_call["arguments"])},type="function"))except Exception as e:print("Tool parse error: {tool_results}")tool_calls=Nonefinish_reason='stop'else:finish_reason='stop'tool_calls = Nonemessage  = ChatCompletionMessage(role="assistant",content=response['choices'][0]['message']['content'],function_call=None,tool_calls=tool_calls,)choices = [Choice(finish_reason=finish_reason, index=0, message=message)]response_oai = ChatCompletion(id=str(random.randint(0,25000)),model=params["model"],created=int(time.time()),object="chat.completion",choices=choices,usage=CompletionUsage(prompt_tokens=0,completion_tokens=0,total_tokens=0),cost=0.0,)return response_oaidef message_retrieval(self, response):"""Retrieve the messages from the response."""choices = response.choicesif isinstance(response, Completion):return [choice.text for choice in choices] if TOOL_ENABLED:return [  # type: ignore [return-value](choice.message  # type: ignore [union-attr]if choice.message.function_call is not None or choice.message.tool_calls is not None  # type: ignore [union-attr]else choice.message.content)  # type: ignore [union-attr]for choice in choices]else:return [  # type: ignore [return-value]choice.message if choice.message.function_call is not None else choice.message.content  # type: ignore [union-attr]for choice in choices]def cost(self, response) -> float:"""Calculate the cost of the response."""response.cost = 0return 0@staticmethoddef get_usage(response):# returns a dict of prompt_tokens, completion_tokens, total_tokens, cost, model# if usage needs to be tracked, else Nonereturn {"prompt_tokens": response.usage.prompt_tokens if response.usage is not None else 0,"completion_tokens": response.usage.completion_tokens if response.usage is not None else 0,"total_tokens": (response.usage.prompt_tokens + response.usage.completion_tokens if response.usage is not None else 0),"cost": response.cost if hasattr(response, "cost") else 0,"model": response.model,}chatbot = autogen.AssistantAgent(name="chatbot",system_message="For currency exchange tasks, only use the functions you have been provided with. Reply TERMINATE when the task is done.",llm_config=local_llm_config,
)# create a UserProxyAgent instance named "user_proxy"
user_proxy = autogen.UserProxyAgent(name="user_proxy",is_termination_msg=lambda x: x.get("content", "") and x.get("content", "").rstrip().endswith("TERMINATE"),human_input_mode="NEVER",max_consecutive_auto_reply=5,
)CurrencySymbol = Literal["USD", "EUR"]def exchange_rate(base_currency: CurrencySymbol, quote_currency: CurrencySymbol) -> float:if base_currency == quote_currency:return 1.0elif base_currency == "USD" and quote_currency == "EUR":return 1 / 1.1elif base_currency == "EUR" and quote_currency == "USD":return 1.1else:raise ValueError(f"Unknown currencies {base_currency}, {quote_currency}")@user_proxy.register_for_execution()
@chatbot.register_for_llm(description="Currency exchange calculator.")
def currency_calculator(base_amount: Annotated[float, "Amount of currency in base_currency"],base_currency: Annotated[CurrencySymbol, "Base currency"] = "USD",quote_currency: Annotated[CurrencySymbol, "Quote currency"] = "EUR",
) -> str:quote_amount = exchange_rate(base_currency, quote_currency) * base_amountreturn f"{quote_amount} {quote_currency}"print(chatbot.llm_config["tools"])
chatbot.register_model_client(model_client_cls=CustomModelClient)
query = "How much is 123.45 USD in EUR?"
# query = "What's the weather like in New York in fahrenheit?"
res = user_proxy.initiate_chat(chatbot, message=query,max_round=5,)
print("Chat history:", res.chat_history)

运行示例结果:

user_proxy (to chatbot):How much is 123.45 USD in EUR?--------------------------------------------------------------------------------
chatbot (to user_proxy):***** Suggested tool call (507): currency_calculator *****
Arguments:
{"base_amount": 123.45, "base_currency": "USD", "quote_currency": "EUR"}
**********************************************************-------------------------------------------------------------------------------->>>>>>>> EXECUTING FUNCTION currency_calculator...
user_proxy (to chatbot):user_proxy (to chatbot):***** Response from calling tool (507) *****
112.22727272727272 EUR
********************************************--------------------------------------------------------------------------------
chatbot (to user_proxy):The currency calculator returned 112.23 EUR.--------------------------------------------------------------------------------
user_proxy (to chatbot):

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

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

安卓13长按电源按键直接关机 andriod13不显示关机对话框直接关机

总纲 android13 rom 开发总纲说明 文章目录 1.前言2.问题分析3.代码分析4.代码修改5.编译6.彩蛋1.前言 有些设备需要在长按电源键的时候,直接关机。不需要弹出对话框进行询问。 2.问题分析 过滤电源按键,需要在系统里面处理的话,那么我们需要熟悉android的事件分发,然后再…

L67 【哈工大_操作系统】操作系统历史 学习任务

L6 操作系统历史 线条一 1、上古神机 IBM7094 专注于计算批处理操作系统&#xff08;Batch system&#xff09; 2、OS/360 一台计算机干多种事&#xff0c;多道程序作业之间的 切换和调度 成为核心 &#xff08;多进程结构和进程管理概念萌芽&#xff01;&#xff09; 3…

链式栈讲解

文章目录 &#x1f34a;自我介绍&#x1f34a;链式栈入栈和出栈linkstack.hlinkstack.c 你的点赞评论就是对博主最大的鼓励 当然喜欢的小伙伴可以&#xff1a;点赞关注评论收藏&#xff08;一键四连&#xff09;哦~ &#x1f34a;自我介绍 Hello,大家好&#xff0c;我是小珑也要…

《黑神话悟空》开发框架与战斗系统解析

本文主要围绕《黑神话悟空》的开发框架与战斗系统解析展开 主要内容 《黑神话悟空》采用的技术栈 《黑神话悟空》战斗系统的实现方式 四种攻击模式 连招系统的创建 如何实现高扩展性的战斗系统 包括角色属性系统、技能配置文件和逻辑节点的抽象等关键技术点 版权声明 本…

考研数据结构——C语言实现有向图邻接矩阵

首先&#xff0c;定义了一些基本的数据结构和常量&#xff1a; VertexType&#xff1a;顶点的数据类型&#xff0c;这里定义为char。EdgeType&#xff1a;边的数据类型&#xff0c;这里定义为int&#xff0c;用于存储权重。MAXVEX&#xff1a;定义了图中最大顶点数为100。INFIN…

详细解读,F5服务器负载均衡的技术优势

在现代大规模、高流量的网络使用场景中&#xff0c;为应对高并发和海量数据的挑战&#xff0c;服务器负载均衡技术应运而生。但凡知道服务器负载均衡这一名词的&#xff0c;基本都对F5有所耳闻&#xff0c;因为负载均衡正是F5的代表作&#xff0c;换句通俗易懂的话来说&#xf…

前端vue-关于标签切换的实现

首先是循环&#xff0c;使用v-for“&#xff08;item,index) in list” :key“item.id” 然后当点击哪个的时候再切换&#xff0c;使用v-bind:class" "或者是:class" ",如果都是用active的话&#xff0c;那么每一个标签都是被选中的状态&#xff0c;…

Android IME输入法启动显示隐藏流程梳理

阅读Android AOSP 12版本代码&#xff0c;对输入法IME整体框架模块进行学习梳理&#xff0c;内容包含输入法框架三部分IMM、IMMS、IMS的启动流程、点击弹出流程、显示/隐藏流程&#xff0c;以及常见问题和调试技巧。 1. IME整体框架​​​​​​​ IME整体分为三个部分&#xf…

Log4j2—漏洞分析(CVE-2021-44228)

文章目录 Log4j2漏洞原理漏洞根因调用链源码分析调用链总结 漏洞复现dnsrmi Log4j2漏洞原理 前排提醒&#xff1a;本篇文章基于我另外一篇总结的JNDI注入后写的&#xff0c;建议先看该文章进行简单了解JNDI注入&#xff1a; https://blog.csdn.net/weixin_60521036/article/de…

茴香豆:企业级知识问答工具实践闯关任务

基础任务 在 InternStudio 中利用 Internlm2-7b 搭建标准版茴香豆知识助手&#xff0c;并使用 Gradio 界面完成 2 轮问答&#xff08;问题不可与教程重复&#xff0c;作业截图需包括 gradio 界面问题和茴香豆回答&#xff09;。知识库可根据根据自己工作、学习或感兴趣的内容调…

50页PPT麦肯锡精益运营转型五步法

读者朋友大家好&#xff0c;最近有会员朋友咨询晓雯&#xff0c;需要《 50页PPT麦肯锡精益运营转型五步法》资料&#xff0c;欢迎大家下载学习。 知识星球已上传的资料链接&#xff1a; 企业架构 企业架构 (EA) 设计咨询项目-企业架构治理(EAM)现状诊断 105页PPTHW企业架构设…

unity将多层嵌套的结构体与json字符串相互转化

定义多个结构体&#xff0c;将结构体内容输入到最终的JObject中&#xff0c;然后将其转为字符串打印出来&#xff0c;即可。 代码内容如下&#xff1a; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine;public class Test : MonoBehaviour {private Ap…

【开源大模型生态9】百度的文心大模型

这张图展示了百度千帆大模型平台的功能架构及其与BML-AI开发平台和百度百舸AI异构计算平台的关系。以下是各个模块的解释&#xff1a; 模型广场&#xff1a; 通用大模型&#xff1a;提供基础的自然语言处理能力。行业大模型&#xff1a;针对不同行业的定制化模型。大模型工具链…

android10 系统定制:增加应用使用数据埋点,应用使用时长统计

需求意在统计应用的使用时长和开始结束时间&#xff0c;最终生成一个文件可以直观看出什么时候进入了哪个应用、什么时候退出&#xff0c;如图&#xff1a; 每行记录了应用的进入或退出&#xff0c;以逗号分割。分别记录了事件开始时间&#xff0c;应用包名&#xff0c;进入或…

51单片机——直流电机驱动

1、直流电机介绍 直流电机是一种将电能转换为机械能的装置。一般的直流电机有两个电极&#xff0c;当电极正接时&#xff0c;电机正转&#xff0c;当电极反接时&#xff0c;电机反转。 直流电机主要由永磁体&#xff08;定子&#xff09;、线圈&#xff08;转子&#xff09;和…

YoloV10改进策略:BackBone改进|Next-ViT主干赋能下的革命性改进

摘要 Next-ViT(下一代视觉Transformer)是专为解决传统ViT模型在工业部署中遇到的推理速度慢、计算复杂度高等问题而设计的。它巧妙地结合了高效的Next Convolution Block(NCB)和Next Transformer Block(NTB),通过创新的混合策略(NHS)堆叠这些模块,从而在各种视觉任务…

驱动---动态模块编译

动态模块编译 ctags 用法 创建文件 ------- ctags -R 一定要在顶层目录下 1&#xff0e; ctags –R * 2. vi –t tag (请把tag替换为您欲查找的变量或函数名) 3&#xff0e; Ctrl ] (跳转到要找的目标) 4&#xff0e; Ctrl T (回跳) 5&#xff0e; set tag/p…

计算机的错误计算(九十八)

摘要 探讨 的计算精度问题。 由计算机的错误计算&#xff08;九十六&#xff09;知&#xff0c;IEEE 754-2019标准中含有 运算。 另外&#xff0c;似乎没有语言直接编程实现内置了该运算。 例1. 已知 x-0.9999999999321 . 计算 不妨用Java编程计算&#xff1a; import…

【linux】基础IO(上)

1. 共识原理 文件 内容 属性文件分为 打开的文件 没打开的文件打开的文件 &#xff1a; 是进程打开的 ----- 本质是要研究文件和进程的关系没打开的文件 &#xff1a; 没打开的文件储存在磁盘上&#xff0c;由于没打开的文件很多&#xff0c;所以需要分门别类的防止好&…

【Linux实用教程】-03-用户权限命令

点个关注吧 &#x1f334; 3.1 Linux 的用户和组 &#x1f33e;3.1.1 用户的管理 添加用户 useradd 添加一个用户useradd test 添加 test 用户useradd test -d /home/t1 指定用户 home 目录 注意&#xff1a; 用户操作需要使用管理员权限操作&#xff0c;可以先使用…