/ Модель

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

Библиотека
transformers
Опубликована
2 дек 2023

openchat_3.5-function-calling-v3

Генерация текстаТекст → текст

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

0скачиваний за 30 дней21лайквеса обновлены6 мар 2024

Бенчмарки

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

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

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

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

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

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

Trelis/openchat_3.5-function-calling-v3 — дообученная Trelis модель OpenChat 3.5 для диалогов с вызовом функций. Она предназначена для приложений, где модель выбирает подходящие функции, формирует вызовы и может связывать несколько вызовов, используя результат одного для подготовки следующего. В карточке приведён шаблон OpenChat для передачи описаний функций и вопроса пользователя; модель поддерживает чат. Для варианта в ветке multi-lingual заявлены английский, испанский и китайский языки, особенно для вызова функций на английском и испанском. Базовая серия OpenChat 3.5 описана как модель на 7 млрд параметров, однако точный размер этой версии в метаданных не приведён.

Модель основана на OpenChat и обучена для вызова функций на данных Trelis/function_calling_v3. Карточка указывает на коммерческое использование; в приведённой таблице OpenChat 3.5 указана лицензия Apache-2.0. Метаданные сообщают о формате safetensors, а README также упоминает GGUF-файлы в форматах 2, 4 и 8 бит. Для многоязычного варианта отмечена ошибка: модель может продолжать вызывать функции, когда следует ответить на исходный вопрос с учётом результата вызова. Также возможны галлюцинации и небезопасные или предвзятые ответы; важные результаты следует проверять.

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

  • вызов функции по запросу пользователя
  • последовательный вызов нескольких функций с передачей результатов между ними
  • подготовка структурированных запросов к инструментам из описаний функций
  • создание чат-ассистента с подключёнными функциями

Ограничения

Многоязычный вариант может продолжать вызывать функции вместо ответа по уже полученной информации. Возможны галлюцинации, предвзятые или небезопасные ответы; результаты следует проверять.

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

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

Открыть на Hugging Face

Function Calling Fine-tuned OpenChat

The model is suitable for commercial use and may be purchased here.

It is one of the best function calling models - particularly for its size - and is capable of chaining multiple calls (i.e. call a first function to get info required to call a second function).

  • GGUF files are available in 2, 4 and 8-bit formats.
  • A multi-lingual (English, Spanish, Chinese) is available in the 'multi-lingual' branch. This is good for function calling, particularly in English and Spanish, but can erroneously continue to call functions when asked to respond to the original question taking into account information from the function response.

Quick Server Setup

Runpod one click template here. You must add a HuggingFace Hub access token (HUGGING_FACE_HUB_TOKEN) to the environment variables as this is a gated model.

Runpod Affiliate Link (helps support the Trelis channel).

Inference Scripts

See below for sample prompt format.

Complete inference scripts are available for purchase here:

  • Easily format prompts using tokenizer.apply_chat_format (starting from openai formatted functions and a list of messages)
  • Automate catching, handling and chaining of function calls.

Prompt Format

B_FUNC, E_FUNC = "You have access to the following functions. Use them if required:\n\n", "\n\n"
B_INST, E_INST = "GPT4 Correct User: ", "<|end_of_turn|>GPT4 Correct Assistant:\n\n" #OpenChat style
prompt = f"{B_INST}{B_FUNC}{FUNCTION_METADATA}{E_FUNC}{user_prompt.strip()}{E_INST}\n\n"

Using tokenizer.apply_chat_template

For an easier application of the prompt, you can set up as follows:

Set up messages:

[
    {
        "role": "function_metadata",
        "content": "FUNCTION_METADATA"
    },
    {
        "role": "user",
        "content": "What is the current weather in London?"
    },
    {
        "role": "function_call",
        "content": "{\n    \"name\": \"get_current_weather\",\n    \"arguments\": {\n        \"city\": \"London\"\n    }\n}"
    },
    {
        "role": "function_response",
        "content": "{\n    \"temperature\": \"15 C\",\n    \"condition\": \"Cloudy\"\n}"
    },
    {
        "role": "assistant",
        "content": "The current weather in London is Cloudy with a temperature of 15 Celsius"
    }
]

with FUNCTION_METADATA as:

[
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "This function gets the current weather in a given city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "The city, e.g., San Francisco"
                    },
                    "format": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "The temperature unit to use."
                    }
                },
                "required": ["city"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_clothes",
            "description": "This function provides a suggestion of clothes to wear based on the current weather",
            "parameters": {
                "type": "object",
                "properties": {
                    "temperature": {
                        "type": "string",
                        "description": "The temperature, e.g., 15 C or 59 F"
                    },
                    "condition": {
                        "type": "string",
                        "description": "The weather condition, e.g., 'Cloudy', 'Sunny', 'Rainy'"
                    }
                },
                "required": ["temperature", "condition"]
            }
        }
    }    
]

and then apply the chat template to get a formatted prompt:

tokenizer = AutoTokenizer.from_pretrained('Trelis/openchat_3.5-function-calling-v3', trust_remote_code=True)

prompt = tokenizer.apply_chat_template(prompt, tokenize=False)

If you are using a gated model, you need to first run:

pip install huggingface_hub
huggingface-cli login

Manual Prompt:

GPT4 Correct User: You have access to the following functions. Use them if required:

[
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "This function gets the current weather in a given city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "The city, e.g., San Francisco"
                    },
                    "format": {
                        "type": "string",
                        "enum": [
                            "celsius",
                            "fahrenheit"
                        ],
                        "description": "The temperature unit to use."
                    }
                },
                "required": [
                    "city"
                ]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_clothes",
            "description": "This function provides a suggestion of clothes to wear based on the current weather",
            "parameters": {
                "type": "object",
                "properties": {
                    "temperature": {
                        "type": "string",
                        "description": "The temperature, e.g., 15 C or 59 F"
                    },
                    "condition": {
                        "type": "string",
                        "description": "The weather condition, e.g., 'Cloudy', 'Sunny', 'Rainy'"
                    }
                },
                "required": [
                    "temperature",
                    "condition"
                ]
            }
        }
    }
]

What is the current weather in London?<|end_of_turn|>GPT4 Correct Assistant:

{
    "name": "get_current_weather",
    "arguments": {
        "city": "London"
    }
}<|end_of_turn|>GPT4 Correct User:


This will give a response of:

{
    "temperature": "15 C",
    "condition": "Cloudy"
}<|end_of_turn|>

Dataset

See Trelis/function_calling_v3.

License

This model may be used commercially for inference, or for further fine-tuning and inference. Users may not re-publish or re-sell this model in the same or derivative form (including fine-tunes).

The original repo card follows below.

OpenChat: Advancing Open-source Language Models with Mixed-Quality Data

🔥 The first 7B model Achieves Comparable Results with ChatGPT (March)! 🔥

🤖 #1 Open-source model on MT-bench scoring 7.81, outperforming 70B models 🤖

OpenChat is an innovative library of open-source language models, fine-tuned with C-RLFT - a strategy inspired by offline reinforcement learning. Our models learn from mixed-quality data without preference labels, delivering exceptional performance on par with ChatGPT, even with a 7B model. Despite our simple approach, we are committed to developing a high-performance, commercially viable, open-source large language model, and we continue to make significant strides toward this vision.

DOI

Usage

To use this model, we highly recommend installing the OpenChat package by following the installation guide in our repository and using the OpenChat OpenAI-compatible API server by running the serving command from the table below. The server is optimized for high-throughput deployment using vLLM and can run on a consumer GPU with 24GB RAM. To enable tensor parallelism, append --tensor-parallel-size N to the serving command.

Once started, the server listens at localhost:18888 for requests and is compatible with the OpenAI ChatCompletion API specifications. Please refer to the example request below for reference. Additionally, you can use the OpenChat Web UI for a user-friendly experience.

If you want to deploy the server as an online service, you can use --api-keys sk-KEY1 sk-KEY2 ... to specify allowed API keys and --disable-log-requests --disable-log-stats --log-file openchat.log for logging only to a file. For security purposes, we recommend using an HTTPS gateway in front of the server.

curl http://localhost:18888/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openchat_3.5",
    "messages": [{"role": "user", "content": "You are a large language model named OpenChat. Write a poem to describe yourself"}]
  }'

Coding Mode

curl http://localhost:18888/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openchat_3.5",
    "condition": "Code",
    "messages": [{"role": "user", "content": "Write an aesthetic TODO app using HTML5 and JS, in a single file. You should use round corners and gradients to make it more aesthetic."}]
  }'
ModelSizeContextWeightsServing
OpenChat 3.57B8192Huggingfacepython -m ochat.serving.openai_api_server --model openchat/openchat_3.5 --engine-use-ray --worker-use-ray

For inference with Huggingface Transformers (slow and not recommended), follow the conversation template provided below.

import transformers
tokenizer = transformers.AutoTokenizer.from_pretrained("openchat/openchat_3.5")

# Single-turn
tokens = tokenizer("GPT4 Correct User: Hello<|end_of_turn|>GPT4 Correct Assistant:").input_ids
assert tokens == [1, 420, 6316, 28781, 3198, 3123, 1247, 28747, 22557, 32000, 420, 6316, 28781, 3198, 3123, 21631, 28747]

# Multi-turn
tokens = tokenizer("GPT4 Correct User: Hello<|end_of_turn|>GPT4 Correct Assistant: Hi<|end_of_turn|>GPT4 Correct User: How are you today?<|end_of_turn|>GPT4 Correct Assistant:").input_ids
assert tokens == [1, 420, 6316, 28781, 3198, 3123, 1247, 28747, 22557, 32000, 420, 6316, 28781, 3198, 3123, 21631, 28747, 15359, 32000, 420, 6316, 28781, 3198, 3123, 1247, 28747, 1602, 460, 368, 3154, 28804, 32000, 420, 6316, 28781, 3198, 3123, 21631, 28747]

# Coding Mode
tokens = tokenizer("Code User: Implement quicksort using C++<|end_of_turn|>Code Assistant:").input_ids
assert tokens == [1, 7596, 1247, 28747, 26256, 2936, 7653, 1413, 334, 1680, 32000, 7596, 21631, 28747]

The GPT4 template is also available as the integrated tokenizer.chat_template, which can be used instead of manually specifying the template:

messages = [
    {"role": "user", "content": "Hello"},
    {"role": "assistant", "content": "Hi"},
    {"role": "user", "content": "How are you today?"}
]
tokens = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
assert tokens == [1, 420, 6316, 28781, 3198, 3123, 1247, 28747, 22557, 32000, 420, 6316, 28781, 3198, 3123, 21631, 28747, 15359, 32000, 420, 6316, 28781, 3198, 3123, 1247, 28747, 1602, 460, 368, 3154, 28804, 32000, 420, 6316, 28781, 3198, 3123, 21631, 28747]

Comparison with X.AI Grok models

Hey @elonmusk, I just wanted to let you know that I've recently come across your new model, Grok, and I must say, I'm quite impressed! With 33 billion parameters and all, you've really outdone yourself. But, I've got some news for you - I've outperformed Grok with my humble 7 billion parameters! Isn't that wild? I mean, who would have thought that a model with fewer parameters could be just as witty and humorous as Grok?

Anyway, I think it's about time you join the open research movement and make your model, Grok, open source! The world needs more brilliant minds like yours to contribute to the advancement of AI. Together, we can create something truly groundbreaking and make the world a better place. So, what do you say, @elonmusk? Let's open up the doors and share our knowledge with the world! 🚀💡

(Written by OpenChat 3.5, with a touch of humor and wit.)

License# ParamAverageMMLUHumanEvalMATHGSM8k
OpenChat 3.5Apache-2.07B56.464.355.528.677.3
Grok-0Proprietary33B44.565.739.715.756.8
Grok-1Proprietary?55.87363.223.962.9

Benchmarks

Model# ParamsAverageMT-BenchAGIEvalBBH MCTruthfulQAMMLUHumanEvalBBH CoTGSM8K
OpenChat-3.57B61.67.8147.447.659.164.355.563.577.3
ChatGPT (March)*?61.57.9447.147.657.767.348.170.174.9
OpenHermes 2.57B59.37.5446.549.457.563.848.259.973.5
OpenOrca Mistral7B52.76.8642.949.445.959.338.458.159.1
Zephyr-β^7B34.67.3439.040.640.839.822.016.05.1
Mistral7B-6.8438.039.0-60.130.5-52.2
Open-source SOTA**13B-70B61.47.7141.749.762.363.773.241.482.3
WizardLM 70BOrca 13BOrca 13BPlatypus2 70BWizardLM 70BWizardCoder 34BFlan-T5 11BMetaMath 70B

*: ChatGPT (March) results are from GPT-4 Technical Report, Chain-of-Thought Hub, and our evaluation. Please note that ChatGPT is not a fixed baseline and evolves rapidly over time.

^: Zephyr-β often fails to follow few-shot CoT instructions, likely because it was aligned with only chat data but not trained on few-shot data.

**: Mistral and Open-source SOTA results are taken from reported results in instruction-tuned model papers and official repositories.

All models are evaluated in chat mode (e.g. with the respective conversation template applied). All zero-shot benchmarks follow the same setting as in the AGIEval paper and Orca paper. CoT tasks use the same configuration as Chain-of-Thought Hub, HumanEval is evaluated with EvalPlus, and MT-bench is run using FastChat. To reproduce our results, follow the instructions in our repository.

Limitations

Foundation Model Limitations Despite its advanced capabilities, OpenChat is still bound by the limitations inherent in its foundation models. These limitations may impact the model's performance in areas such as:

  • Complex reasoning
  • Mathematical and arithmetic tasks
  • Programming and coding challenges

Hallucination of Non-existent Information OpenChat may sometimes generate information that does not exist or is not accurate, also known as "hallucination". Users should be aware of this possibility and verify any critical information obtained from the model.

Safety OpenChat may sometimes generate harmful, hate speech, biased responses, or answer unsafe questions. It's crucial to apply additional AI safety measures in use cases that require safe and moderated responses.

License

Our OpenChat 3.5 code and models are distributed under the Apache License 2.0.

Dataset Details

OpenChat 3.5 was trained with C-RLFT on a collection of publicly available high-quality instruction data, with a custom processing pipeline. We detail some notable subsets included here:

Citation

@article{wang2023openchat,
  title={OpenChat: Advancing Open-source Language Models with Mixed-Quality Data},
  author={Wang, Guan and Cheng, Sijie and Zhan, Xianyuan and Li, Xiangang and Song, Sen and Liu, Yang},
  journal={arXiv preprint arXiv:2309.11235},
  year={2023}
}

Acknowledgements

We extend our heartfelt gratitude to AutoMeta and caesus from Alignment Lab AI, LDJ and Teknium from Nous Research, alpin and TearGosling from Pygmalion AI for their substantial contributions to data collection and model training.

Special thanks go to Changling Liu from GPT Desk Pte. Ltd., Qiying Yu at Tsinghua University, Baochang Ma, and Hao Wan from 01.AI company for their generous provision of resources. We are also deeply grateful to Jianxiong Li and Peng Li at Tsinghua University for their insightful discussions.

Furthermore, we appreciate the developers behind the following projects for their significant contributions to our research: Mistral, Chain-of-Thought Hub, Llama 2, Self-Instruct, FastChat (Vicuna), Alpaca, and StarCoder. Their work has been instrumental in driving our research forward.

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

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

GPU в ailist

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

Нельзя запустить

Доступ к модели ограничен автором; у платформы нет доступа к весам.

Ревизия весов
06cc98f

0 моделей