ChatPromptTemplate.from_messages(...)가 받는 메시지 포맷(튜플/템플릿/메시지 객체), template_format(f-string/mustache/jinja2), MessagesPlaceholder 사용법은 문서와 일치합니다.
1) 기본형: 시스템+휴먼 (f-string)
from langchain_core.prompts import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
SYSTEM = (
"너는 AI 서비스를 개발하는 파이썬 시니어 엔지니어다. "
"답변은 한국어, 정확하고 간결하게. 추정은 '추정'이라고 표시해."
)
prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template(SYSTEM),
HumanMessagePromptTemplate.from_template("{input}"),
])
# 사용 예
# result = (prompt | llm).invoke({"input": "FastAPI로 서명 검증 웹훅 예제 코드 보여줘"})
- 포맷에 쓸 변수는 invoke({"input": ...})로 전달합니다. (필수/옵셔널 변수 자동 추론 가능) python.langchain.com
📝 사용한 프롬프트 텍스트
- system: SYSTEM 위 문자열 그대로
- human: "{input}"
2) 대화 히스토리 포함
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
SYSTEM = "너는 컨텍스트를 보수적으로 신뢰하는 AI 엔지니어다. 근거가 없으면 '불명확'이라 말해."
prompt = ChatPromptTemplate.from_messages([
("system", SYSTEM),
MessagesPlaceholder("history"), # 과거 대화를 이 위치에 삽입
("human", "{input}"),
])
# 호출 시 history는 메시지 리스트로 전달
# (prompt | llm).invoke({
# "history": [("human","어제 만든 FastAPI 훅 기억해?"), ("ai","네, HMAC 검증 추가했어요.")],
# "input": "거기에 재시도 로직 붙이는 법?"
# })
- MessagesPlaceholder("history")에 채팅 리스트를 그대로 넣습니다. 필요하면 n_messages=...로 잘라 쓸 수 있어요. python.langchain.com
📝 사용한 프롬프트 텍스트
- system: SYSTEM 위 문자열
- human: "{input}" (+ 중간에 history가 끼어듦)
3) Jinja2 템플릿으로 변수 가독성↑
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages(
[
("system", "{{role}}. 응답은 간결한 체크리스트로."),
("human", "요청: {{input}}\n제약: {{constraints | join(', ')}}"),
],
template_format="jinja2", # f-string/mustache/jinja2 중 선택
)
# (prompt | llm).invoke({
# "role": "너는 보안에 엄격한 파이썬 설계자다",
# "input": "OAuth2 리프레시 토큰 롤오버 전략",
# "constraints": ["회귀 호환", "제로 다운타임"]
# })
- template_format은 from_messages(...)에서도 직접 지정 가능합니다. python.langchain.com
📝 사용한 프롬프트 텍스트
- system: "{{role}}. 응답은 간결한 체크리스트로."
- human: "요청: {{input}}\n제약: {{constraints | join(', ')}}"
4) 부분 변수 고정(partial)로 운영 파라미터 잠그기
from langchain_core.prompts import (
ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
)
SYSTEM = (
"너는 {product} 팀의 리뷰어다. 코드 안전성/성능/가독성 순으로 평가하고, "
"근거를 3줄 이내 bullet로 요약하라."
)
prompt = ChatPromptTemplate([
SystemMessagePromptTemplate.from_template(
SYSTEM,
partial_variables={"product": "결제게이트웨이"} # 고정
),
HumanMessagePromptTemplate.from_template("리뷰 대상:\n{code}"),
])
# (prompt | llm).invoke({"code": "<코드...>"})
- SystemMessagePromptTemplate.from_template(...)에 partial_variables로 일부 변수만 고정해 둘 수 있습니다. python.langchain.com
📝 사용한 프롬프트 텍스트
- system: SYSTEM (단, {product}는 partial로 "결제게이트웨이")
- human: "리뷰 대상:\n{code}"
5) JSON 구조 추출(도구 없이)
from langchain_core.prompts import ChatPromptTemplate
SYSTEM = (
"너는 정보 추출기다. 반드시 JSON만 출력하라. 설명 금지.\n"
'스키마: {"service": str, "endpoints": [str], "auth": "none|basic|oauth2"}'
)
prompt = ChatPromptTemplate.from_messages([
("system", SYSTEM),
("human", "다음 API 문서에서 서비스명/엔드포인트/인증방식 추출:\n{text}"),
])
# (prompt | llm).invoke({"text": "<API 설명 본문...>"})
📝 사용한 프롬프트 텍스트
- system: SYSTEM 위 문자열
- human: "다음 API 문서에서 ...\n{text}"
참고/검증 포인트
- from_messages([...])는 템플릿/튜플/메시지 객체/문자열을 섞어 받을 수 있습니다. python.langchain.com
- template_format은 기본 f-string이며 mustache/jinja2도 지원합니다. python.langchain.com
- 대화 기록 삽입은 MessagesPlaceholder("history")를 사용합니다(필요 시 n_messages로 제한). python.langchain.com
with ChatGPT
'공부방 > Python & AI' 카테고리의 다른 글
| [AI] LangGraph의 tools_condition (0) | 2025.10.13 |
|---|---|
| [Python] Sequence (0) | 2025.10.12 |
| [AI] add_messages (0) | 2025.10.12 |
| [Python] Annotated (0) | 2025.10.12 |
| [AI] MessagesPlaceholder (0) | 2025.10.12 |