text-generation-inference 文件

指南

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

指導

文字生成推理 (TGI) 現在支援JSON 和正則表示式語法以及工具和函式,以幫助開發人員引導 LLM 響應以滿足其需求。

這些功能從版本1.4.3開始可用。可以透過huggingface_hub庫訪問。工具支援與 OpenAI 的客戶端庫相容。以下指南將引導您瞭解這些新功能以及如何使用它們!

注意:指導在/generate端點中作為語法支援,在v1/chat/completions端點中作為工具支援。

工作原理

TGI 利用outlines庫有效地解析和編譯使用者指定的語法結構和工具。這種整合將定義的語法轉換為中間表示,作為引導和約束內容生成的框架,確保輸出符合指定的語法規則。

如果您對 outlines 在 TGI 中如何使用的技術細節感興趣,可以檢視概念性指導文件

目錄 📚

語法和約束

工具和函式

  • 工具引數:透過預定義函式增強 AI 的能力。
  • 透過客戶端:使用 TGI 的客戶端庫與訊息 API 和工具函式互動。
  • OpenAI 整合:使用 OpenAI 的客戶端庫與 TGI 的訊息 API 和工具函式互動。

語法和約束 🛣️

語法引數

在 TGI 1.4.3中,我們引入了語法引數,允許您指定從 LLM 獲得的響應格式。

使用 curl,您可以向 TGI 的訊息 API 傳送帶有語法引數的請求。這是與 API 互動最原始的方式,建議使用Pydantic以提高易用性和可讀性。

curl localhost:3000/generate \
    -X POST \
    -H 'Content-Type: application/json' \
    -d '{
    "inputs": "I saw a puppy a cat and a raccoon during my bike ride in the park",
    "parameters": {
        "repetition_penalty": 1.3,
        "grammar": {
            "type": "json",
            "value": {
                "properties": {
                    "location": {
                        "type": "string"
                    },
                    "activity": {
                        "type": "string"
                    },
                    "animals_seen": {
                        "type": "integer",
                        "minimum": 1,
                        "maximum": 5
                    },
                    "animals": {
                        "type": "array",
                        "items": {
                            "type": "string"
                        }
                    }
                },
                "required": ["location", "activity", "animals_seen", "animals"]
            }
        }
    }
}'
// {"generated_text":"{ \n\n\"activity\": \"biking\",\n\"animals\": [\"puppy\",\"cat\",\"raccoon\"],\n\"animals_seen\": 3,\n\"location\": \"park\"\n}"}

Hugging Face Hub Python 庫

Hugging Face Hub Python 庫提供了一個客戶端,可以輕鬆與訊息 API 互動。以下是使用客戶端傳送帶有語法引數的請求的示例。

from huggingface_hub import InferenceClient

client = InferenceClient("https://:3000")

schema = {
    "properties": {
        "location": {"title": "Location", "type": "string"},
        "activity": {"title": "Activity", "type": "string"},
        "animals_seen": {
            "maximum": 5,
            "minimum": 1,
            "title": "Animals Seen",
            "type": "integer",
        },
        "animals": {"items": {"type": "string"}, "title": "Animals", "type": "array"},
    },
    "required": ["location", "activity", "animals_seen", "animals"],
    "title": "Animals",
    "type": "object",
}

user_input = "I saw a puppy a cat and a raccoon during my bike ride in the park"
resp = client.text_generation(
    f"convert to JSON: 'f{user_input}'. please use the following schema: {schema}",
    max_new_tokens=100,
    seed=42,
    grammar={"type": "json", "value": schema},
)

print(resp)
# { "activity": "bike ride", "animals": ["puppy", "cat", "raccoon"], "animals_seen": 3, "location": "park" }

語法可以使用 Pydantic 模型、JSON 模式或正則表示式定義。LLM 將生成符合指定語法的響應。

注意:語法必須編譯成中間表示才能約束輸出。語法編譯計算量大,首次請求可能需要幾秒鐘才能完成。後續請求將使用快取的語法,速度會快得多。

用 Pydantic 約束

使用 Pydantic 模型,我們可以用更短、更可讀的方式定義與上一個示例類似的語法。

from huggingface_hub import InferenceClient
from pydantic import BaseModel, conint
from typing import List


class Animals(BaseModel):
    location: str
    activity: str
    animals_seen: conint(ge=1, le=5)  # Constrained integer type
    animals: List[str]


client = InferenceClient("https://:3000")

user_input = "I saw a puppy a cat and a raccoon during my bike ride in the park"
resp = client.text_generation(
    f"convert to JSON: 'f{user_input}'. please use the following schema: {Animals.schema()}",
    max_new_tokens=100,
    seed=42,
    grammar={"type": "json", "value": Animals.schema()},
)

print(resp)
# { "activity": "bike ride", "animals": ["puppy", "cat", "raccoon"], "animals_seen": 3, "location": "park" }

將語法定義為正則表示式

from huggingface_hub import InferenceClient

client = InferenceClient("https://:3000")

section_regex = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
regexp = f"HELLO\.{section_regex}\.WORLD\.{section_regex}"

# This is a more realistic example of an ip address regex
# regexp = f"{section_regex}\.{section_regex}\.{section_regex}\.{section_regex}"


resp = client.text_generation(
    f"Whats Googles DNS? Please use the following regex: {regexp}",
    seed=42,
    grammar={
        "type": "regex",
        "value": regexp,
    },
)


print(resp)
# HELLO.255.WORLD.255

工具和函式 🛠️

工具引數

除了語法引數,我們還引入了一套工具和函式,以幫助您充分利用訊息 API。

工具是一組使用者定義的函式,可以與聊天功能協同使用,以增強 LLM 的功能。函式與語法類似,定義為 JSON 模式,並可以作為引數的一部分傳遞給訊息 API。

curl localhost:3000/v1/chat/completions \
    -X POST \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "tgi",
    "messages": [
        {
            "role": "user",
            "content": "What is the weather like in New York?"
        }
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "Get the current weather",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA"
                        },
                        "format": {
                            "type": "string",
                            "enum": ["celsius", "fahrenheit"],
                            "description": "The temperature unit to use. Infer this from the users location."
                        }
                    },
                    "required": ["location", "format"]
                }
            }
        }
    ],
    "tool_choice": "get_current_weather"
}'
// {"id":"","object":"text_completion","created":1709051640,"model":"HuggingFaceH4/zephyr-7b-beta","system_fingerprint":"1.4.3-native","choices":[{"index":0,"message":{"role":"assistant","tool_calls":{"id":0,"type":"function","function":{"description":null,"name":"tools","parameters":{"format":"celsius","location":"New York"}}}},"logprobs":null,"finish_reason":"eos_token"}],"usage":{"prompt_tokens":157,"completion_tokens":19,"total_tokens":176}}

帶工具的聊天補全

語法在/generate端點中受支援,而工具在/chat/completions端點中受支援。以下是使用客戶端傳送帶工具引數的請求的示例。

from huggingface_hub import InferenceClient

client = InferenceClient("https://:3000")

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "format": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "The temperature unit to use. Infer this from the users location.",
                    },
                },
                "required": ["location", "format"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_n_day_weather_forecast",
            "description": "Get an N-day weather forecast",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "format": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "The temperature unit to use. Infer this from the users location.",
                    },
                    "num_days": {
                        "type": "integer",
                        "description": "The number of days to forecast",
                    },
                },
                "required": ["location", "format", "num_days"],
            },
        },
    },
]

chat = client.chat_completion(
    messages=[
        {
            "role": "system",
            "content": "You're a helpful assistant! Answer the users question best you can.",
        },
        {
            "role": "user",
            "content": "What is the weather like in Brooklyn, New York?",
        },
    ],
    tools=tools,
    seed=42,
    max_tokens=100,
)

print(chat.choices[0].message.tool_calls)
# [ChatCompletionOutputToolCall(function=ChatCompletionOutputFunctionDefinition(arguments={'format': 'fahrenheit', 'location': 'Brooklyn, New York', 'num_days': 7}, name='get_n_day_weather_forecast', description=None), id=0, type='function')]

OpenAI 整合

TGI 暴露了一個與 OpenAI 相容的 API,這意味著您可以使用 OpenAI 的客戶端庫與 TGI 的訊息 API 和工具功能進行互動。

from openai import OpenAI

# Initialize the client, pointing it to one of the available models
client = OpenAI(
    base_url="https://:3000/v1",
    api_key="_",
)

# NOTE: tools defined above and removed for brevity

chat_completion = client.chat.completions.create(
    model="tgi",
    messages=[
        {
            "role": "system",
            "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
        },
        {
            "role": "user",
            "content": "What's the weather like the next 3 days in San Francisco, CA?",
        },
    ],
    tools=tools,
    tool_choice="auto",  # tool selected by model
    max_tokens=500,
)


called = chat_completion.choices[0].message.tool_calls
print(called)
# {
#     "id": 0,
#     "type": "function",
#     "function": {
#         "description": None,
#         "name": "tools",
#         "parameters": {
#             "format": "celsius",
#             "location": "San Francisco, CA",
#             "num_days": 3,
#         },
#     },
# }

工具選擇配置

在配置模型如何在聊天補全期間與工具互動時,有幾個選項可以決定是否或如何呼叫工具。這些選項由tool_choice引數控制,該引數指定模型與工具使用相關的行為。支援以下模式

  1. 自動:

    • 模型根據使用者輸入決定是呼叫工具還是生成響應訊息。
    • 如果提供了工具,這是預設模式。
    • 用法示例
      tool_choice="auto"
  2. :

    • 模型絕不會呼叫任何工具,只生成響應訊息。
    • 如果未提供工具,這是預設模式。
    • 用法示例
      tool_choice="none"
  3. 必需:

    • 模型必須呼叫一個或多個工具,並且不會自行生成響應訊息。
    • 用法示例
      tool_choice="required"
  4. 按函式名指定工具呼叫:

    • 您可以透過直接指定工具函式或使用物件定義來強制模型呼叫特定工具。
    • 兩種方法:
      1. 提供函式名作為字串
        tool_choice="get_current_weather"
      2. 使用函式物件格式
        tool_choice={
          "type": "function",
          "function": {
              "name": "get_current_weather"
          }
        }

這些選項在將工具與聊天補全端點整合時提供了靈活性。您可以配置模型,使其自動依賴工具,或根據任務需要強制其遵循預定義行為。


工具選擇選項 描述 使用時機
自動 模型決定是呼叫工具還是生成訊息。如果提供了工具,這是預設設定。 當您希望模型自行決定何時需要工具時使用。
模型生成訊息而不呼叫任何工具。如果未提供工具,這是預設設定。 當您不希望模型呼叫任何工具時使用。
必需 模型必須呼叫一個或多個工具,並且不會自行生成訊息。 當工具呼叫是強制性的,並且您不希望生成常規訊息時使用。
特定工具呼叫(name或物件) 透過指定其名稱(tool_choice="get_current_weather")或使用物件來強制模型呼叫特定工具。 當您希望將模型限制為只調用特定工具進行響應時使用。
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.