with system(): lm += "You are a helpful assistant" with user(): lm += "Hello. What is your name?" with assistant(): lm += gen(name="lm_response", max_tokens=20)
print(f"{lm['lm_response']=}")
gen() 是 Guidance 的核心生成函数,通过 name 参数将生成的文本绑定到变量上,后续可通过 lm['variable_name'] 访问。
lm = phi_lm with system(): lm += "You are a teenager" with user(): lm += "How old are you?" with assistant(): lm += gen("lm_age", regex=r"\d+", temperature=0.8)
print(f"The language model is {lm['lm_age']} years old")
import json from pydantic import BaseModel, Field from guidance import json as gen_json
classBloodPressure(BaseModel): systolic: int = Field(gt=300, le=400) diastolic: int = Field(gt=0, le=20) location: str = Field(max_length=50) model_config = dict(extra="forbid")
lm = phi_lm with system(): lm += "You are a doctor taking a patient's blood pressure taken from their arm" with user(): lm += "Report the blood pressure" with assistant(): lm += gen_json(name="bp", schema=BloodPressure)
result = BloodPressure.model_validate_json(lm["bp"]) print(result.model_dump_json(indent=8))
lm = phi_lm with system(): lm += "You are a geography expert" with user(): lm += """What is the capital of Sweden? Answer with the correct letter. A) Helsinki B) Reykjavik C) Stockholm D) Oslo """ with assistant(): lm += select(["A", "B", "C", "D"], name="model_selection")
print(f"The model selected {lm['model_selection']}")
with system(): lm += "You are a helpful assistant" with user(): lm += "List three colors, one per line:" with assistant(): lm += gen(name="colors", max_tokens=50)
import json from pydantic import BaseModel, Field from guidance import system, user, assistant from guidance import json as gen_json from guidance.models import Transformers
from guidance import system, user, assistant, gen, select from guidance import guidance from guidance.models import Model
@guidance defconstrained_math_solver(lm: Model, problem: str): """多步数学推理:先分析、再计算、最后选择答案""" with user(): lm += f"Problem: {problem}\n" lm += "Step 1 - Identify the operation needed: " with assistant(): lm += gen(name="step1_analysis", max_tokens=60)
with user(): lm += "Step 2 - Show your calculation: " with assistant(): lm += gen(name="step2_calculation", max_tokens=100)
with user(): lm += "Step 3 - Select the final answer: " with assistant(): lm += select( ["A) 9", "B) 12", "C) 24", "D) 36"], name="final_answer" ) return lm
lm = Transformers("microsoft/Phi-4-mini-instruct") with system(): lm += "You are a careful math tutor. Think step by step."
result = constrained_math_solver( lm, "If a train travels at 60 mph for 2.5 hours, how far does it go?" ) print(f"Analysis: {result['step1_analysis']}") print(f"Calculation: {result['step2_calculation']}") print(f"Final answer: {result['final_answer']}")
sentiments = [] reviews = [ "This product is amazing, exceeded all my expectations!", "Terrible quality, broke after two days of use.", "It's okay, does the job but nothing special.", "The customer service was outstanding and resolved my issue quickly.", "Waste of money, do not buy this.", ]
for review in reviews: lm_session = lm with system(): lm_session += "You are a sentiment classifier." with user(): lm_session += ( f"Classify this review as POSITIVE, NEGATIVE, or NEUTRAL.\n" f"Review: {review}\n" f"Output ONLY one word: " ) with assistant(): lm_session += gen( name="sentiment", regex=r"POSITIVE|NEGATIVE|NEUTRAL", max_tokens=10 ) sentiments.append(lm_session["sentiment"])
for review, sentiment inzip(reviews, sentiments): print(f"[{sentiment}] {review}")