使用豆包大模型的function能力

什么是大模型function能力

专业角度

大模型的 function 一般指函数调用(Function Calling),是大模型可调用特定函数或方法来操作、处理数据的功能。
从实现看,需在请求参数给模型传函数信息,模型判断是否调用并返回相关内容,开发者据此调用函数,再将结果给模型获后续响应。其作用包括增强模型功能,能调用外部功能或 API 做更多事;提高数据准确性,可实时获取外部数据优化回答;提升用户体验,让用户用自然语言指令使模型高效完成复杂任务。它常用于实时信息检索、复杂计算、代码解释执行、个性化服务等场景。
 

说人话

让大模型执行自己定义的函数,并返回结果

支持模型

还有其他模型,可以自己看看

20250221230019700-image

 

大模型调用

在调用之前,确保创建好了接入点

https://console.volcengine.com/ark/region:ark+cn-beijing/endpoint?DefaultModel=doubao-pro-32k&DefaultModelVersion=241215&config=%7B%7D&projectName=undefined

20250221230210935-image

 

普通非流式

安装

npm install openai

调用

import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: ['ARK_API_KEY'],
  baseURL: 'https://ark.cn-beijing.volces.com/api/v3',
});

async function main() {
  // Non-streaming:
  console.log('----- standard request -----')
  const completion = await openai.chat.completions.create({
    messages: [
      { role: 'system', content: '你是人工智能助手' },
      { role: 'user', content: '常见的十字花科植物有哪些?' },
    ],
    model: 'doubao-1-5-pro-32k-250115',
  });
  console.log(completion.choices[0]?.message?.content);


}

main();

现在我开始问大模型天气问题,但是我又想让大模型使用我自己的代码,而不是大模型自己的,下面我将写一个函数,来模拟获取天气

// 模拟获取天气信息的函数
async function get_current_weather() {
  
    // 这里只是模拟返回数据,实际应调用真实的天气 API
    const mockWeather = {
        "city": "西安",
        "temperature": "15",
        "unit": "摄氏度",
        "forecast": "多云"
    };
    return JSON.stringify(mockWeather);
}

现在,我想要让大模型判断我要问天气意图的时候,调用上面这个函数,然后返回我模拟的天气信息

首先,在这里可以参考火山引擎的文档https://www.volcengine.com/docs/82379/1298454#function

从文档中得知,在请求大模型时,需要传tools参数

tools: [
    {
        type: 'function',
        function: {
            name: 'get_current_weather',
            description: '当让你获取天气的时候用它',
            parameters: {
                type: 'object',
                properties: {
                    location: {
                        type: 'string',
                        description: '需要查询天气'
                    },
                
                },
                required: ['location']
            }
        }
    }
],

整体结构

tools 是一个数组,其中每个元素代表一个可调用的工具,这里只有一个工具,其类型为 function,也就是函数调用工具。

具体字段解释

1. type

type: 'function'

指定工具的类型为函数调用。这告诉 豆包模型,当前提供了一个外部函数可供调用以完成特定任务。

2. function

这是一个对象,包含了函数的详细信息,具体如下:
name
name: 'get_current_weather'

函数的名称,模型在需要调用这个函数时,会使用这个名称来指定调用哪个函数。这里函数名为 get_current_weather,表示获取当前天气的函数。

description
description: '当让你获取天气的时候用它'

对函数功能的自然语言描述,帮助模型理解在什么情况下应该调用这个函数。当用户询问关于天气的问题时,模型就可能会判断需要调用 get_current_weather 函数。

parameters
parameters: {
    type: 'object',
    properties: {
        location: {
            type: 'string',
            description: '需要查询天气'
        }
    },
    required: ['location']
}
  • type: 'object':表示函数的参数是一个对象。
  • properties:定义了对象参数的各个属性。这里只有一个属性 location,它的类型是字符串,描述为 “需要查询天气”,意味着该属性用于指定要查询天气的地点。
  • required: ['location']:指定了参数对象中哪些属性是必需的。这里表示 location 属性是调用 get_current_weather 函数时必须提供的。

作用

通过提供这些函数信息,当用户输入 “今天西安天气” 时,模型会根据描述和参数信息,判断是否需要调用 get_current_weather 函数来获取天气信息。如果需要,模型会返回一个包含函数调用信息的响应,代码中后续会根据这个响应调用实际的函数并处理结果。
 
 
 

具体实现代码

import OpenAI from 'openai';

// 初始化 OpenAI 客户端
const openai = new OpenAI({
    apiKey: ['ARK_API_KEY'],
    baseURL: 'https://ark.cn-beijing.volces.com/api/v3',
});

// 模拟获取天气信息的函数
async function get_current_weather() {
  
    // 这里只是模拟返回数据,实际应调用真实的天气 API
    const mockWeather = {
        "city": "西安",
        "temperature": "15",
        "unit": "摄氏度",
        "forecast": "多云"
    };
    return JSON.stringify(mockWeather);
}

async function main() {
    console.log('----- non - streaming request -----');
    try {
        // 使用非流式模式获取完整响应
        const response = await openai.chat.completions.create({
            messages: [
                { role: 'system', content: '你是人工智能助手' },
                { role: 'user', content: '今天西安天气' },
            ],
            tools: [
            {
                type: 'function',
                function: {
                    name: 'get_current_weather',
                    description: '当让你获取天气的时候用它',
                    parameters: {
                        type: 'object',
                        properties: {
                            location: {
                                type: 'string',
                                description: '需要查询天气'
                            },
                        
                        },
                        required: ['location']
                    }
                }
            }
            ],
            model: 'ep-20250221150319-fj98h',
            // 关闭流式模式
            stream: false,
        });

        // console.log('Response:', response);
        const message = response.choices[0].message;
        // console.log('Message details:', message);

        if (message.tool_calls) {
            const toolCall = message.tool_calls[0];
            console.log('Tool call:', toolCall);
            if (toolCall.function.name === 'get_current_weather') {
                // 解析 arguments 字符串为对象
                const parameters = JSON.parse(toolCall.function.arguments.trim());
                console.log('Tool call parameters:', parameters);
                const weatherInfo = await get_current_weather(parameters);
                console.log('获取到的天气信息:', weatherInfo);
            }
        }
    } catch (error) {
        console.error('请求过程中出现错误:', error);
    }
}

main();

返回

返回的正是我们自定义的天气数据

----- non - streaming request -----
Tool call: {
  function: { arguments: ' {"location": "西安"}', name: 'get_current_weather' },
  id: 'call_ctr70ik47ss9lss9e4jkiv75',
  type: 'function'
}
Tool call parameters: { location: '西安' }
获取到的天气信息: {"city":"西安","temperature":"15","unit":"摄氏度","forecast":"多云"}

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容