欢迎光临
我们一直在努力

LangChain学习-day02-模型的创建和调用

准备大模型

国内的头部大模型,如Deepseek、Qwen、Kimi、GLM等,都非常的优秀(为什么不用Claude、GPT呢,奈何钱包空空啊。つ﹏⊂),足够日常使用了,这里我选择了DeepSeek;

Deepseek开放平台:https://platform.deepseek.com/usage;

打开网址,找到API Keys,创建一个api key

image-20260716203837843

image-20260716203912070

这里注意,创建了key后一定要第一时间,复制出来,关闭后就不能复制了

image-20260716203956106

模型的创建

创建配置文件

先创建.env文件,配置模型的key和base_url

DEEPSEEK_API_KEY="XXX"
DEEPSEEK_API_BASE="https://api.deepseek.com"

配置文件的名字不是随便写的,源码中配置环境变量的时候建议使用DEEPSEEK_API_KEY和DEEPSEEK_API_BASE,只用标准名称后,在后边创建模型的时候可以省略这部分;如果创建模型的时候没有配置key和base_url,LangChain会自动去.env文件中找对应的配置;其他模型也是这样,有类似的名称,比如质谱就是ZHIPU_API_KEY和ZHIPU_API_BASE

image-20260716204729558

创建模型的三种办法

模型的专有API

import os

from dotenv import load_dotenv
from langchain_deepseek import ChatDeepSeek

load_dotenv(verbose=True)

DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
DEEPSEEK_API_BASE = os.getenv("DEEPSEEK_API_BASE")

deepseek_llm = ChatDeepSeek(
model="deepseek-v4-flash",
api_key=DEEPSEEK_API_KEY,
base_url=DEEPSEEK_API_BASE,
)

response = deepseek_llm.invoke("介绍一下你自己!")
print(response)

兼容的API

import os

from dotenv import load_dotenv
from langchain_openai import ChatOpenAI

load_dotenv(verbose=True)
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
DEEPSEEK_API_BASE = os.getenv("DEEPSEEK_API_BASE")

deepseek_llm = ChatOpenAI(
model="deepseek-v4-flash",
api_key=DEEPSEEK_API_KEY,
base_url=DEEPSEEK_API_BASE,
)

response = deepseek_llm.invoke("介绍一下你自己!")
print(response)

对话模型初始化的方式

import os

from dotenv import load_dotenv
from langchain.chat_models import init_chat_model

load_dotenv(verbose=True)
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
DEEPSEEK_API_BASE = os.getenv("DEEPSEEK_API_BASE")

# 第一种
deepseek_llm = init_chat_model(
model="deepseek:deepseek-v4-flash",
api_key=DEEPSEEK_API_KEY,
base_url=DEEPSEEK_API_BASE,
)
# 第二种
deepseek_llm = init_chat_model(
model_provider="deepseek",
model="deepseek-v4-flash",
api_key=DEEPSEEK_API_KEY,
base_url=DEEPSEEK_API_BASE,
)

response = deepseek_llm.invoke("介绍一下你自己!")
print(response)

在init_chat_model的方式中,新增模型供应商的概念;

源码中可以看到,现在支持的模型供应商如下所示:如果用的供应商不在这里面,供应商就需写openai,一般模型都支持openai协议;

– You want `model` and `model_provider` to be independently
swappable at runtime via `configurable_fields` (e.g., to route
the same model name to a different host).

Supported values and the integration package each requires:

– `openai` -> [`langchain-openai`](https://docs.langchain.com/oss/python/integrations/providers/openai)
– `anthropic` -> [`langchain-anthropic`](https://docs.langchain.com/oss/python/integrations/providers/anthropic)
– `azure_openai` -> [`langchain-openai`](https://docs.langchain.com/oss/python/integrations/providers/openai)
– `azure_ai` -> [`langchain-azure-ai`](https://docs.langchain.com/oss/python/integrations/providers/microsoft)
– `google_vertexai` -> [`langchain-google-vertexai`](https://docs.langchain.com/oss/python/integrations/providers/google)
– `google_genai` -> [`langchain-google-genai`](https://docs.langchain.com/oss/python/integrations/providers/google)
– `anthropic_bedrock` -> [`langchain-aws`](https://docs.langchain.com/oss/python/integrations/providers/aws)
– `bedrock` -> [`langchain-aws`](https://docs.langchain.com/oss/python/integrations/providers/aws)
– `bedrock_converse` -> [`langchain-aws`](https://docs.langchain.com/oss/python/integrations/providers/aws)
– `cohere` -> [`langchain-cohere`](https://docs.langchain.com/oss/python/integrations/providers/cohere)
– `fireworks` -> [`langchain-fireworks`](https://docs.langchain.com/oss/python/integrations/providers/fireworks)
– `together` -> [`langchain-together`](https://docs.langchain.com/oss/python/integrations/providers/together)
– `mistralai` -> [`langchain-mistralai`](https://docs.langchain.com/oss/python/integrations/providers/mistralai)
– `huggingface` -> [`langchain-huggingface`](https://docs.langchain.com/oss/python/integrations/providers/huggingface)
– `groq` -> [`langchain-groq`](https://docs.langchain.com/oss/python/integrations/providers/groq)
– `ollama` -> [`langchain-ollama`](https://docs.langchain.com/oss/python/integrations/providers/ollama)
– `google_anthropic_vertex` -> [`langchain-google-vertexai`](https://docs.langchain.com/oss/python/integrations/providers/google)
– `deepseek` -> [`langchain-deepseek`](https://docs.langchain.com/oss/python/integrations/providers/deepseek)
– `ibm` -> [`langchain-ibm`](https://docs.langchain.com/oss/python/integrations/providers/ibm)
– `nvidia` -> [`langchain-nvidia-ai-endpoints`](https://docs.langchain.com/oss/python/integrations/providers/nvidia)
– `xai` -> [`langchain-xai`](https://docs.langchain.com/oss/python/integrations/providers/xai)
– `openrouter` -> [`langchain-openrouter`](https://docs.langchain.com/oss/python/integrations/providers/openrouter)
– `perplexity` -> [`langchain-perplexity`](https://docs.langchain.com/oss/python/integrations/providers/perplexity)
– `upstage` -> [`langchain-upstage`](https://docs.langchain.com/oss/python/integrations/providers/upstage)
– `baseten` -> [`langchain-baseten`](https://docs.langchain.com/oss/python/integrations/providers/baseten)
– `litellm` -> [`langchain-litellm`](https://docs.langchain.com/oss/python/integrations/providers/litellm)
– `meta` -> [`langchain-meta`](https://pypi.org/project/langchain-meta)

创建参数

  • temperature,范围0~2,数值越大模型的创造性越强,比如在RAG项目中,要按照文档回答问题,这个值就要低一点,接近0比较好;
  • max_token,回答的最大token数量,超过最大token后截断content,标志:‘finish_reason’: ‘length’,正常结束是’finish_reason’: ‘stop’;

import os

from dotenv import load_dotenv
from langchain.chat_models import init_chat_model

load_dotenv(verbose=True)
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
DEEPSEEK_API_BASE = os.getenv("DEEPSEEK_API_BASE")

deepseek_llm = init_chat_model(
model="deepseek:deepseek-v4-flash",
api_key=DEEPSEEK_API_KEY,
base_url=DEEPSEEK_API_BASE,
temperature=2,
max_tokens=256,
)

response = deepseek_llm.invoke("介绍一下你自己!")
print(response)

模型的调用

调用有八种方式,分别是:

  • invoke(),等待模型响应后一次性输出结果;
  • stream(),流式输出,像打字机一样一个字一个字的输出;
  • batch(),批量输出,多个问题批量输出,按照问题顺序输出,减少网络开销,节省时间;
  • batch_as_completed(),批量输出,那个问题先结束就先输出
  • aivoke()、astream()、abatch(),对应方法的异步输出;

response = deepseek_llm.invoke("介绍一下你自己!")
response = deepseek_llm.stream("介绍一下你自己!")
response = deepseek_llm.batch("介绍一下你自己!")
response = deepseek_llm.batch_as_completed("介绍一下你自己!")

模型调用的时候传入的消息种类在后面的章节消息中说明;

美化输出

pretty_print()

response = deepseek_llm.invoke("介绍一下你自己!")
reponse.pretty_print()

只输出response.content;

image-20260716212327675

使用 rich 库

from rich import print as rprint
rprint(response)

输出

AIMessage(
content='你好呀!我是DeepSeek,很高兴认识你!😊\\n\\n让我做个自我介绍:\\n\\n**我是谁?**\\n我是由深度求索公司(Deep
Seek)开发的AI助手,是目前最新的DeepSeek模型。我的使命就是帮你解答问题、提供建议、协助创作,做你的贴心智能小伙伴!\\
n\\n**我能做什么?**\\n',
additional_kwargs={
'refusal': None,
'reasoning_content':
'好的,用户让我介绍一下自己。这是一个非常常见的开场问题,用户可能是第一次接触我,想了解我的基本情况和能力范围。我需
要给出一个清晰、全面且友好的自我介绍,帮助用户快速建立认知。\\n\\n想到了可以从几个核心方面来组织回复:先热情打招呼,
说明我是谁以及开发公司。然后重点介绍我的主要功能和特点,比如文本处理、上下文长度、文件支持、免费性质等,这些是用户
最可能关心的。接着说明我的能力边界,比如不支持多模态识别,避免用户产生误解。最后可以说明知识截止时间,并主动提供帮
助,激发用户进一步提问的意愿。\\n\\n整体结构可以按照“问候与身份说明 核心功能列举 重要限制说明 知识更新信息
开放邀请提问”来展开。语言要亲切、有条理,适当使用表情符号增加亲和力,但思考过程里不用考虑表情符。'
},
response_metadata={
'token_usage': {
'completion_tokens': 256,
'prompt_tokens': 7,
'total_tokens': 263,
'completion_tokens_details': {
'accepted_prediction_tokens': None,
'audio_tokens': None,
'reasoning_tokens': 185,
'rejected_prediction_tokens': None
},
'prompt_tokens_details': {'audio_tokens': None, 'cache_write_tokens': None, 'cached_tokens': 0},
'prompt_cache_hit_tokens': 0,
'prompt_cache_miss_tokens': 7
},
'model_provider': 'deepseek',
'model_name': 'deepseek-v4-flash',
'system_fingerprint': 'fp_8b330d02d0_prod0820_fp8_kvcache_20260402',
'id': '218063b5-a8e1-46ff-83be-ae102575a181',
'finish_reason': 'length',
'logprobs': None
},
id='lc_run–019f6b18-701d-7420-8caa-a0d5ccf361fb-0',
tool_calls=[],
invalid_tool_calls=[],
usage_metadata={
'input_tokens': 7,
'output_tokens': 256,
'total_tokens': 263,
'input_token_details': {'cache_read': 0},
'output_token_details': {'reasoning': 185}
}
)

学习langchain,一开始跟着AI学习,但是发现一个问题,AI输出的内容都比较久,新旧掺杂,代码就运行不出来,搞得心态爆照,后来就跟着官网学习,又在B站看了好多视频。我现在写博客的顺序是打乱官网的顺序,从比较基础的内容开始,后续的学习我会继续发,如果我的教程对您的学习有一点帮助,请给我一个赞,一个关注,您的支持就是我更新的动力;有问题可以评论,如果有错误的地方可以一起交流,我这边会改正;纯自学;

赞(0)
未经允许不得转载:171主机测评 » LangChain学习-day02-模型的创建和调用
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址