OpenSource-Hub

outlines

라이브러리

dottxt-ai/outlines

대규모 언어 모델이 구조화된 결과를 출력하도록 보장합니다.

개요

Outlines는 대규모 언어 모델이 지정된 구조(예: JSON, 정규식 또는 Pydantic 모델)에 부합하는 출력을 생성하도록 보장하는 Python 라이브러리입니다. 다양한 모델 백엔드를 지원하며 기존 워크플로와 원활하게 통합됩니다.

README 미리보기

\n\n\n\n\n\n 🗒️ *Structured outputs for LLMs* 🗒️\n\nMade with ❤👷️ by the team at [.txt](https://dottxt.co)\nTrusted by NVIDIA, Cohere, HuggingFace, vLLM, etc.\n\n\n[![PyPI Version][pypi-version-badge]][pypi]\n[![Downloads][downloads-badge]][pypistats]\n[![Stars][stars-badge]][stars]\n\n\n[![Discord][discord-badge]][discord]\n[![Blog][dottxt-blog-badge]][dottxt-blog]\n[![Twitter][twitter-badge]][twitter]\n\nThe .txt API is currently in early access. **[Request access here →](https://h1xbpbfsf0w.typeform.com/to/fwQNWmS8?utm_source=github&utm_medium=organic&utm_campaign=outlines)**\n\n\n\n\n## 🚀 Building the future of structured generation\n\nWe're working with select partners to develop new interfaces to structured generation.\n\nNeed XML, FHIR, custom schemas or grammars? Let's talk.\n\nAudit your schema: share one schema, we show you what breaks under generation, the constraints that fix it, and compliance rates before and after. Sign up [here](https://h1xbpbfsf0w.typeform.com/to/rtFUraA2?typeform).\n\n## Table of Contents\n\n- [Why Outlines?](#why-outlines)\n- [Quickstart](#quickstart)\n- [Real-World Examples](#real-world-examples)\n  - [🙋‍♂️ Customer Support Triage](#customer-support-triage)\n  - [📦 E-commerce Product Categorization](#e-commerce-product-categorization)\n  - [📊 Parse Event Details with Incomplete Data](#parse-event-details-with-incomplete-data)\n  - [🗂️ Categorize Documents into Predefined Types](#categorize-documents-into-predefined-types)\n  - [📅 Schedule a Meeting with Function Calling](#schedule-a-meeting-with-function-calling)\n  - [📝 Dynamically Generate Prompts with Re-usable Templates](#dynamically-generate-prompts-with-re-usable-templates)\n- [They Use Outlines](#they-use-outlines)\n- [Model Integrations](#model-integrations)\n- [Core Features](#core-features)\n- [Other Features](#other-features)\n- [About .txt](#about-txt)\n- [Community](#community)\n\n\n\n## Why Outlines?\n\nLLMs are powerful but their outputs are unpredictable

FAQ (5)

문제 해결
Outlines에서 JsonSchema whitespace_pattern을 변경할 때 오래된 캐시 히트나 잘못된 정규식 출력이 발생하는 문제를 해결하는 방법은?

JsonSchema.__eq__는 파싱된 스키마 JSON만 비교하고 whitespace_pattern은 비교하지 않으므로, 패턴이 서로 다른 스키마가 동일한 것으로 처리되어 캐시/중복 제거 시 잘못된 logits processor가 재사용될 수 있습니다. 다음과 같이 패턴도 비교하도록 동등성 비교를 수정하세요:

def __eq__(self, other):
    if not isinstance(other, JsonSchema):
        return False
    try:
        self_dict = json.loads(self.schema)
        other_dict = json.loads(other.schema)
        return (
            self_dict == other_dict
            and self.whitespace_pattern == other.whitespace_pattern
        )
    except json.JSONDecodeError:
        return (
            self.schema == other.schema
            and self.whitespace_pattern == other.whitespace_pattern
        )

패치가 적용되기 전까지는 JsonSchema만을 기준으로 processor를 캐시하지 마세요. (schema.schema, schema.whitespace_pattern)과 같은 캐시 키를 사용하거나, 패턴이 변경될 때 해당 캐시를 지우세요.

원본 Issue #1981
문제 해결
MkDocs에서 Python 패키지를 src 레이아웃으로 마이그레이션한 후 API Reference가 비어 있는 이유는 무엇인가요?

mkdocs-gen-files가 새 패키지 위치를 스캔하도록 scripts/gen_ref_pages.py를 업데이트하세요. 기존 경로 root / "outlines"를 root / "src" / "outlines"로 바꾸세요. 변경 후 MkDocs로 문서를 다시 빌드하고 site/api_reference/models/index.html과 같은 페이지가 생성되는지 확인하세요. 이 문제는 src-layout 마이그레이션으로 패키지가 outlines/에서 src/outlines/로 이동하면서 기존 glob이 비게 되어 발생합니다.

원본 Issue #1912
문제 해결
Outlines의 json_schema_dict_to_dataclass가 선택적 필드에 대해 `age: int = None`을 생성하는 이유는 무엇이며, 어떻게 해결할 수 있나요?

src/outlines/types/json_schema_utils.py에서 json_schema_dict_to_dataclass는 필수가 아닌 필드의 기본값으로 None을 할당하지만, 해당 타입을 Optional로 감싸지 않습니다. 필수가 아닌 속성이 Optional[typ]를 사용하도록 컨버터를 업데이트하세요:

from typing import Optional

for property, details in properties.items():
    typ = schema_type_to_python(details, "dataclass")

    if property not in required:
        typ = Optional[typ]
        defaults[property] = None

    annotations[property] = typ

이렇게 하면 선택적 JSON Schema 정수가 age: Optional[int] = None을 생성하게 되어 Pydantic 컨버터와 일치하고, 구조화된 생성에서 null을 허용합니다. 임시 해결 방법으로, 수정이 적용될 때까지 필수가 아닌 dataclass 필드를 Optional[T] = None으로 수동 선언하거나 convert_to(schema, "pydantic")을 사용하세요.

원본 Issue #1938
문제 해결
Outlines `Literal[1.5]`가 `"1x5"`와 같은 문자열을 잘못 매칭하는 문제를 해결하는 방법은?

숫자 값은 이스케이프 없이 정규식으로 변환되므로, 1.5의 .가 정규식 와일드카드로 작동합니다. src/outlines/types/dsl.py에서 숫자 term 생성을 Regex(str(value))에서 Regex(re.escape(str(value)))로 변경하고, re가 임포트되어 있는지 확인하세요:

import re

# Inside python_types_to_terms handling for int/float:
term = Regex(re.escape(str(value)))

이렇게 하면 1\.5가 생성되므로 Literal[1.5]는 "1.5"만 매칭하고 "1x5"는 거부합니다. 수정 사항이 릴리스될 때까지 float 리터럴 제약 대신 Regex(r"1\.5")와 같이 명시적으로 이스케이프된 정규식을 사용하세요.

원본 Issue #1901
문제 해결
outlines.types.ipv6가 선행 0이 포함된 유효하지 않은 IPv4-mapped IPv6 주소를 허용하는 문제를 어떻게 수정하나요?

ipv6 정규식은 기존 IPv4 옥텟 패턴을 재사용하므로, ::ffff:01.1.1.1 또는 ::ffff:00.0.0.0과 같은 접미사가 잘못 매칭됩니다.

ipv6 정의에서 기존 옥텟 패턴이 나타나는 두 위치를 모두 교체하여 src/outlines/types/__init__.py에서 이 문제를 수정하세요:

기존 패턴:
25[0-5]|2[0-4][0-9]|1?[0-9]{1,2}

새 패턴:
25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]

다음 두 IPv4-mapped 분기 모두에서 업데이트해야 합니다:
- ::ffff:a.b.c.d
- x:x:x:x::a.b.c.d

새 패턴은 0, 1, 42, 192와 같은 표준 옥텟은 허용하지만, 00, 01, 007과 같이 앞에 0이 붙는 형태는 거부합니다.

패치를 적용하기 전 임시 해결 방법으로, Python 표준 라이브러리를 사용하여 생성된 주소를 검증하세요:

import ipaddress

def is_valid_ip(value: str) -> bool:
    try:
        ipaddress.ip_address(value)
        return True
    except ValueError:
        return False

정규식 수정을 적용한 후에는 ::ffff:192.168.1.1과 1:2:3:4::5.6.7.8이 여전히 매칭되지만, ::ffff:01.1.1.1, ::ffff:00.0.0.0, 1:2:3:4::5.6.007.8은 거부됩니다.

원본 Issue #1911