അപ്ഡേറ്റ് ചെയ്തത് 25 സെപ്റ്റ. 2025
8 മിനിറ്റ്
# pip install langchain langchain-openaifrom langchain_openai import ChatOpenAIfrom langchain_core.prompts import ChatPromptTemplate# 1) Modelllm = ChatOpenAI(model="gpt-4o-mini", temperature=0)# 2) Promptprompt = ChatPromptTemplate.from_messages( and streaming guide.---## Building Blocks You’ll Use 80% of the Time### 1) Prompts and Output Parsing- Use `ChatPromptTemplate` for structured prompts.- Parse outputs with `StrOutputParser` or JSON parsers for typed responses.```pythonfrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-4o-mini")prompt = ChatPromptTemplate.from_template("""Summarize the following text in 3 bullet points:---{text}""")parser = StrOutputParserchain = prompt | llm | parsersummary = chain.invoke({"text": "LangChain helps build LLM apps with RAG and tools."})print(summary)# pip install faiss-cpu tiktokenfrom langchain_openai import OpenAIEmbeddings, ChatOpenAIfrom langchain_community.vectorstores import FAISSfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_core.prompts import ChatPromptTemplate# Prepare documentstexts = .---## From Prototype to Production: A Step-by-Step Blueprint### Step 1: Define the User Story- Who is the user? What job are they trying to get done?- Example: “A support agent that answers product questions from internal docs and recent tickets.”### Step 2: Choose the Minimum Viable Stack- Model: Pick a reasonably priced, reliable model (e.g., GPT-4o-mini or a frontier open model).- Data: Decide if you need RAG now. If yes, start with FAISS locally.- I/O: Use LCEL for fast iteration; avoid custom glue code.### Step 3: Implement a Clean RAG Loop- Split docs properly.- Index embeddings.- Prompt with context and citations.- Add a guardrail to avoid hallucination when no relevant context is found.```pythonfrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.prompts import ChatPromptTemplateqa_prompt = ChatPromptTemplate.from_template("""Answer the question using ONLY the CONTEXT below. If the answer isn'tin the context, say "I don't know." Include cited doc IDs.CONTEXT:{context}QUESTION: {question}""")parser = StrOutputParserrag_chain = (RunnableParallel(context=retriever, question=RunnableLambda(lambda x: x.### Step 5: Typed Outputs and Validation- Use `PydanticOutputParser` or JSON schema to enforce structure for API responses.- Validate fields to catch model drift.### Step 6: Tooling and Function Calling for Real Tasks- Introduce tools sparingly.- Common tools: calculator, web search, SQL query executor, code runner.- Clearly describe tool capabilities in docstrings.### Step 7: Hardening- Rate limit and retry strategies.- Timeouts and circuit breakers.- Safety filters and content checks.### Step 8: Evaluation & Continuous Improvement- Test with golden datasets (input → expected output).- Evaluate faithfulness, answer completeness, and citation accuracy.- Measure retrieval hit rate and latency.---## Common Patterns and Gotchas- Start simple: Chains before agents. You’ll get predictability and lower cost.- Chunking matters: Tuning chunk size/overlap can change retrieval quality more than the model swap.- Prompt leakage: Don’t stuff the kitchen sink into system prompts; keep them focused.- Determinism: Set `temperature=0` for evaluation and critical workflows.- Streaming UX: Stream tokens to the UI while the rest of the system fetches assets or preloads context.- Structured outputs: Use parsers to make downstream integration painless.---## A Full Mini Project: Docs Q&A With CitationsThis example ties everything together: ingestion, RAG, answer generation, and streaming.```python# pip install langchain langchain-openai faiss-cpu tiktokenfrom langchain_openai import ChatOpenAI, OpenAIEmbeddingsfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_community.vectorstores import FAISSfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.runnables import RunnableParallel, RunnableLambda# 1) Ingestcorpus = {"pricing": "Our Pro plan supports 1M context tokens and includes priority support.","limits": "The API rate limit is 60 requests per minute for Pro users.","security": "We store logs for 30 days unless logging is disabled by the admin.",}splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=50)all_chunks, ids = [], []for doc_id, text in corpus.items:for i, chunk in enumerate(splitter.split_text(text)):all_chunks.append(chunk)ids.append(f"{doc_id}-{i}")# 2) Indexdb = FAISS.from_texts(all_chunks, OpenAIEmbeddings)retriever = db.as_retriever(k=4)# 3) Promptprompt = ChatPromptTemplate.from_template("""You are a support assistant. Use the CONTEXT to answer.If unsure, say "I don't know." Include citations of source IDs.CONTEXT:{context}QUESTION: {question}""")# 4) Model and parserllm = ChatOpenAI(model="gpt-4o-mini", temperature=0)parser = StrOutputParser# 5) Compose chainrag = (RunnableParallel(context=retriever,question=RunnableLambda(lambda x: x["question"]) # pass-through)| prompt| llm| parser)# 6) Ask a questionfor chunk in rag.stream({"question": "What are Pro rate limits and log retention?"}):print(chunk, end="", flush=True)ബാച്ച് വഴിയുള്ള ബാച്ച് പ്രോസസ്സിംഗ്.prompt | llm ചെയിൻ ഉണ്ടാക്കാൻ LCEL ഉപയോഗിക്കുക, കൂടാതെ .invoke അല്ലെങ്കിൽ .stream ഉപയോഗിച്ച് ടെസ്റ്റ് ചെയ്യുക. വേഗത്തിൽ തുടങ്ങാനായി ലളിതമായ ചാറ്റ്, RAG, ഏജൻ്റുകൾ എന്നിവയുടെ ഔദ്യോഗിക ട്യൂട്ടോറിയലുകൾ ഘട്ടം ഘട്ടമായി പഠിക്കുക.Runnable ചെയിനുകളും .stream സിങ്കിനായും .astream അസിങ്കിനായും പിന്തുണയ്ക്കുന്നു, ഇത് ഭാഗങ്ങൾ എത്തുമ്പോൾ നൽകുന്നു. സ്ട്രീമിംഗ് ഗൈഡിൽ ഉപയോഗവും മികച്ച രീതികളും ഉൾക്കൊള്ളുന്നു.
ChatPDF എങ്ങനെ നിപുണമാക്കാം: സാന്ദ്രമായ രേഖകളിൽ നിന്നുള്ള വേഗത്തിലുള്ള洞察ങ്ങൾ

വേഗതയുള്ള, കൃത്യമായ ഡോക്യുമെന്റുകൾക്കായി മികച്ച X ഓട്ടോ-ട്രാൻസ്ലേഷൻ বিকল্পം

ഇറാനിൽ Samsung AI വിവർത്തനം ലഭ്യമല്ലേ? പ്രായോഗിക പരിഹാരങ്ങൾ

പേർഷ്യൻ വിവർത്തന ഉപകരണങ്ങൾ: വേഗതയിലും കൃത്യതയിലും പ്രായോഗിക മാർഗ്ഗനിർദേശം

ആഴത്തിലുള്ള, ഉദ്ധരിക്കപ്പെട്ട ഗവേഷണത്തിനുള്ള മികച്ച Grok ബദലുകൾ

AI ഇമേജ് ജനറേറ്ററിൻ്റെ നിങ്ങൾ ശരിക്കും ഉപയോഗിക്കുന്ന 15 പ്രധാന ഫീച്ചറുകൾ