?️ LLM이 모든 지원서의 언어를 사용하도록 하세요. ?️
.txt 팀이 ❤?️로 제작했습니다.
유튜브 채널 | .txt 블로그 | 지저귀다
pip install outlines
여기 처음이세요? 설정 가이드로 이동
outlinesdev/outlines
를 제공하세요!개요에는 매주 새로운 릴리스와 기능이 출시됩니다. 별표를 표시하고 ? 이 저장소를 시청하고 @dottxtai를 팔로우하여 최신 소식을 받아보세요!
우리는 구조화된 세대의 경계를 계속 확장하기 위해 회사를 시작했습니다. .txt에 대해 자세히 알아보고 호스팅 솔루션이 필요한 경우 .json API를 사용해 보세요.
대규모 언어 모델을 포함하는 시스템의 안정성을 향한 첫 번째 단계는 출력과 사용자 정의 코드 사이에 잘 정의된 인터페이스가 있는지 확인하는 것입니다. 아웃라인은 언어 모델 생성을 제어하여 출력을 보다 예측 가능하게 만드는 방법을 제공합니다.
여러 가능성 중에서 선택하여 완료를 줄일 수 있습니다.
import outlines
model = outlines . models . transformers ( "microsoft/Phi-3-mini-4k-instruct" )
prompt = """You are a sentiment-labelling assistant.
Is the following review positive or negative?
Review: This restaurant is just awesome!
"""
generator = outlines . generate . choice ( model , [ "Positive" , "Negative" ])
answer = generator ( prompt )
정수 또는 부동 소수점만 반환하도록 모델에 지시할 수 있습니다.
import outlines
model = outlines . models . transformers ( "WizardLM/WizardMath-7B-V1.1" )
prompt = "<s>result of 9 + 9 = 18</s><s>result of 1 + 2 = "
answer = outlines . generate . format ( model , int )( prompt )
print ( answer )
# 3
prompt = "sqrt(2)="
generator = outlines . generate . format ( model , float )
answer = generator ( prompt , max_tokens = 10 )
print ( answer )
# 1.41421356
개요에는 빠른 정규식 구조 생성도 함께 제공됩니다. 실제로 choice
및 format
기능은 무엇보다도 내부적으로 정규식 구조 생성을 사용합니다.
import outlines
model = outlines . models . transformers ( "microsoft/Phi-3-mini-4k-instruct" )
prompt = "What is the IP address of the Google DNS servers? "
generator = outlines . generate . text ( model )
unstructured = generator ( prompt , max_tokens = 30 )
generator = outlines . generate . regex (
model ,
r"((25[0-5]|2[0-4]d|[01]?dd?).){3}(25[0-5]|2[0-4]d|[01]?dd?)" ,
)
structured = generator ( prompt , max_tokens = 30 )
print ( unstructured )
# What is the IP address of the Google DNS servers?
#
# Passive DNS servers are at DNS servers that are private.
# In other words, both IP servers are private. The database
# does not contain Chelsea Manning
print ( structured )
# What is the IP address of the Google DNS servers?
# 2.2.6.1
다른 라이브러리와 달리 아웃라인의 정규식 구조 생성은 비구조적 생성만큼 빠릅니다.
아웃라인을 사용하면 생성 프로세스를 안내하여 출력이 JSON 스키마 또는 Pydantic 모델을 따르도록 보장할 수 있습니다.
from enum import Enum
from pydantic import BaseModel , constr
import outlines
import torch
class Weapon ( str , Enum ):
sword = "sword"
axe = "axe"
mace = "mace"
spear = "spear"
bow = "bow"
crossbow = "crossbow"
class Armor ( str , Enum ):
leather = "leather"
chainmail = "chainmail"
plate = "plate"
class Character ( BaseModel ):
name : constr ( max_length = 10 )
age : int
armor : Armor
weapon : Weapon
strength : int
model = outlines . models . transformers ( "microsoft/Phi-3-mini-4k-instruct" )
# Construct structured sequence generator
generator = outlines . generate . json ( model , Character )
# Draw a sample
seed = 789001
character = generator ( "Give me a character description" , seed = seed )
print ( repr ( character ))
# Character(name='Anderson', age=28, armor=<Armor.chainmail: 'chainmail'>, weapon=<Weapon.sword: 'sword'>, strength=8)
character = generator ( "Give me an interesting character description" )
print ( repr ( character ))
# Character(name='Vivian Thr', age=44, armor=<Armor.plate: 'plate'>, weapon=<Weapon.crossbow: 'crossbow'>, strength=125)
이 방법은 통합 유형, 선택적 유형, 배열, 중첩 스키마 등과 함께 작동합니다. 일부 필드 제약 조건은 아직 지원되지 않지만 다른 모든 것은 작동합니다.
때로는 Pydantic 모델 대신 JSON 스키마를 전달하고 싶을 때도 있습니다. 우리는 당신을 보호해 드립니다:
import outlines
schema = '''{
"title": "Character",
"type": "object",
"properties": {
"name": {
"title": "Name",
"maxLength": 10,
"type": "string"
},
"age": {
"title": "Age",
"type": "integer"
},
"armor": {"$ref": "#/definitions/Armor"},
"weapon": {"$ref": "#/definitions/Weapon"},
"strength": {
"title": "Strength",
"type": "integer"
}
},
"required": ["name", "age", "armor", "weapon", "strength"],
"definitions": {
"Armor": {
"title": "Armor",
"description": "An enumeration.",
"enum": ["leather", "chainmail", "plate"],
"type": "string"
},
"Weapon": {
"title": "Weapon",
"description": "An enumeration.",
"enum": ["sword", "axe", "mace", "spear", "bow", "crossbow"],
"type": "string"
}
}
}'''
model = outlines . models . transformers ( "microsoft/Phi-3-mini-4k-instruct" )
generator = outlines . generate . json ( model , schema )
character = generator ( "Give me a character description" )
공식 문법이 세상을 지배하고, 아웃라인은 공식 문법이 LLM도 지배하게 만듭니다. EBNF 형식으로 컨텍스트 없는 문법을 전달할 수 있으며 아웃라인은 이 문법에 유효한 출력을 생성합니다.
import outlines
arithmetic_grammar = """
?start: expression
?expression: term (("+" | "-") term)*
?term: factor (("*" | "/") factor)*
?factor: NUMBER
| "-" factor
| "(" expression ")"
%import common.NUMBER
"""
model = outlines . models . transformers ( "WizardLM/WizardMath-7B-V1.1" )
generator = outlines . generate . cfg ( model , arithmetic_grammar )
sequence = generator ( "Alice had 4 apples and Bob ate 2. Write an expression for Alice's apples:" )
print ( sequence )
# (8-2)
이것은 매우 간단한 문법이었고, outlines.generate.cfg
사용하여 구문적으로 유효한 Python, SQL 등을 생성할 수 있습니다. 실제로 모든 종류의 구조화된 텍스트입니다. 당신이 해야 할 일은 웹에서 "X EBNF 문법"을 검색하고 개요 grammars
모듈을 살펴보는 것뿐입니다.
윤곽선은 함수의 시그니처에서 출력의 구조를 추론할 수 있습니다. 결과는 사전이며 일반적인 사전 확장 구문 **
을 사용하여 함수에 직접 전달할 수 있습니다.
import outlines
def add ( a : int , b : int ):
return a + b
model = outlines . models . transformers ( "WizardLM/WizardMath-7B-V1.1" )
generator = outlines . generate . json ( model , add )
result = generator ( "Return json with two integers named a and b respectively. a is odd and b even." )
print ( add ( ** result ))
# 3
구조를 지정하기 위해 함수를 직접 전달하는 것의 가장 큰 장점은 LLM의 구조가 함수 정의에 따라 변경된다는 것입니다. 여러 곳에서 코드를 변경할 필요가 없습니다!
매개변수를 생성하기 위해 열거형에 다양한 함수를 포함할 수도 있습니다.
from enum import Enum
from functools import partial
import outlines
def add ( a : int , b : int ) -> int :
return a + b
def mul ( c : float , d : float ) -> float :
return c * d
class Operation ( Enum ):
add = partial ( add )
mul = partial ( mul )
model = outlines . models . transformers ( "WizardLM/WizardMath-7B-V1.1" )
generator = outlines . generate . json ( model , add )
result = generator ( "Return json with two float named c and d respectively. c is negative and d greater than 1.0." )
print ( result )
# {'c': -3.14, 'd': 1.5}
프롬프트 작성이 지저분해질 수 있습니다. 아웃라인을 사용 하면 "템플릿 기능" 내에 템플릿을 캡슐화하여 프롬프트를 더 쉽게 작성하고 관리할 수 있습니다.
이러한 기능을 사용하면 프롬프트 로직을 일반 프로그램 로직과 깔끔하게 분리할 수 있습니다. 다른 모듈과 라이브러리에서 가져올 수 있습니다.
템플릿 기능은 불필요한 추상화가 필요하지 않으며 Jinja2 템플릿 엔진을 사용하여 간결한 방식으로 복잡한 프롬프트를 작성하는 데 도움을 줍니다.
import outlines
examples = [
( "The food was disgusting" , "Negative" ),
( "We had a fantastic night" , "Positive" ),
( "Recommended" , "Positive" ),
( "The waiter was rude" , "Negative" )
]
@ outlines . prompt
def labelling ( to_label , examples ):
"""You are a sentiment-labelling assistant.
{% for example in examples %}
{{ example[0] }} // {{ example[1] }}
{% endfor %}
{{ to_label }} //
"""
model = outlines . models . transformers ( "microsoft/Phi-3-mini-4k-instruct" )
prompt = labelling ( "Just awesome" , examples )
answer = outlines . generate . text ( model )( prompt , max_tokens = 100 )
@article{willard2023efficient,
title={Efficient Guided Generation for LLMs},
author={Willard, Brandon T and Louf, R{'e}mi},
journal={arXiv preprint arXiv:2307.09702},
year={2023}
}