Дополнительные возможности

Поддержка function calls (УСТАРЕЛО)


С 20 августа 2024 функциональность function calls, как устаревшая версия tool calls, больше не работает. Пожалуйста, используйте tool calls для реализации.

У нас добавлена поддержка function calling вызовов OpenAI – в том числе для части опенсорс моделей!
https://openai.com/blog/function-calling-and-other-api-updates
https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models

Такой вызов просит OpenAI модель вывести json, соответствующий одной из предложенных функций. Например, можно подать на вход функцию “get_current_weather” – и выходом модели будет json “get_current_weather” с параметрами, соответствующими текущему пользовательскому текстовому запросу (см. примеры по ссылке)

Поддерживаются модели:
  • OpenAI openai/gpt-3.5-turbo, gpt4, и, возможно другие (ответ будет в элементе function_call)
  • jondurbin/airoboros-l2–70b (ответ будет в элементе content)

Также на практике и множество других моделей поддерживают function calls (Claude и пр.), но их поддержка не задекларирована, так что используйте на свой страх и риск. У автора работали anthropic/claude-instant-v1, openchat/openchat-7b, gryphe/mythomax-L2–13b и пр.

Пример вызова:
#
    prompt = "What is the weather like in Boston?"

    messages = []
    #messages.append({"role": "system", "content": system_text})
    messages.append({"role": "user", "content": prompt})

    response = openai.ChatCompletion.create(

        model="openai/gpt-3.5-turbo",
        # model="jondurbin/airoboros-l2-70b",
        messages =messages,
        temperature=0.9,
        n=1,
        max_tokens = 1500,
        stream=stream,
        functions=[
            {
                "name": "get_current_weather",
                "description": "Get the current weather in a given location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA"
                        },
                        "unit": {
                            "type": "string",
                            "enum": ["celsius", "fahrenheit"]
                        }
                    },
                    "required": ["location"]
                }
            }
        ]
    )



Поддержка tools (РЕКОМЕНДУЕТСЯ, поддерживаются и другие модели при записи tools в OpenAI-формате)


Аналогично предыдущему.

Tool calls поддерживается моделями, у которых есть бедж tools в списке моделей – их более 20, включая опенсорс модели. Вы можете зайти в список моделей по новизне, и отфильтровать модели по слову tools.
 
У не OpenAI-моделей могут быть незначительные несовестимости с форматом, но наши базовые тесты показывают совместимость.

Пример вызова:
#
    prompt = "What is the weather like in Boston?"

    messages = []
    #messages.append({"role": "system", "content": system_text})
    messages.append({"role": "user", "content": prompt})

    response = openai.ChatCompletion.create(

        model="openai/gpt-3.5-turbo",
        messages =messages,
        temperature=0.1,
        n=1,
        max_tokens = 1500,
        stream=False,
        tool_choice="auto",
        tools = [{
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "Get the current weather in a given location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA",
                        },
                        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                    },
                    "required": ["location"],
                },
            },
        }
        ]
    )



Поддержка structured outputs (РЕКОМЕНДУЕТСЯ, поддерживаются и другие модели при записи в OpenAI-формате)


Аналогично предыдущему.

Structured outputs поддерживается моделями, у которых есть бедж structured-outputs в списке моделей – включая опенсорс модели. Вы можете зайти в список моделей по новизне, и отфильтровать модели по слову structured-outputs. Обычно поддерживаются OpenAI модели, и последние модели Google (Gemini Flash 3, Gemini Pro 3)
 
У не OpenAI-моделей могут быть незначительные несовестимости с форматом, но наши базовые тесты показывают совместимость.

Для ознакомления рекомендуем ознакомиться со статьей: https://cookbook.openai.com/examples/structured_outputs_intro

Базовый пример
def test_structured_outputs(model:str) -> dict:
    math_tutor_prompt = '''
        You are a helpful math tutor. You will be provided with a math problem,
        and your goal will be to output a step by step solution, along with a final answer.
        For each step, just provide the output as an equation use the explanation field to detail the reasoning.
    '''

    prompt = "There are equation 'x+3=8'. Find the integer 'x'"

    messages = []

    messages.append({"role": "system", "content": math_tutor_prompt})
    messages.append({"role": "user", "content": prompt})

    response = openai.ChatCompletion.create(
        headers={
            "X-Title": "Test structured outputs"
        },
        model=model,
        messages=messages,
        temperature=0.1,
        n=1,
        max_tokens=500,
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "math_reasoning",
                "schema": {
                    "type": "object",
                    "properties": {
                        "steps": {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                    "explanation": {"type": "string"},
                                    "output": {"type": "string"}
                                },
                                "required": ["explanation", "output"],
                                "additionalProperties": False
                            }
                        },
                        "final_answer": {"type": "integer"}
                    },
                    "required": ["steps", "final_answer"],
                    "additionalProperties": False
                },
                "strict": True
            }
        }

    )
    print("Response:", response)
    response1 = response["choices"][0]["message"] # будет содержать content, в котором нужный JSON со структурой

    # response_text: str = str(response1).strip()
    return response1

Поддержка MCP (Model Context Protocol)


Наши нейросети c tools эффективно поддерживают Model Context Protocol.
См. описание здесь: https://vsegpt.ru/ExtTools/CherryStudio

Также мы поддерживаем доступ к части функциональности с помощью MCP Servers for VseGPT:
https://github.com/janvarev/mcp-vsepgt-server