/ Модель

Характеристики

Контекст
4 096 токенов
Параметры
6,5 млрд
Размер весов
13,8 ГБ
Лицензия
CC BY-NC 4.0
Архитектура
llama · dense
Библиотека
transformers
Опубликована
17 июл 2024

xLAM-7b-fc-r

Генерация текстаТекст → текст3 профессии

Компактная модель Salesforce для преобразования текстовых инструкций в структурированные вызовы функций и инструментов в агентных приложениях.

458скачиваний за 30 дней79лайковвеса обновлены11 апр 2025

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

xLAM-7b-fc-r — языковая модель семейства xLAM от Salesforce, предназначенная для вызова функций и использования инструментов в агентных приложениях. Это плотная авторегрессионная архитектура Llama с 6,5 млрд параметров по метаданным; карточка относит её к серии, дообученной на моделях DeepSeek-Coder, а датасет обучения указан как Salesforce/xlam-function-calling-60k. Модель принимает текстовые запросы и описания доступных API и генерирует структурированные ответы для вызова функций.

Модель подходит для автоматизации рабочих процессов и взаимодействия с цифровыми сервисами: например, агент может запросить погоду, управлять публикациями в соцсетях или обращаться к финансовым сервисам. README сообщает о результате 88,24% на Berkeley Function-Calling Leaderboard на дату оценки 18 июля 2024 года. Метаданные указывают контекст 4096 токенов и поддержку английского языка. Для запуска предусмотрены Transformers и vLLM; веса опубликованы в формате safetensors.

Лицензия CC-BY-NC-4.0 ограничивает коммерческое использование. Результат на бенчмарке относится к указанной конфигурации оценки, а фактическое качество зависит от формата API и сценария применения.

Сценарии применения

  • вызов API по инструкции на естественном языке
  • создание агента для получения прогноза погоды
  • автоматизация управления публикациями в социальных сетях
  • подготовка вызовов финансовых сервисов
  • интеграция LLM-агента с пользовательскими инструментами

Ограничения

Контекст модели составляет 4096 токенов по метаданным; коммерческое использование ограничено лицензией CC-BY-NC-4.0. Результат BFCL в README приведён для конкретной конфигурации и даты оценки.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Welcome to the xLAM model family! Large Action Models (LAMs) are advanced large language models designed to enhance decision-making and translate user intentions into executable actions that interact with the world. LAMs autonomously plan and execute tasks to achieve specific goals, serving as the brains of AI agents. They have the potential to automate workflow processes across various domains, making them invaluable for a wide range of applications.

Table of Contents

Model Series

We provide a series of xLAMs in different sizes to cater to various applications, including those optimized for function-calling and general agent applications:

Model# Total ParamsContext LengthRelease DateCategoryDownload ModelDownload GGUF files
xLAM-7b-r7.24B32kSep. 5, 2024General, Function-calling🤗 Link--
xLAM-8x7b-r46.7B32kSep. 5, 2024General, Function-calling🤗 Link--
xLAM-8x22b-r141B64kSep. 5, 2024General, Function-calling🤗 Link--
xLAM-1b-fc-r1.35B16kJuly 17, 2024Function-calling🤗 Link🤗 Link
xLAM-7b-fc-r6.91B4kJuly 17, 2024Function-calling🤗 Link🤗 Link
xLAM-v0.1-r46.7B32kMar. 18, 2024General, Function-calling🤗 Link--

The fc series of models are optimized for function-calling capability, providing fast, accurate, and structured responses based on input queries and available APIs. These models are fine-tuned based on the deepseek-coder models and are designed to be small enough for deployment on personal devices like phones or computers.

We also provide their quantized GGUF files for efficient deployment and execution. GGUF is a file format designed to efficiently store and load large language models, making GGUF ideal for running AI models on local devices with limited resources, enabling offline functionality and enhanced privacy.

For more details, check our GitHub and paper.

Repository Overview

This repository is focused on our small xLAM-7b-fc-r model, which is optimized for function-calling and can be easily deployed on personal devices.

Function-calling, or tool use, is one of the key capabilities for AI agents. It requires the model not only understand and generate human-like text but also to execute functional API calls based on natural language instructions. This extends the utility of LLMs beyond simple conversation tasks to dynamic interactions with a variety of digital services and applications, such as retrieving weather information, managing social media platforms, and handling financial services.

The instructions will guide you through the setup, usage, and integration of xLAM-7b-fc-r with HuggingFace and vLLM. We will first introduce the basic usage, and then walk through the provided tutorial and example scripts in the examples folder.

Framework Versions

  • Transformers 4.41.0
  • Pytorch 2.3.0+cu121
  • Datasets 2.19.1
  • Tokenizers 0.19.1

Benchmark Results

We mainly test our function-calling models on the Berkeley Function-Calling Leaderboard (BFCL), which offers a comprehensive evaluation framework for assessing LLMs' function-calling capabilities across various programming languages and application domains like Java, JavaScript, and Python.

See our paper and Github repo for more detailed analysis.

Usage

Basic Usage with Huggingface

To use the xLAM-7b-fc-r model from Huggingface, please first install the transformers library:

pip install transformers>=4.41.0

We use the following example to illustrate how to use our model to perform function-calling tasks. Please note that, our model works best with our provided prompt format. It allows us to extract JSON output that is similar to the function-calling mode of ChatGPT.

import json
import torch 
from transformers import AutoModelForCausalLM, AutoTokenizer

torch.random.manual_seed(0) 

model_name = "Salesforce/xLAM-7b-fc-r"
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name) 

# Please use our provided instruction prompt for best performance
task_instruction = """
You are an expert in composing functions. You are given a question and a set of possible functions. 
Based on the question, you will need to make one or more function/tool calls to achieve the purpose. 
If none of the functions can be used, point it out and refuse to answer. 
If the given question lacks the parameters required by the function, also point it out.
""".strip()

format_instruction = """
The output MUST strictly adhere to the following JSON format, and NO other text MUST be included.
The example format is as follows. Please make sure the parameter type is correct. If no function call is needed, please make tool_calls an empty list '[]'.
```
{
    "tool_calls": [
    {"name": "func_name1", "arguments": {"argument1": "value1", "argument2": "value2"}},
    ... (more tool calls as required)
    ]
}
```
""".strip()

# Define the input query and available tools
query = "What's the weather like in New York in fahrenheit?"

get_weather_api = {
    "name": "get_weather",
    "description": "Get the current weather for a location",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, New York"
            },
            "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "The unit of temperature to return"
            }
        },
        "required": ["location"]
    }
}

search_api = {
    "name": "search",
    "description": "Search for information on the internet",
    "parameters": {
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": "The search query, e.g. 'latest news on AI'"
            }
        },
        "required": ["query"]
    }
}

openai_format_tools = [get_weather_api, search_api]

# Helper function to convert openai format tools to our more concise xLAM format
def convert_to_xlam_tool(tools):
    ''''''
    if isinstance(tools, dict):
        return {
            "name": tools["name"],
            "description": tools["description"],
            "parameters": {k: v for k, v in tools["parameters"].get("properties", {}).items()}
        }
    elif isinstance(tools, list):
        return [convert_to_xlam_tool(tool) for tool in tools]
    else:
        return tools

# Helper function to build the input prompt for our model
def build_prompt(task_instruction: str, format_instruction: str, tools: list, query: str):
    prompt = f"[BEGIN OF TASK INSTRUCTION]\n{task_instruction}\n[END OF TASK INSTRUCTION]\n\n"
    prompt += f"[BEGIN OF AVAILABLE TOOLS]\n{json.dumps(xlam_format_tools)}\n[END OF AVAILABLE TOOLS]\n\n"
    prompt += f"[BEGIN OF FORMAT INSTRUCTION]\n{format_instruction}\n[END OF FORMAT INSTRUCTION]\n\n"
    prompt += f"[BEGIN OF QUERY]\n{query}\n[END OF QUERY]\n\n"
    return prompt
    
# Build the input and start the inference
xlam_format_tools = convert_to_xlam_tool(openai_format_tools)
content = build_prompt(task_instruction, format_instruction, xlam_format_tools, query)

messages=[
    { 'role': 'user', 'content': content}
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)

# tokenizer.eos_token_id is the id of <|EOT|> token
outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
print(tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True))

Then you should be able to see the following output string in JSON format:

{"tool_calls": [{"name": "get_weather", "arguments": {"location": "New York", "unit": "fahrenheit"}}]}

We highly recommend to use our provided prompt format and helper functions to yield the best function-calling performance of our model.

Usage with vLLM

We provide example scripts to deploy our model with vllm and run inferences. First, install the required packages:

pip install vllm openai argparse jinja2

The example scripts are located in the examples folder.

1. Test Prompt Template

To build prompts using the chat template and output formatted prompts ready for various test cases, run:

python test_prompt_template.py --model 

2. Test xLAM Model with a Manually Served Endpoint

a. Serve the model with vLLM:

python -m vllm.entrypoints.openai.api_server --model Salesforce/xLAM-7b-fc-r --served-model-name xLAM-7b-fc-r --dtype bfloat16 --port 8001

b. Run the test script:

python test_xlam_model_with_endpoint.py --model_name xLAM-7b-fc-r --port 8001 [OPTIONS]

Options:

  • --temperature: Default 0.3
  • --top_p: Default 1.0
  • --max_tokens: Default 512

This test script provides a handler implementation that can be easily applied to your customized function-calling applications.

3. Test xLAM Model by Directly Using vLLM Library

To test the xLAM model directly with the vLLM library, run:

python test_xlam_model_with_vllm.py --model Salesforce/xLAM-7b-fc-r [OPTIONS]

Options are the same as for the endpoint test. This test script also provides a handler implementation that can be easily applied to your customized function-calling applications.

Customization

These examples are designed to be flexible and easily integrated into your own projects. Feel free to modify the scripts to suit your specific needs and applications. You can adjust test queries or API definitions in each script to test different scenarios or model capabilities.

Additional customization tips:

  • Modify the --dtype parameter when serving the model based on your GPU capacity.
  • Refer to the vLLM documentation for more detailed configuration options.
  • Explore the demo.ipynb file for a comprehensive description of the entire workflow, including how to execute APIs.

These resources provide a robust foundation for integrating xLAM models into your applications, allowing for tailored and efficient deployment.

License

xLAM-7b-fc-r is distributed under the CC-BY-NC-4.0 license, with additional terms specified in the Deepseek license.

Ethical Considerations

This release is for research purposes only in support of an academic paper. Our models, datasets, and code are not specifically designed or evaluated for all downstream purposes. We strongly recommend users evaluate and address potential concerns related to accuracy, safety, and fairness before deploying this model. We encourage users to consider the common limitations of AI, comply with applicable laws, and leverage best practices when selecting use cases, particularly for high-risk scenarios where errors or misuse could significantly impact people’s lives, rights, or safety. For further guidance on use cases, refer to our AUP and AI AUP.

Citation

If you find this repo helpful, please cite our paper:

@article{zhang2024xlam,
  title={xlam: A family of large action models to empower ai agent systems},
  author={Zhang, Jianguo and Lan, Tian and Zhu, Ming and Liu, Zuxin and Hoang, Thai and Kokane, Shirley and Yao, Weiran and Tan, Juntao and Prabhakar, Akshara and Chen, Haolin and others},
  journal={arXiv preprint arXiv:2409.03215},
  year={2024}
}

@article{liu2024apigen,
  title={APIGen: Automated Pipeline for Generating Verifiable and Diverse Function-Calling Datasets},
  author={Liu, Zuxin and Hoang, Thai and Zhang, Jianguo and Zhu, Ming and Lan, Tian and Kokane, Shirley and Tan, Juntao and Yao, Weiran and Liu, Zhiwei and Feng, Yihao and others},
  journal={arXiv preprint arXiv:2406.18518},
  year={2024}

@article{zhang2025actionstudio,
  title={ActionStudio: A Lightweight Framework for Data and Training of Action Models},
  author={Zhang, Jianguo and Hoang, Thai and Zhu, Ming and Liu, Zuxin and Wang, Shiyu and Awalgaonkar, Tulika and Prabhakar, Akshara and Chen, Haolin and Yao, Weiran and Liu, Zhiwei and others},
  journal={arXiv preprint arXiv:2503.22673},
  year={2025}
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers

Можно запустить

Подбираем GPU…

Класс архитектуры
LlamaForCausalLM
Ревизия весов
42587ba

0 моделей