पाठ 5 / 31
Prompt Templates और Messages
चरों के साथ पुनः उपयोग योग्य prompts बनाएँ।
नामित slots वाले templates
ChatPromptTemplate {variables} वाले template से भूमिका-चिह्नित messages (system, human, AI) की सूची बनाता है। मानों के dict के साथ invoke करने पर prompt value मिलता है जिसे messages में बदला जा सकता है। Templates prompts को पुनः उपयोग योग्य, versionable और परखने योग्य बनाते हैं, और template अपने इनपुट चर जानता है, इसलिए आधा-भरा prompt भेजने की जगह ग़ायब मान साफ़ error के साथ जल्दी विफल होता है। Chat इतिहास के लिए MessagesPlaceholder और उदाहरण डालने के लिए FewShotChatMessagePromptTemplate उपयोग करें। Prompt पाठ को files या constants में रखें, कोड में बिखेरें नहीं।
Pipe से जोड़ें
Runnables का एक साझा interface है, इसलिए prompts, models और parsers pipe से जुड़ सकते हैं।
Chat prompt template, चलाकर
मैंने यह Python virtual environment में langchain-core 1.6.6, langchain-text-splitters 1.1.2 और llama-index-core 0.14.25 के साथ ऑफ़लाइन चलाया। किसी API key या network call की ज़रूरत नहीं क्योंकि असली मॉडल की जगह fake मॉडल या खिलौना embedding है। Template चर भरे हुए SystemMessage और HumanMessage बनाता है, और बताता है कि उसे इनपुट question और role चाहिए।
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "You are a {role}. Answer in one sentence."),
("human", "{question}"),
])
value = prompt.invoke({"role": "geography teacher", "question": "What is the capital of India?"})
for m in value.to_messages():
print(type(m).__name__, "|", m.content)
print(prompt.input_variables)
Output:
SystemMessage | You are a geography teacher. Answer in one sentence. HumanMessage | What is the capital of India? ['question', 'role']
अक्षरशः braces escape करें
आपके prompt में JSON braces हों तो {{ और }} लिखें ताकि template उन्हें चर न माने।
त्वरित जाँच: Prompt templates का एक लाभ क्या है?
- वे मॉडल को मुफ़्त करते हैं
- पुनः उपयोग योग्य prompts जो चर ग़ायब होने पर जल्दी विफल होते हैं
- वे prompt को मॉडल से छिपाते हैं
- वे parsers को बदलते हैं
Answer
पुनः उपयोग योग्य prompts जो चर ग़ायब होने पर जल्दी विफल होते हैं — Templates prompt निर्माण को संरचना और validation देते हैं।