首页
/ Gorilla OpenFunctions v2:开源模型中的函数调用技术解析

Gorilla OpenFunctions v2:开源模型中的函数调用技术解析

2025-07-06 04:21:48作者:龚格成

概述

Gorilla OpenFunctions v2 是一个基于大型语言模型(LLM)的创新性功能扩展,它能够将自然语言指令转化为可执行的API调用。作为Apache 2.0许可下的开源项目,它在开源模型领域达到了与GPT-4相媲美的技术水平。

核心功能

OpenFunctions v2 提供了多项突破性功能:

  1. 多函数选择:系统能够在多个可用函数中选择最合适的
  2. 并行函数调用:同一函数可以同时使用不同参数值进行多次调用
  3. 混合模式:同时支持多函数选择和并行调用
  4. 相关性检测:智能区分普通对话和函数调用请求
  5. 多语言支持
    • Python:支持string、number、boolean、list、tuple、dict等数据类型
    • JAVA:支持byte、short、int、float等基础类型及集合类
    • JavaScript:支持String、Number、Boolean等类型
  6. 原生REST支持:直接处理REST API调用

模型版本对比

模型版本 主要功能
v2 完整功能集:多函数、并行、混合模式、多语言支持
v1 基础并行功能和函数选择能力
v0 单一函数调用和参数格式化

使用指南

云端调用示例

  1. 安装必要的Python包:
pip install openai==0.28.1
  1. 配置并调用Gorilla服务:
import openai

def get_gorilla_response(prompt="帮我叫一辆Uber", model="gorilla-openfunctions-v2", functions=[]):
    openai.api_key = "EMPTY"
    openai.api_base = "http://luigi.millennium.berkeley.edu:8000/v1"
    try:
        completion = openai.ChatCompletion.create(
            model=model,
            temperature=0.0,
            messages=[{"role": "user", "content": prompt}],
            functions=functions,
        )
        return completion.choices[0]
    except Exception as e:
        print(e, model, prompt)
  1. 构建查询和函数定义:
query = "查询波士顿和旧金山两地的天气"
functions = [
    {
        "name": "get_current_weather",
        "description": "获取指定位置的当前天气",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["location"],
        },
    }
]
response = get_gorilla_response(query, functions=functions)

本地部署指南

  1. 创建Python环境:
conda create -n openfunctions python=3.10
conda activate openfunctions
pip install -r requirements.txt
  1. 使用本地模型进行推理:
def get_prompt(user_query: str, functions: list = []) -> str:
    system = "你是一个AI编程助手..."
    if not functions:
        return f"{system}\n### 指令: <<问题>> {user_query}\n### 响应: "
    return f"{system}\n### 指令: <<函数>>{json.dumps(functions)}\n<<问题>>{user_query}\n### 响应: "

def format_response(response: str):
    try:
        response = strip_function_calls(response)
        if len(response) > 1:  # 并行调用
            return ", ".join(response), [parse_function_call(fc) for fc in response]
        return response[0], parse_function_call(response[0])
    except Exception:
        return response, None

技术特点

  1. 双输出格式:同时提供可读字符串和结构化JSON输出
  2. 参数完整性:确保输出包含参数名而不仅仅是值
  3. 错误恢复:当JSON解析失败时回退到字符串输出
  4. 多语言适配:针对不同编程语言优化参数处理

性能评估

项目提供了在线评估平台,实时跟踪模型在函数调用任务上的表现。评估标准包括:

  • 函数选择准确性
  • 参数提取正确率
  • 多函数处理能力
  • 并行调用效率

应用场景

  1. 智能助手开发:构建能够执行复杂操作的对话系统
  2. 自动化工作流:将自然语言指令转化为系统操作
  3. 多服务集成:统一不同API的调用方式
  4. 教育工具:帮助学生理解编程概念和API使用

总结

Gorilla OpenFunctions v2代表了开源模型在函数调用领域的重要进展,其多语言支持、并行处理能力和智能函数选择机制使其成为开发复杂应用的强大工具。无论是云端服务还是本地部署,都能为开发者提供灵活高效的解决方案。