Text Generation Inference 文件

指南

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

指引 (Guidance)

文字生成推論 (TGI) 現已支援 JSON 和正則表達式語法 (grammars) 以及 工具與函式,協助開發者引導 LLM 的回應以符合其需求。

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

注意:guidance 作為語法支援於 /generate 端點,並作為工具支援於 v1/chat/completions 端點。

運作方式

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

如果您對 TGI 如何使用 outlines 的技術細節感興趣,可以查看 概念指南文件

目錄 📚

語法與約束

工具與函式

語法與約束 🛣️

語法參數

在 TGI 1.4.3 中,我們引入了 grammar 參數,讓您可以指定希望 LLM 輸出的回應格式。

使用 curl,您可以向 TGI 的 Messages API 發送帶有 grammar 參數的請求。這是與 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 函式庫提供了一個方便的客戶端,可輕鬆與 Messages API 互動。以下是一個如何使用該客戶端發送帶有 grammar 參數請求的範例。

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 schema 或正則表達式來定義。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.model_json_schema()}",
    max_new_tokens=100,
    seed=42,
    grammar={"type": "json", "value": Animals.model_json_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

工具與函式 🛠️

工具參數

除了 grammar 參數外,我們還引入了一組工具與函式,協助您充分利用 Messages API。

工具是一組使用者定義的函式,可與聊天功能並用,以增強 LLM 的能力。函式與語法類似,皆定義為 JSON schema,並可作為參數傳遞給 Messages 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 的 Messages 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. auto:

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

    • 模型永遠不會呼叫任何工具,僅會生成回應訊息。
    • 如果未提供工具,這是預設模式。
    • 使用範例
      tool_choice="none"
  3. required:

    • 模型必須呼叫一個或多個工具,且不會自行生成回應訊息。
    • 使用範例
      tool_choice="required"
  4. 依函式名稱指定特定工具呼叫:

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

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


工具選擇選項 說明 使用時機
auto 模型決定是否呼叫工具或生成訊息。若提供工具,此為預設值。 當您希望模型自行決定何時需要使用工具時使用。
none 模型僅生成訊息而不呼叫任何工具。若未提供工具,此為預設值。 當您不希望模型呼叫任何工具時使用。
required 模型必須呼叫一個或多個工具,且不自行生成訊息。 當工具呼叫為強制性,且您不希望產生常規訊息時使用。
特定工具呼叫 (name 或物件) 強制模型呼叫特定工具,透過指定其名稱 (tool_choice="get_current_weather") 或使用物件。 當您希望限制模型僅呼叫特定工具來進行回應時使用。
在 GitHub 上更新

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