Deep Read

Chain

把 chain 想象成一条流水线

输入数据 → [template] → [llm] → [parser] → 输出结果
              填占位符    调用AI   提取文本

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate
from langchain_core.output_parsers import StrOutputParser

from models import DEEPSEEK_URL, DEEPSEEK_V4_PRO
import os

api_key = os.getenv("MY_DEEPSEEK_API_KEY")
base_url = DEEPSEEK_URL
model = DEEPSEEK_V4_PRO
llm = ChatOpenAI(api_key=api_key, base_url=base_url, model=model)


"""
# 第1种格式
template = ChatPromptTemplate.from_messages(
    [("system", "你是一名专业的翻译助手"), ("human", "讲以下{text} 翻译成英文")]
)

# 第2种格式 
template = ChatPromptTemplate.from_messages([("human", "讲以下{text} 翻译成英文")])

"""
# 第3种格式
template = ChatPromptTemplate.from_template("讲以下{text} 翻译成英文")

message = template.invoke({"text": "我是程序员"})
# 真正调用大模型,返回 AI 的回答
aimessage = llm.invoke(message)

# 创建解析器
parser = StrOutputParser()
result = parser.invoke(aimessage)
print(result)



# chain = template | llm | parser

# # invoke 就是触发整个 chain 执行,把输入数据从头到尾跑一遍,返回最终结果。
# result = chain.invoke(["text", "我是程序员"])