채팅과 도구 사용
채팅과 도구 사용
Guidance는 채팅 형식의 상호작용을 파이썬 컨텍스트 매니저로 자연스럽게 표현해요. system(), user(), assistant() 블록 안에서 텍스트와 gen()·select()를 +=로 이어 나가면, 역할별 메시지가 문법에 맞춰 자동으로 조립돼요. 역할 구분이 명확해 코드가 읽기 쉽고 유지 보수하기 좋아요.
대화 만들기
Model 객체는 **불변(immutable)**이라, 새 대화를 시작하려면 원본 모델에서 복사본을 만들어 쓰는 게 기본 패턴이에요.
from guidance import system, user, assistant, gen
from guidance.models import Transformers
lm = Transformers("microsoft/Phi-4-mini-instruct")
with system():
lm += "You are a JSON generation expert."
with user():
lm += "Generate a person object with name and age."
with assistant():
lm += gen("response", max_tokens=100)
print(lm["response"])
gen("response", ...)처럼 이름을 붙이면, 생성된 값을 lm["response"]로 꺼내 쓸 수 있어요. 이건 이후 로직(파싱, 검증, 다른 도구로 전달)에 바로 연결하기 좋아요.
출처: https://github.com/guidance-ai/guidance/blob/main/docs/tutorials.rst
선택으로 고정 응답
select()는 주어진 목록 중 하나만 고르도록 강제해요. 객체 지향 라벨링이나 객관식, 또는 고정된 상태 전이에 유용해요.
from guidance import system, user, assistant, select
with system():
lm += "You are a helpful assistant."
with user():
lm += "Rate the sentiment: 'I love this movie'."
with assistant():
lm += select(["positive", "negative", "neutral"], name="label")
print(lm["label"]) # positive / negative / neutral 중 하나
도구 호출과 제어 흐름
Guidance의 목표 중 하나는 제어(control)와 생성을 자연스럽게 뒤섞는 것이에요. 파이썬 조건문·반복문·도구 호출을 생성 중간중간에 배치할 수 있어요. 이를테면 모델이 어떤 도구를 골랐는지에 따라 다음 단계를 다르게 진행하는 멀티스텝 워크플로를 만들 수 있어요.
from guidance import gen
lm = model + "Which tool should I use? " + gen(name="tool_choice", regex=r"search|calculate|summarize")
if lm["tool_choice"] == "search":
lm += " Searching..." + gen(max_tokens=20)
elif lm["tool_choice"] == "calculate":
lm += " Calculating..." + gen(max_tokens=20)
이런 방식으로 "프롬프트하고 기도하기" 대신, 출력이 항상 우리가 선언한 흐름을 따르도록 만들 수 있어요.
백엔드별 지원 차이
채팅 컨텍스트 매니저와 select()는 어떤 백엔드에서도 동작하지만, 정규식·문법을 gen()에 거는 강한 제약과 토큰 힐링은 로컬 백엔드(Transformers, llama.cpp)에서 완전히 지원돼요. 원격 API 백엔드는 로짓/토큰 경계 정보를 못 받아 기능 일부가 제한될 수 있으니, 구조가 핵심이라면 로컬 백엔드를 고려하는 게 좋아요.
더 알아보기
- 시작하기: Getting Started
- 제약 생성: Constrained Generation
- 프롬프트 설계: Art of Prompt Design