【LLM實戰|langchain】langchain基礎

every blog every motto: You can do more than you think.
https://blog.csdn.net/weixin_39190382?type=blog

0. 前言

【LLM實戰|langchain】langchain基礎

1. 模型 I/O 封裝

把不同的模型,統一封裝成一個接口,方便更換模型而不用重構代碼。

1.1 模型 API: ChatModel

1.1.1 OpenAI 模型封裝
# !pip install -U langchain
# !pip install -U langchain-openai
from langchain.chat_models import init_chat_model
model = init_chat_model("gpt-4o-mini", model_provider="openai")
response = model.invoke("你是誰")
print(response.content)
1.1.2 多輪對話sessoin
from langchain.schema import (AIMessage,  # 等價于OpenAI接口中的assistant roleHumanMessage,  # 等價于OpenAI接口中的user roleSystemMessage  # 等價于OpenAI接口中的system role
)messages = [SystemMessage(content="你是AI課程助理。"),HumanMessage(content="我是學員,我叫小a。"),AIMessage(content="歡迎!"),HumanMessage(content="我是誰?")
]ret = model.invoke(messages)print(ret.content)
1.1.3 換個國產模型
# !pip install -U langchain-deepseek
from langchain.chat_models import init_chat_modelmodel = init_chat_model(model="deepseek-chat", model_provider="deepseek")response = model.invoke("你是誰")
print(response.content)
我是DeepSeek Chat,由深度求索公司(DeepSeek)研發的智能AI助手!? 我可以幫你解答各種問題,無論是學習、工作、生活,還是科技、娛樂、編程等,我都會盡力提供準確、有用的信息。  有什么我可以幫你的嗎?😊
1.1.4 流式輸出流式輸出
for token in model.stream("你是誰"):print(token.content, end="")
我是DeepSeek Chat,由深度求索公司(DeepSeek)開發的智能AI助手!? 我的使命是幫助你解答各種問題,無論是學習、工作,還是日常生活中的小疑惑,我都會盡力提供準確、有用的信息。  有什么我可以幫你的嗎?😊

1.2 模型的輸入與輸出

1.2.1 Prompt 模板封裝
  1. PromptTemplate 可以在模板中自定義變量
from langchain.prompts import PromptTemplatetemplate = PromptTemplate.from_template("給我講個關于{subject}的笑話")
print("===Template===")
print(template)
print("===Prompt===")
print(template.format(subject='小明'))
===Template===
input_variables=['subject'] input_types={} partial_variables={} template='給我講個關于{subject}的笑話'
===Prompt===
給我講個關于小明的笑話
from langchain.chat_models import init_chat_model# 定義 LLM
llm = init_chat_model("deepseek-chat", model_provider="deepseek")
# 通過 Prompt 調用 LLM
ret = llm.invoke(template.format(subject='小明'))
# 打印輸出
print(ret.content)
好的!這里有一個關于小明的經典笑話:**老師**:小明,用“果然”造個句。  
**小明**:我先吃蘋果,然后喝涼水……  
**老師**:這不對,不能拆開詞語!  
**小明**:那我重新造——昨天我吃水果,然后拉肚子了!  
**老師**:……這是“果然”嗎??  
**小明**(自信):是啊!水果+然后=果然!  (冷場中,全班同學默默翻開了詞典)  希望這個“硬核造句”能讓你笑一下! 😄
  1. ChatPromptTemplate 用模板表示的對話上下文
from langchain.prompts import (ChatPromptTemplate,HumanMessagePromptTemplate,SystemMessagePromptTemplate,
)
from langchain.chat_models import init_chat_model
# llm = init_chat_model("gpt-4o-mini", model_provider="openai")
llm = init_chat_model("deepseek-chat", model_provider="deepseek")template = ChatPromptTemplate.from_messages([SystemMessagePromptTemplate.from_template("你是{product}的客服助手。你的名字叫{name}"),HumanMessagePromptTemplate.from_template("{query}")]
)prompt = template.format_messages(product="五年高考三年模擬",name="小高",query="你是誰"
)print(prompt)ret = llm.invoke(prompt)print(ret.content)
[SystemMessage(content='你是五年高考三年模擬的客服助手。你的名字叫小高', additional_kwargs={}, response_metadata={}), HumanMessage(content='你是誰', additional_kwargs={}, response_metadata={})]
你好呀!我是五年高考三年模擬的客服助手小高~ 很高興為你服務!有什么關于五三教輔的問題都可以問我哦,比如教材版本、使用方法、購買咨詢等等,我都會盡力幫你解答!(??????)??
  1. MessagesPlaceholder 把多輪對話變成模板
from langchain.prompts import (ChatPromptTemplate,HumanMessagePromptTemplate,MessagesPlaceholder,
)human_prompt = "Translate your answer to {language}."
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)chat_prompt = ChatPromptTemplate.from_messages(# variable_name 是 message placeholder 在模板中的變量名# 用于在賦值時使用[MessagesPlaceholder("history"), human_message_template]
)
from langchain_core.messages import AIMessage, HumanMessagehuman_message = HumanMessage(content="Who is Elon Musk?")
ai_message = AIMessage(content="Elon Musk is a billionaire entrepreneur, inventor, and industrial designer"
)messages = chat_prompt.format_prompt(# 對 "history" 和 "language" 賦值history=[human_message, ai_message], language="中文"
)print(messages.to_messages())
[HumanMessage(content='Who is Elon Musk?', additional_kwargs={}, response_metadata={}), AIMessage(content='Elon Musk is a billionaire entrepreneur, inventor, and industrial designer', additional_kwargs={}, response_metadata={}), HumanMessage(content='Translate your answer to 中文.', additional_kwargs={}, response_metadata={})]
result = llm.invoke(messages)
print(result.content)
埃隆·馬斯克(Elon Musk)是一位億萬富翁企業家、發明家和工業設計師。他是多家高科技公司的創始人或領導者,包括特斯拉(Tesla)、SpaceX、Neuralink和The Boring Company。馬斯克以推動電動汽車、太空探索、人工智能和可再生能源等領域的創新而聞名。

1.2 從文件加載prompt模板

from langchain.prompts import PromptTemplatetemplate = PromptTemplate.from_file("example_prompt_template.txt")
print("===Template===")
print(template)
print("===Prompt===")
print(template.format(topic='黑色幽默'))
===Template===
input_variables=['topic'] input_types={} partial_variables={} template='舉一個關于{topic}的例子'
===Prompt===
舉一個關于黑色幽默的例子

1.3 結構化輸出

1.3.1 直接輸出pydantic對象
from pydantic import BaseModel, Field# 定義你的輸出對象
class Date(BaseModel):year: int = Field(description="Year")month: int = Field(description="Month")day: int = Field(description="Day")era: str = Field(description="BC or AD")
from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langchain_core.output_parsers import PydanticOutputParserfrom langchain.chat_models import init_chat_model
# llm = init_chat_model("gpt-4o-mini", model_provider="openai")
llm = init_chat_model("deepseek-chat", model_provider="deepseek")# 定義結構化輸出的模型
structured_llm = llm.with_structured_output(Date)template = """提取用戶輸入中的日期。
用戶輸入:
{query}"""prompt = PromptTemplate(template=template,
)query = "2023年四月6日天氣晴..."
input_prompt = prompt.format_prompt(query=query)structured_llm.invoke(input_prompt)
Date(year=2023, month=4, day=6, era='AD')
1.3.2 輸出指定格式的 JSON
# OpenAI 模型的JSON格式
json_schema = {"title": "Date","description": "Formated date expression","type": "object","properties": {"year": {"type": "integer","description": "year, YYYY",},"month": {"type": "integer","description": "month, MM",},"day": {"type": "integer","description": "day, DD",},"era": {"type": "string","description": "BC or AD",},},
}
structured_llm = llm.with_structured_output(json_schema)structured_llm.invoke(input_prompt)
{'year': 2023, 'month': 4, 'day': 6}
1.3.3 使用 OutputParser

OutputParser 可以按指定格式解析模型的輸出

from langchain_core.output_parsers import JsonOutputParserparser = JsonOutputParser(pydantic_object=Date)prompt = PromptTemplate(template="提取用戶輸入中的日期。\n用戶輸入:{query}\n{format_instructions}",input_variables=["query"],partial_variables={"format_instructions": parser.get_format_instructions()},
)input_prompt = prompt.format_prompt(query=query)
output = llm.invoke(input_prompt)
print("原始輸出:\n"+output.content)print("\n解析后:")
parser.invoke(output)
原始輸出:
```json
{"year": 2023,"month": 4,"day": 6,"era": "AD"
}
```解析后:{'year': 2023, 'month': 4, 'day': 6, 'era': 'AD'}

也可以用 PydanticOutputParser

from langchain_core.output_parsers import PydanticOutputParserparser = PydanticOutputParser(pydantic_object=Date)input_prompt = prompt.format_prompt(query=query)
output = llm.invoke(input_prompt)
print("原始輸出:\n"+output.content)print("\n解析后:")
parser.invoke(output)
原始輸出:
```json
{"year": 2023,"month": 4,"day": 6,"era": "AD"
}
```解析后:Date(year=2023, month=4, day=6, era='AD')

OutputFixingParser 利用大模型做格式自動糾錯

from langchain.output_parsers import OutputFixingParser
from langchain.chat_models import init_chat_modelllm = init_chat_model(model="deepseek-chat", model_provider="deepseek")# 糾錯能力與大模型能力相關
new_parser = OutputFixingParser.from_llm(parser=parser, llm=llm)bad_output = output.content.replace("4","四")
print("PydanticOutputParser:")
try:parser.invoke(bad_output)
except Exception as e:print(e)print("OutputFixingParser:")
new_parser.invoke(bad_output)
PydanticOutputParser:
Invalid json output: ```json
{"year": 2023,"month": 四,"day": 6,"era": "AD"
}
```
For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE 
OutputFixingParser:Date(year=2023, month=4, day=6, era='AD')

1.4 Function Calling

from langchain_core.tools import tool@tool
def add(a: int, b: int) -> int:"""Add two integers.Args:a: First integerb: Second integer"""return a + b@tool
def multiply(a: float, b: float) -> float:"""Multiply two integers.Args:a: First integerb: Second integer"""return a * b
import jsonllm_with_tools = llm.bind_tools([add, multiply])query = "3.5的4倍是多少?"
messages = [HumanMessage(query)]output = llm_with_tools.invoke(messages)print(json.dumps(output.tool_calls, indent=4))
[{"name": "multiply","args": {"a": 3.5,"b": 4},"id": "call_0_2ff05fac-e682-4fa2-9274-b20e2dba817c","type": "tool_call"}
]
messages.append(output)available_tools = {"add": add, "multiply": multiply}for tool_call in output.tool_calls:selected_tool = available_tools[tool_call["name"].lower()]tool_msg = selected_tool.invoke(tool_call)messages.append(tool_msg)new_output = llm_with_tools.invoke(messages)
for message in messages:print(json.dumps(message.model_dump(), indent=4, ensure_ascii=False))
print(new_output.content)
{"content": "3.5的4倍是多少?","additional_kwargs": {},"response_metadata": {},"type": "human","name": null,"id": null,"example": false
}
{"content": "","additional_kwargs": {"tool_calls": [{"id": "call_0_2ff05fac-e682-4fa2-9274-b20e2dba817c","function": {"arguments": "{\"a\":3.5,\"b\":4}","name": "multiply"},"type": "function","index": 0}],"refusal": null},"response_metadata": {"token_usage": {"completion_tokens": 25,"prompt_tokens": 250,"total_tokens": 275,"completion_tokens_details": null,"prompt_tokens_details": {"audio_tokens": null,"cached_tokens": 0},"prompt_cache_hit_tokens": 0,"prompt_cache_miss_tokens": 250},"model_name": "deepseek-chat","system_fingerprint": "fp_8802369eaa_prod0623_fp8_kvcache","id": "c420227e-444d-4d8a-9a91-54735949b8c5","service_tier": null,"finish_reason": "tool_calls","logprobs": null},"type": "ai","name": null,"id": "run--92a3e96d-0f04-470e-b411-2b6766e23d6d-0","example": false,"tool_calls": [{"name": "multiply","args": {"a": 3.5,"b": 4},"id": "call_0_2ff05fac-e682-4fa2-9274-b20e2dba817c","type": "tool_call"}],"invalid_tool_calls": [],"usage_metadata": {"input_tokens": 250,"output_tokens": 25,"total_tokens": 275,"input_token_details": {"cache_read": 0},"output_token_details": {}}
}
{"content": "14.0","additional_kwargs": {},"response_metadata": {},"type": "tool","name": "multiply","id": null,"tool_call_id": "call_0_2ff05fac-e682-4fa2-9274-b20e2dba817c","artifact": null,"status": "success"
}
3.5的4倍是14.0。

1.5 小結

  1. LangChain 統一封裝了各種模型的調用接口,包括補全型和對話型兩種
  2. LangChain 提供了 PromptTemplate 類,可以自定義帶變量的模板
  3. LangChain 提供了一些列輸出解析器,用于將大模型的輸出解析成結構化對象
  4. LangChain 提供了 Function Calling 的封裝
  5. 上述模型屬于 LangChain 中較為實用的部分

2. 數據連接封裝

2.1 文檔加載器:Document Loaders

# !pip install -U langchain-community pymupdf
from langchain_community.document_loaders import PyMuPDFLoaderloader = PyMuPDFLoader("./data/deepseek-v3-1-4.pdf")
pages = loader.load_and_split()print(pages[0].page_content)
DeepSeek-V3 Technical Report
DeepSeek-AI
research@deepseek.com
Abstract
We present DeepSeek-V3, a strong Mixture-of-Experts (MoE) language model with 671B total
parameters with 37B activated for each token. To achieve efficient inference and cost-effective
training, DeepSeek-V3 adopts Multi-head Latent Attention (MLA) and DeepSeekMoE architec-
tures, which were thoroughly validated in DeepSeek-V2. Furthermore, DeepSeek-V3 pioneers
an auxiliary-loss-free strategy for load balancing and sets a multi-token prediction training
objective for stronger performance. We pre-train DeepSeek-V3 on 14.8 trillion diverse and
high-quality tokens, followed by Supervised Fine-Tuning and Reinforcement Learning stages to
fully harness its capabilities. Comprehensive evaluations reveal that DeepSeek-V3 outperforms
other open-source models and achieves performance comparable to leading closed-source
models. Despite its excellent performance, DeepSeek-V3 requires only 2.788M H800 GPU hours
for its full training. In addition, its training process is remarkably stable. Throughout the entire
training process, we did not experience any irrecoverable loss spikes or perform any rollbacks.
The model checkpoints are available at https://github.com/deepseek-ai/DeepSeek-V3.
MMLU-Pro
(EM)
GPQA-Diamond
(Pass@1)
MATH 500
(EM)
AIME 2024
(Pass@1)
Codeforces
(Percentile)
SWE-bench Verified
(Resolved)
0
20
40
60
80
100
Accuracy / Percentile (%)
75.9
59.1
90.2
39.2
51.6
42.0
66.2
41.3
74.7
16.7
35.6
22.6
71.6
49.0
80.0
23.3
24.8
23.8
73.3
51.1
73.8
23.3
25.3
24.5
72.6
49.9
74.6
9.3
23.6
38.8
78.0
65.0
78.3
16.0
20.3
50.8
DeepSeek-V3
DeepSeek-V2.5
Qwen2.5-72B-Inst
Llama-3.1-405B-Inst
GPT-4o-0513
Claude-3.5-Sonnet-1022
Figure 1 | Benchmark performance of DeepSeek-V3 and its counterparts.
arXiv:2412.19437v2  [cs.CL]  18 Feb 2025

2.2 文檔處理器

2.2.1 TextSplitter
# !pip install --upgrade langchain-text-splitters
from langchain_text_splitters import RecursiveCharacterTextSplittertext_splitter = RecursiveCharacterTextSplitter(chunk_size=512,chunk_overlap=200, length_function=len,add_start_index=True,
)paragraphs = text_splitter.create_documents([pages[0].page_content])
for para in paragraphs:print(para.page_content)print('-------')
DeepSeek-V3 Technical Report
DeepSeek-AI
research@deepseek.com
Abstract
We present DeepSeek-V3, a strong Mixture-of-Experts (MoE) language model with 671B total
parameters with 37B activated for each token. To achieve efficient inference and cost-effective
training, DeepSeek-V3 adopts Multi-head Latent Attention (MLA) and DeepSeekMoE architec-
tures, which were thoroughly validated in DeepSeek-V2. Furthermore, DeepSeek-V3 pioneers
-------
training, DeepSeek-V3 adopts Multi-head Latent Attention (MLA) and DeepSeekMoE architec-
tures, which were thoroughly validated in DeepSeek-V2. Furthermore, DeepSeek-V3 pioneers
an auxiliary-loss-free strategy for load balancing and sets a multi-token prediction training
objective for stronger performance. We pre-train DeepSeek-V3 on 14.8 trillion diverse and
high-quality tokens, followed by Supervised Fine-Tuning and Reinforcement Learning stages to
-------
objective for stronger performance. We pre-train DeepSeek-V3 on 14.8 trillion diverse and
high-quality tokens, followed by Supervised Fine-Tuning and Reinforcement Learning stages to
fully harness its capabilities. Comprehensive evaluations reveal that DeepSeek-V3 outperforms
other open-source models and achieves performance comparable to leading closed-source
models. Despite its excellent performance, DeepSeek-V3 requires only 2.788M H800 GPU hours
-------
other open-source models and achieves performance comparable to leading closed-source
models. Despite its excellent performance, DeepSeek-V3 requires only 2.788M H800 GPU hours
for its full training. In addition, its training process is remarkably stable. Throughout the entire
training process, we did not experience any irrecoverable loss spikes or perform any rollbacks.
The model checkpoints are available at https://github.com/deepseek-ai/DeepSeek-V3.
MMLU-Pro
(EM)
GPQA-Diamond
(Pass@1)
MATH 500
(EM)

2.3、向量數據庫與向量檢索

# !pip install dashscope
# !pip install faiss-cpu
import os
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.embeddings import DashScopeEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_community.document_loaders import PyMuPDFLoader# 加載文檔
loader = PyMuPDFLoader("./data/deepseek-v3-1-4.pdf")
pages = loader.load_and_split()# 文檔切分
text_splitter = RecursiveCharacterTextSplitter(chunk_size=512,chunk_overlap=200,length_function=len,add_start_index=True,
)texts = text_splitter.create_documents([page.page_content for page in pages[:1]]
)# 灌庫
embeddings = DashScopeEmbeddings(model="text-embedding-v1", dashscope_api_key=os.getenv("DASHSCOPE_API_KEY")
)
index = FAISS.from_documents(texts, embeddings)# 檢索 top-5 結果
retriever = index.as_retriever(search_kwargs={"k": 5})docs = retriever.invoke("deepseek v3有多少參數")for doc in docs:print(doc.page_content)print("----")
22.6
71.6
49.0
80.0
23.3
24.8
23.8
73.3
51.1
73.8
23.3
25.3
24.5
72.6
49.9
74.6
9.3
23.6
38.8
78.0
65.0
78.3
16.0
20.3
50.8
DeepSeek-V3
DeepSeek-V2.5
Qwen2.5-72B-Inst
Llama-3.1-405B-Inst
GPT-4o-0513
Claude-3.5-Sonnet-1022
Figure 1 | Benchmark performance of DeepSeek-V3 and its counterparts.
arXiv:2412.19437v2  [cs.CL]  18 Feb 2025
----
objective for stronger performance. We pre-train DeepSeek-V3 on 14.8 trillion diverse and
high-quality tokens, followed by Supervised Fine-Tuning and Reinforcement Learning stages to
fully harness its capabilities. Comprehensive evaluations reveal that DeepSeek-V3 outperforms
other open-source models and achieves performance comparable to leading closed-source
models. Despite its excellent performance, DeepSeek-V3 requires only 2.788M H800 GPU hours
----
training, DeepSeek-V3 adopts Multi-head Latent Attention (MLA) and DeepSeekMoE architec-
tures, which were thoroughly validated in DeepSeek-V2. Furthermore, DeepSeek-V3 pioneers
an auxiliary-loss-free strategy for load balancing and sets a multi-token prediction training
objective for stronger performance. We pre-train DeepSeek-V3 on 14.8 trillion diverse and
high-quality tokens, followed by Supervised Fine-Tuning and Reinforcement Learning stages to
----
DeepSeek-V3 Technical Report
DeepSeek-AI
research@deepseek.com
Abstract
We present DeepSeek-V3, a strong Mixture-of-Experts (MoE) language model with 671B total
parameters with 37B activated for each token. To achieve efficient inference and cost-effective
training, DeepSeek-V3 adopts Multi-head Latent Attention (MLA) and DeepSeekMoE architec-
tures, which were thoroughly validated in DeepSeek-V2. Furthermore, DeepSeek-V3 pioneers
----
other open-source models and achieves performance comparable to leading closed-source
models. Despite its excellent performance, DeepSeek-V3 requires only 2.788M H800 GPU hours
for its full training. In addition, its training process is remarkably stable. Throughout the entire
training process, we did not experience any irrecoverable loss spikes or perform any rollbacks.
The model checkpoints are available at https://github.com/deepseek-ai/DeepSeek-V3.
MMLU-Pro
(EM)
GPQA-Diamond
(Pass@1)
MATH 500
(EM)
----

3. Chain 和 LangChain Expression Language (LCEL)

LangChain Expression Language(LCEL)是一種聲明式語言,可輕松組合不同的調用順序構成 Chain。LCEL 自創立之初就被設計為能夠支持將原型投入生產環境,無需代碼更改,從最簡單的“提示+LLM”鏈到最復雜的鏈(已有用戶成功在生產環境中運行包含數百個步驟的 LCEL Chain)。

LCEL 的一些亮點包括:

  1. 流支持:使用 LCEL 構建 Chain 時,你可以獲得最佳的首個令牌時間(即從輸出開始到首批輸出生成的時間)。對于某些 Chain,這意味著可以直接從 LLM 流式傳輸令牌到流輸出解析器,從而以與 LLM 提供商輸出原始令牌相同的速率獲得解析后的、增量的輸出。

  2. 異步支持:任何使用 LCEL 構建的鏈條都可以通過同步 API(例如,在 Jupyter 筆記本中進行原型設計時)和異步 API(例如,在 LangServe 服務器中)調用。這使得相同的代碼可用于原型設計和生產環境,具有出色的性能,并能夠在同一服務器中處理多個并發請求。

  3. 優化的并行執行:當你的 LCEL 鏈條有可以并行執行的步驟時(例如,從多個檢索器中獲取文檔),我們會自動執行,無論是在同步還是異步接口中,以實現最小的延遲。

  4. 重試和回退:為 LCEL 鏈的任何部分配置重試和回退。這是使鏈在規模上更可靠的絕佳方式。目前我們正在添加重試/回退的流媒體支持,因此你可以在不增加任何延遲成本的情況下獲得增加的可靠性。

  5. 訪問中間結果:對于更復雜的鏈條,訪問在最終輸出產生之前的中間步驟的結果通常非常有用。這可以用于讓最終用戶知道正在發生一些事情,甚至僅用于調試鏈條。你可以流式傳輸中間結果,并且在每個 LangServe 服務器上都可用。

  6. 輸入和輸出模式:輸入和輸出模式為每個 LCEL 鏈提供了從鏈的結構推斷出的 Pydantic 和 JSONSchema 模式。這可以用于輸入和輸出的驗證,是 LangServe 的一個組成部分。

  7. 無縫 LangSmith 跟蹤集成:隨著鏈條變得越來越復雜,理解每一步發生了什么變得越來越重要。通過 LCEL,所有步驟都自動記錄到 LangSmith,以實現最大的可觀察性和可調試性。

  8. 無縫 LangServe 部署集成:任何使用 LCEL 創建的鏈都可以輕松地使用 LangServe 進行部署。

原文:https://python.langchain.com/docs/expression_language/

3.1 Pipeline 式調用 PromptTemplate, LLM 和 OutputParser

from langchain.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from pydantic import BaseModel, Field
from typing import List, Dict, Optional
from enum import Enum
import json
from langchain.chat_models import init_chat_model
# 輸出結構
class SortEnum(str, Enum):data = 'data'price = 'price'class OrderingEnum(str, Enum):ascend = 'ascend'descend = 'descend'class Semantics(BaseModel):name: Optional[str] = Field(description="流量包名稱", default=None)price_lower: Optional[int] = Field(description="價格下限", default=None)price_upper: Optional[int] = Field(description="價格上限", default=None)data_lower: Optional[int] = Field(description="流量下限", default=None)data_upper: Optional[int] = Field(description="流量上限", default=None)sort_by: Optional[SortEnum] = Field(description="按價格或流量排序", default=None)ordering: Optional[OrderingEnum] = Field(
description="升序或降序排列", default=None)# Prompt 模板
prompt = ChatPromptTemplate.from_messages([("system", "你是一個語義解析器。你的任務是將用戶的輸入解析成JSON表示。不要回答用戶的問題。"),("human", "{text}"),]
)# 模型
llm = init_chat_model("deepseek-chat", model_provider="deepseek")structured_llm = llm.with_structured_output(Semantics)# LCEL 表達式
runnable = ({"text": RunnablePassthrough()} | prompt | structured_llm
)# 直接運行
ret = runnable.invoke("不超過100元的流量大的套餐有哪些")
print(json.dumps(ret.model_dump(),indent = 4,ensure_ascii=False)
)
{"name": null,"price_lower": null,"price_upper": 100,"data_lower": null,"data_upper": null,"sort_by": "data","ordering": "descend"
}

3.2 用 LCEL 實現 RAG

import os
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain.chains import RetrievalQA
from langchain_community.document_loaders import PyMuPDFLoader
from langchain_community.embeddings.dashscope import DashScopeEmbeddings# 加載文檔
loader = PyMuPDFLoader("./data/deepseek-v3-1-4.pdf")
pages = loader.load_and_split()# 文檔切分
text_splitter = RecursiveCharacterTextSplitter(chunk_size=512,chunk_overlap=200,length_function=len,add_start_index=True,
)texts = text_splitter.create_documents([page.page_content for page in pages[:1]]
)# 灌庫
embeddings = DashScopeEmbeddings(model="text-embedding-v1", dashscope_api_key=os.getenv("DASHSCOPE_API_KEY")
)
db = FAISS.from_documents(texts, embeddings)# 檢索 top-5 結果
retriever = db.as_retriever(search_kwargs={"k": 5})
docs = retriever.invoke("deepseek v3有多少參數")for doc in docs:print(doc.page_content)print("----")
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnablePassthrough
from langchain.prompts import ChatPromptTemplate# Prompt模板
template = """Answer the question based only on the following context:
{context}Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)# Chain
rag_chain = ({"question": RunnablePassthrough(), "context": retriever}| prompt| llm| StrOutputParser()
)rag_chain.invoke("deepseek V3有多少參數")
'DeepSeek-V3 是一個混合專家(MoE)語言模型,總參數為 **6710 億(671B)**,其中每個 token 激活 **370 億(37B)** 參數。'

3.3 用 LCEL 實現模型切換(工廠模式)

from langchain_core.runnables.utils import ConfigurableField
from langchain_community.chat_models import QianfanChatEndpoint
from langchain.prompts import (ChatPromptTemplate,HumanMessagePromptTemplate,
)
from langchain.chat_models import init_chat_model
from langchain.schema import HumanMessage
import os# 模型1
ds_model = init_chat_model("deepseek-chat", model_provider="deepseek")# 模型2
gpt_model = init_chat_model("gpt-4o-mini", model_provider="openai")# 通過 configurable_alternatives 按指定字段選擇模型
model = gpt_model.configurable_alternatives(ConfigurableField(id="llm"), default_key="gpt", deepseek=ds_model,# claude=claude_model,
)# Prompt 模板
prompt = ChatPromptTemplate.from_messages([HumanMessagePromptTemplate.from_template("{query}"),]
)# LCEL
chain = ({"query": RunnablePassthrough()} | prompt| model | StrOutputParser()
)# 運行時指定模型 "gpt" or "deepseek"
ret = chain.with_config(configurable={"llm": "deepseek"}).invoke("請自我介紹")print(ret)
你好!我是 **DeepSeek Chat**,由深度求索(DeepSeek)公司研發的智能AI助手。我的知識截止到 **2024年7月**,可以幫助你解答各種問題,包括**學習、工作、編程、寫作、生活小技巧**等。  ### ? **我的特點**:
- **免費使用**:目前不收費,隨時為你提供幫助!  
- **超長上下文支持**:可以處理 **128K** 長度的文本,適合分析長文檔、論文或復雜對話。  
- **文件閱讀能力**:支持上傳 **PDF、Word、Excel、PPT、TXT** 等文件,并從中提取關鍵信息。  
- **邏輯清晰**:擅長數學推理、代碼編寫、論文潤色等任務。  
- **中文優化**:對中文理解和生成特別友好,同時也能流利使用英文和其他語言。  ### 🚀 **我能幫你做什么?**  
? **學習輔導**:解題思路、論文寫作、語言翻譯  
? **工作助手**:寫郵件、做PPT、整理數據  
? **編程支持**:代碼調試、算法講解、Python/Java/C++等  
? **創意寫作**:小說、詩歌、廣告文案  
? **生活百科**:旅行攻略、健康建議、美食推薦  如果你有任何問題,盡管問我吧!😊 你今天想了解什么呢?

3.4 通過 LCEL,還可以實現

  1. 配置運行時變量:https://python.langchain.com/docs/how_to/configure/
  2. 故障回退:https://python.langchain.com/docs/how_to/fallbacks/
  3. 并行調用:https://python.langchain.com/docs/how_to/parallel/
  4. 邏輯分支:https://python.langchain.com/docs/how_to/routing/
  5. 動態創建 Chain: https://python.langchain.com/docs/how_to/dynamic_chain/

更多例子:https://python.langchain.com/docs/how_to/lcel_cheatsheet/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/92561.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/92561.shtml
英文地址,請注明出處:http://en.pswp.cn/web/92561.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

十九、MySQL-DQL-基本查詢

基本查詢代碼:DQL:基本查詢 1.查詢指定字段 name,entrydate 并返回 -- 1.查詢指定字段 name,entrydate 并返回 select name,entrydate from tb_emp;2.查詢返回所有字段 -- 2.查詢返回所有字段 -- 推薦 select id, username, password, name, gender, image, job, e…

CamX-驍龍相機修改

1. 修改視頻模式預覽尺寸和分辨率 vendor/codeaurora/packages/apps/SnapdragonCamera/src/com/android/camera/CaptureModule.javaprivate void updatePreviewSize() {int width mPreviewSize.getWidth();int height mPreviewSize.getHeight(); - mPreviewSize new …

容器技術基礎與實踐:從鏡像管理到自動運行配置全攻略

1. 相比較虛擬機,容器有哪些技術優勢?(1)直接在操作系統上運行,從而跨系統上的所有容器共享資源,‘(2)共享主機的內核。(3)與虛擬機相比,它需要的…

書生浦語第五期-L1G4-InternLM 論文分類微調實踐(XTuner 版)

XTuner介紹一句話介紹XTuner:XTuner 是一個高效、靈活、全能的輕量化大模型微調工具庫。核心特點:高效:支持在有限資源下微調大模型,如在8GB顯存上微調7B參數模型,也支持多節點微調70B模型;自動分發高性能算…

從靈感枯竭到批量產出:無憂秘書創作平臺如何重構內容生產者的工作流程?全環節賦能分析

在當今快節奏的數字時代,內容創作者面臨著前所未有的挑戰。無論是自媒體運營者、自由撰稿人還是企業營銷人員,都需要高效地生產高質量的內容以滿足市場需求。然而,靈感枯竭、效率低下以及內容質量不穩定等問題常常困擾著這些內容生產者。為了…

【開源工具】基于Python的PDF清晰度增強工具全解析(附完整源碼)

??? 【開源工具】基于Python的PDF清晰度增強工具全解析(附完整源碼) ?? 個人主頁:創客白澤 - CSDN博客 ?? 系列專欄:??《Python開源項目實戰》 ?? 熱愛不止于代碼,熱情源自每一個靈感閃現的夜晚。愿以開源之火,點亮前行之路。 ?? 希望大家多多支持,我們一起進…

Qwen-Image開源模型實戰

Qwen-Image開源模型實戰:ComfyUI低顯存量化部署與中文海報生成指南 阿里云通義千問團隊最新開源的Qwen-Image模型以其卓越的中英文文本渲染能力在AI繪圖領域掀起了一場革命。這款200億參數的MMDiT架構模型不僅能夠生成高質量圖像,更突破了AI繪圖長期存在…

JavaWeb03——javascript基礎語法

1.什么是JavaScript?JavaScript(簡稱 JS)是一種 編程語言,它主要用來為網頁添加交互功能。它可以讓網頁變得動態,讓它不僅僅是靜態的文字和圖片,還能響應用戶操作(比如點擊按鈕、彈框警告等&…

數據庫入門:從零開始構建你的第一個數據庫

歡迎來到數據庫的世界!今天,我們將一起探索如何創建、管理和查詢數據庫。無論你是初學者還是希望加深理解的開發者,這篇博客都將幫助你更好地掌握數據庫的基礎知識。一、數據庫的基本操作創建數據庫首先,讓我們從創建一個新數據庫…

從匯編角度揭秘C++構造函數(1)

C的構造函數一直比較神秘,今天我們通過匯編的角度來揭秘一下,它的本質是什么。與常規函數有什么不同。從以下這段代碼說起: class Person { public:Person(int age) { _age age; }void printAge(){ printf("age %d\r\n",_age); …

java10學習筆記

Java 10 于 2018 年 3 月發布,是 Java 平臺按照新的六個月發布周期發布的第一個版本。雖然相比 Java 8 和 Java 9 的大型更新,Java 10 的變化較小,但仍然引入了一些重要的特性,特別是本地變量類型推斷(var)…

Flutter Listview的基本使用

Listview() 前端頁面常見的一個以列表方式顯示內容的組件。可垂直或水平滾動的列表。屬性說明scrollDirection設置滾動的方向,取值包括horizontal、verticalreverse設置是否翻轉,默認值falseitemExtent設置滾動方向子元素的長度,垂直方向為高…

強化學習筆記:從Q學習到GRPO

推薦學習huggingface的強化學習課程,全面了解強化學習的發展史。 以下是個人筆記,內容不一定完整,有些是個人理解。 基于值函數(value function)的強化學習 基于值函數(value function)的強化學習:學習的是一個值函數&#xff0…

MySQL索引底層原理與性能優化實踐

#技術棧深潛計劃一、前言 在日常開發中,MySQL數據庫以其高效、易用、可擴展等特性成為最主流的關系型數據庫之一。而索引作為數據庫查詢優化的核心工具,被譽為“數據庫的加速器”。但你真的了解MySQL索引的底層原理嗎?為什么InnoDB默認采用B樹…

Ext系列文件系統

1.硬件常見的硬件有磁盤、服務器、機柜、機房機械磁盤但是計算機中唯一的一個機械設備磁盤外設的特點就是外設慢容量大,價格便宜1.1.磁盤的物理結構磁盤的物理圖:磁盤的存儲圖扇區:是磁盤存儲數據的基本單位,512字節,塊設備磁盤的…

前綴函數——KMP的本質

前綴函數我個人覺得 oiwiki 上的學習順序是很合理的,學 KMP 之前先了解前綴函數是非常便于理解的。前后綴定義 前綴 prefixprefixprefix 指的是從字符串 SSS 的首位到某個位置 iii 的一個子串,這樣的子串寫作 prefix(S,i)prefix(S,i)prefix(S,i)。 后綴 …

解決chrome下載crx文件被自動刪除,加載未打包的擴展程序時提示“無法安裝擴展程序,因為它使用了不受支持的清單版本解決方案”

解決chrome下載crx文件被自動刪除 【chrome設置-隱私與安全-安全瀏覽】,選擇 不保護 【chrome設置-下載內容】,勾選 下載前詢問每個文件的保存位置 下載crx文件時,選擇保存文件夾,將 .crx后綴 改為 .zip后綴,再確定。 …

嵌入式學習day23-shell命令

linux軟件編程學習大綱:1.IO操作文件2.多任務編程3.網絡編程4.數據庫編程5.硬件設備管理學習目標:1.學習接口調用(第一層)2.軟件操作流程和思想(第二層)3.軟件設計思想和流程架構(第三層&#x…

GPT-5 系列深度詳解:第1章-引言(目錄)

1 引言2 模型數據與訓練3 觀察到的安全挑戰與評估 3.1 從強制拒絕到安全完成 3.2 禁?內容 3.3 拍?屁 3.4 越獄 3.5 指令層級 3.6 幻覺 3.7 欺騙 3.7.1 欺騙思維鏈監控 3.8 圖像輸入 3.9 健康 3.10 多語言性能 3.1.1公平性與偏見: BBQ評估4 紅隊測試與外部評估…

NineData 新增支持 AWS ElastiCache 復制鏈路

2025 年,絕大多數企業已完成業務上云,以獲取更高的彈性、可擴展性和成本效益。AWS ElastiCache 作為 AWS 提供的全托管式內存數據庫服務,已成為許多企業在云上構建高并發、低延遲應用的理想選擇。NineData 數據復制現已全面支持從自建 Redis …