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

news2024/9/20 6:12:43

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 CompletionUsage

local_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 = True

class 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=None
                finish_reason='stop'
        else:
            finish_reason='stop'
            tool_calls = None

        message  = 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_oai

    def message_retrieval(self, response):
        """Retrieve the messages from the response."""
        choices = response.choices
        if 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 = 0
        return 0

    @staticmethod
    def get_usage(response):
        # returns a dict of prompt_tokens, completion_tokens, total_tokens, cost, model
        # if usage needs to be tracked, else None
        return {
            "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.0
    elif base_currency == "USD" and quote_currency == "EUR":
        return 1 / 1.1
    elif base_currency == "EUR" and quote_currency == "USD":
        return 1.1
    else:
        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_amount
    return 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.coloradmin.cn/o/2148205.html

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

相关文章

VS code 查看 ${workspaceFolder} 目录指代路径

VS code 查看 ${workspaceFolder} 目录指代路径 引言正文 引言 在 VS code 创建与运行 task.json 文件 一文中我们已经介绍了如何创建属于自己的 .json 文件。在 VS code 中&#xff0c;有时候我们需要添加一些文件路径供我们导入自定义包使用&#xff0c;此时&#xff0c;我们…

Github Wiki 超链接 转 码云Gitee Wiki 超链接

Github Wiki 超链接 转 码云Gitee Wiki 超链接 Github 是 &#xff1a;[[相对路径]] Gitee 是 &#xff1a;[链接文字](./相对路径) 查找&#xff1a;\[\[(.*?)\]\] 替换&#xff1a;[$1]\(./$1\) 或替换&#xff1a;**[$1]\(./$1\)** &#xff08;码云的超链接&#xff0c;很…

实战18-Card封装

import Card from ../../components/Card/Index; import rvp from ../../utils/resposive/rvIndex;Component export default struct DomesticService {build() {Column() {Card() {//默认插槽Text("DomesticService")}}.width(100%).margin({ top: rvp(43) })} } im…

2024 Python3.10 系统入门+进阶(十五):文件及目录操作

目录 一、文件IO操作1.1 创建或打开文件1.2 读取文件1.2.1 按行读取1.2.2 多行读取1.2.3 完整读取 1.3 写入文件1.3.1 写入字符串1.3.2 写入序列 1.4 上下文管理1.4.1 with语句的使用1.4.2 上下文管理器(拓展----可以学了面向对象之后再回来看) 1.5 文件的遍历 二、os.path模块…

大语言模型-教育方向数据集

大语言模型-教育方向数据集 编号论文数据集1Bitew S K, Hadifar A, Sterckx L, et al. Learning to Reuse Distractors to Support Multiple-Choice Question Generation in Education[J]. IEEE Transactions on Learning Technologies, 2022, 17: 375-390.Televic, NL, https…

79页 PPT华为项目管理经典培训教材(高级)

读者朋友大家好&#xff0c;最近有会员朋友咨询晓雯&#xff0c;需要《79页PPT华为项目管理经典培训教材》资料&#xff0c;欢迎大家文末扫码下载学习。 一、华为项目管理理念方法 &#xff08;一&#xff09;项目管理基本概念与方法 项目启动 明确项目目标&#xff1a;华为…

SAP B1 流程实操 - 营销单据销售部分(上)

背景 在 SAP B1 中&#xff0c;最重要的模块就是【销售】&#xff0c;企业可能不涉及生产和库存&#xff08;贸易公司&#xff09;&#xff0c;甚至不涉及采购&#xff08;服务业&#xff09;&#xff0c;但是一定会有基本的 销售。本文中我们讲解 销售 模块的基本核心&#x…

【QT】基于HTTP协议的网络应用程序

目录 1 HTTP概述 2 QT中实现高层网络操作的类 3 使用HTTP类请求数据 4 基于HTTP协议的网络文件下载 1 HTTP概述 HTTP&#xff08;超文本传输协议&#xff09;是互联网上应用最为广泛的协议之一&#xff0c;它定义了客户端和服务器之间进行通信的规则。HTTP是一种无状态的协议…

rcc 不是内部或外部命令,也不是可运行的程序或批处理文件

D:\Windows Kits\10\bin\10.0.22621.0\x86 将上述路径添加到环境变量中&#xff0c;重启电脑

【微服务-注册中心】

注册中心的作用&#xff1a; 微服务将业务拆分成了一个一个服务&#xff0c;当实现一个业务的时需要调用多个服务&#xff0c;那么每个服务的调用都需要知道它的URL。如何更方便的调用&#xff0c;注册中心就出现了。 我们可以把注册中心当作通讯录&#xff0c;通讯录中记录了服…

【JS】postMessage与MessageChannel

前言 postMessage 和 MessageChannel 都是用来实现跨文档、跨窗口或跨线程&#xff08;Web Worker&#xff09;的消息传递机制。 postMessage 可以在 iframe、同源或跨源窗口之间传递数据&#xff0c;也可以用于主线程与 Web Worker 之间的通信。 postMessage 是一种单向的…

Django 聚合查询

文章目录 一、聚合查询二、使用步骤1.准备工作2.具体使用3.分组查询&#xff08;annotate&#xff09;1.定义2.使用3.具体案例 4.F() 查询1.定义2.使用 5.Q() 查询1.定义2.查询 一、聚合查询 使用聚合查询前要先从 django.db.models 引入 Avg、Max、Min、Count、Sum&#xff0…

VS code EXPLORER 中不显示指定文件及文件夹设置(如.pyc, __pycache__, .vscode 文件)

VS code EXPLORER 中不显示指定文件及文件夹设置 引言正文方法1打开方式1打开方式2 方法2 引言 VS code 号称地表最强轻量级编译器&#xff0c;其最大的优势在于用户可以根据自己的需求下载适合自己的 extension。从而定制个性化的编译器。然而&#xff0c;本人今天遇到了一个…

如何调用API接口:一份简明指南

在软件开发中&#xff0c;调用API接口是一项基本而重要的技能。API&#xff08;应用程序编程接口&#xff09;允许不同程序之间进行交互&#xff0c;使得数据和功能可以跨应用程序共享。本文将为你提供一份简明的指南&#xff0c;帮助你理解如何调用API接口。 什么是API接口&am…

Android中的引用类型:Weak Reference, Soft Reference, Phantom Reference 和 WeakHashMap

在Android开发中&#xff0c;内存管理是一个非常重要的话题。为了更好地管理内存&#xff0c;Java和Android提供了多种引用类型&#xff0c;包括Weak Reference、Soft Reference、Phantom Reference以及WeakHashMap。这些引用类型在不同的场景下可以帮助我们更有效地管理内存&a…

(笔记)mac笔记本调节键盘速率

我在使用neovim的时候&#xff0c;发现按下hjkl或者shift[]来进行移动的时候 开始延迟大概几百毫秒的时间才开始移动 所以我上网找了下方法 发现修改这了可以改变速率 我就直接拉到了fast 芜湖 起飞 local opt vim.opt local o vim.o local g vim.go.timeoutlen 100 o…

论文速递!时序预测!DCSDNet:双卷积季节性分解网络,应用于天然气消费预测过程

本期推文将介绍一种新的时序预测方法:双卷积季节性分解网络&#xff08;Dual Convolution withSeasonal Decomposition Network, DCSDNet&#xff09;在天然气消费预测的应用&#xff0c;这项研究发表于《Applied Energy》期刊。 针对天然气消费的多重季节性和非规律性&#x…

汽车焊机数据通信:Profinet转Canopen网关的神奇连接

在汽车制造领域&#xff0c;汽车焊机的高效、稳定运行对于整车质量至关重要。而Profinet转Canopen网关在汽车焊机的数据通信中发挥着关键作用。 Profinet是一种广泛应用于工业自动化领域的通信协议&#xff0c;具有高速、实时、可靠等特点。Canopen则在汽车电子等领域有着广泛…

软件渗透测试流程有哪些?专业软件测评公司简析渗透测试的好处

软件渗透测试是进行软件安全测评的重要环节&#xff0c;旨在通过模拟攻击手段发现软件系统的脆弱性。这种安全测试方法能够帮助开发人员和系统管理员发现并修复潜在的安全漏洞&#xff0c;以确保软件系统的安全性和完整性。软件渗透测试是一项高度技术性的任务&#xff0c;需要…

口哨声、歌声、boing声和biotwang声:用AI识别鲸鱼叫声

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…