Langchain笔记:模型

  • 在 LangChain 中,最简单的独立模型使用方式是通过 init_chat_model

1 init_model 创建模型

1.1 举例

python 复制代码
import os
from langchain.chat_models import init_chat_model

os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_**"

model = init_chat_model(
    "Qwen/Qwen3-0.6B",
    model_provider="huggingface",
    temperature=0.7,
    max_tokens=1024,
)

1.2 init_chat_model 主要参数

|-------------------|----------------------------------------------------------|
| model | 要使用的具体模型名称或 ID 也可以使用 provider:model 的格式,例如 openai:o1 |
| api_key(string) | 访问模型提供商所需的密钥,通常通过环境变量设置 |
| temperature | 控制输出的随机性。数值越高,输出越有创造性;越低,结果越确定 |
| max_tokens | 限制输出 token 的最大数量,从而控制回复长度 |
| timeout | 等待模型响应的最大时间(秒),超时则取消请求 |
| max_retries | 在网络超时或限流等错误下,允许重试的最大次数。 |

2 调用模型(invocation)

2,1 单条信息

python 复制代码
response = model.invoke("Why do parrots talk?")
print(response.content)
'''
<|im_start|>user
Why do parrots talk?<|im_end|>
<|im_start|>assistant
<think>
Okay, so the user is asking, "Why do parrots talk?" I need to address this question. Let me start by recalling what I know about parrots. Parrots are birds, and they do have the ability to talk. But why?

First, I should mention that parrots are intelligent animals. They have a high degree of intelligence, which allows them to learn and use language. This is important because it shows their cognitive abilities. I can explain that parrots have been observed to use tools, understand human speech, and even mimic sounds. 

Next, I should consider their social structure. Parrots are often seen as social animals. They communicate with others, and maybe they use their voices to interact with their flock. This social aspect is part of their communication. 

Also, I need to touch on their natural instincts. Parrots are known to mimic sounds and behaviors. They might mimic human speech, so that's another point. I should explain that their natural instincts include this mimicry.

Then, maybe mention their ability to learn and understand human language. They can learn to speak and understand speech, which is a remarkable trait. 

I should also consider the possibility of their role as ambassadors. Parrots might serve as messengers, passing on information. 

Wait, but I need to make sure not to confuse them with other animals. The user might be thinking of a different animal, so I should clarify that parrots are specifically birds. 

Also, I should mention that parrots have a lot of experience in their environment. They have lived for a long time, so they have developed the ability to talk. 

Are there any other factors? Maybe their physical characteristics. Parrots have feathers and strong beaks, which help them with their communication. 

I should also explain that their ability to talk is a result of their intelligence, social behavior, and natural instincts. 

I need to structure this into a clear answer. Start with the fact that parrots talk, then explain the reasons, including intelligence, social structure, mimicry, and learning. Maybe add that they use their voices to interact. 

Wait, but I should check if there's any information I might be missing. For example, do they have a specific way of speaking, or is it a general ability? 

Also, maybe mention that their ability to talk is not only a function of their brain but also their environment. They have evolved to communicate in their environment. 

I think that covers the main points. Let me put this all together in a coherent way.
</think>

Parrots are known for their remarkable ability to talk, which is a result of a combination of their intelligence, social behavior, and natural instincts. Here's a breakdown of why parrots can and do talk:

1. **Intelligence and Cognitive Abilities**: Parrots are highly intelligent animals, capable of learning complex behaviors and understanding human speech. They can mimic sounds, understand language, and engage in abstract thinking, which allows them to use words and language in their communication.

2. **Social Interaction**: Parrots are social creatures that live in groups. They use vocalizations to interact with their flock and communicate with their同伴 (friends). Their ability to mimic human speech and respond to human voices is often a sign of their social structure and communication skills.

3. **Natural Instincts**: Parrots have been observed to mimic sounds and behaviors, including human speech. This mimicry is part of their natural instinct to learn and adapt to their environment.

4. **Learning and Adaptation**: Parrots have developed a long history of learning and evolving to communicate effectively. Their ability to understand and use language is a testament to their cognitive capabilities.

In summary, parrots' ability to talk is a result of their intelligence, social nature, and natural instincts, allowing them to interact and communicate effectively within their environments.
'''

2.2 多轮对话

python 复制代码
conversation = [
    {"role": "system", "content": "You are a helpful assistant that translates English to French."},
    {"role": "user", "content": "Translate: I love programming."},
    {"role": "assistant", "content": "J'adore la programmation."},
    {"role": "user", "content": "Translate: I love building applications."}
]
response = model.invoke(conversation)
print(response.content)
'''
<|im_start|>system
You are a helpful assistant that translates English to French.<|im_end|>
<|im_start|>user
Translate: I love programming.<|im_end|>
<|im_start|>assistant
J'adore la programmation.<|im_end|>
<|im_start|>user
Translate: I love building applications.<|im_end|>
<|im_start|>assistant
<think>
Okay, the user wants me to translate "I love building applications." into French. Let me start by breaking it down.

First, "I love" translates to "J'adore" in French. Then, "building applications" -- applications in French can be "applications" or "applications" as well. "Building" here is the main verb, so "créer" is the right choice. 

Putting it together: "J'adore créer des applications." That seems correct. Let me double-check to make sure there's no typo or grammatical error. "Applications" is plural, which matches the action of building multiple applications. 

I think that's it. The translation is accurate and natural in French.
</think>

J'adore créer des applications.

'''

注:conversation这些,在LangChain 里被做成了强类型对象

python 复制代码
conversation = [
    SystemMessage("You are a helpful assistant that translates English to French."),
    HumanMessage("Translate: I love programming."),
    AIMessage("J'adore la programmation."),
    HumanMessage("Translate: I love building applications.")
]

所以如果是Agent设计(LangGraph,LangChain),那就要用后者

3 流式输出

python 复制代码
for chunk in model.stream("Why do parrots have colorful feathers?"):
    print(chunk.text, end="", flush=True)

4 批次输出

python 复制代码
responses = model.batch([
    "Why do parrots have colorful feathers?",
    "How do airplanes fly?",
    "What is quantum computing?"
])

responses
'''
[AIMessage(content="<|im_start|>user\nWhy do parrots have colorful feathers?<|im_end|>\n<|im_start|>assistant\n<think>\nOkay, the user is asking why parrots have colorful feathers. Let me start by recalling what I know about parrots. Parrots are known for their vibrant colors and feathers. I remember that some parrots have colors like blue and green, and they often sing in different songs. \n\nFirst, I should mention the purpose of colorful feathers. Maybe they are used for communication, like signaling to other parrots. Also, some parrots have feathers that are not just for color but for other functions. For example, some species have feathers that are used for protection or as a tool in their environment.\n\nI should also think about evolutionary reasons. Colorful feathers might have evolved over time to help with camouflage, so parrots can blend in with their surroundings or warn other animals. Additionally, the colors could serve as a form of mimicry, like in some birds to confuse predators.\n\nI need to make sure I cover the main points: communication, camouflage, mimicry, and maybe some evolutionary aspects. Also, it's good to mention that parrots are often seen with colorful feathers and that their colorful appearance is a trait that has been passed down through generations. \n\nWait, did I mention the different types of feathers? I think the user is interested in the specific reasons behind this trait, so maybe breaking it down into points would be helpful. Also, maybe include some examples of parrots that have different colors to give context. \n\nI should avoid any technical terms and keep the explanation simple and engaging. The user might be a bird enthusiast or someone curious about their pets, so the answer should be informative but not too complex. Let me check if I have all the key points covered and make sure the information is accurate.\n</think>\n\nParrots have colorful feathers for several reasons, both evolutionary and functional. Here's a breakdown:\n\n1. **Communication**: Colorful feathers help parrots communicate with other birds. For example, some parrots use bright colors to signal their mood, territory, or even to attract mates.\n\n2. **Camouflage**: Some parrots have feathers that mimic the colors of their surroundings, helping them blend into their habitats and avoid predators.\n\n3. **Mimicry**: Some parrots use their feathers to mimic other birds or even animals, which can be a defense mechanism or a way to escape predators.\n\n4. **Evolutionary Adaptation**: Colorful feathers evolved over time to enhance survival. Bright colors may have helped parrots avoid predators or signal their health and fitness to others.\n\n5. **Tool Use**: In some cases, colorful feathers might be used as a tool for feeding or nesting, though this is less common.\n\nIn summary, the colorful feathers of parrots are a combination of traits that have evolved to aid in survival, communication, and adaptation to their environments.", additional_kwargs={}, response_metadata={}, id='lc_run--019c1962-e1a0-7ce0-a8f2-835059a19b9f-0', tool_calls=[], invalid_tool_calls=[]),
 AIMessage(content="<|im_start|>user\nHow do airplanes fly?<|im_end|>\n<|im_start|>assistant\n<think>\nOkay, the user asked how airplanes fly. Let me start by breaking down the basic question. First, I need to explain the main components of an airplane. There's the fuselage, wings, engines, and the control surfaces. Then, the propulsion system. Maybe mention the engine and how it generates thrust. Oh, and the lift that's generated by the wings.\n\nWait, what about the aerodynamics? The wings create lift, which allows the plane to stay in the air. I should explain how the wings work, like the shape and the flow of air over them. Maybe mention the airspeed and lift. Also, the takeoff and landing processes. How the engines start the plane, then the engines provide thrust, and the wings generate lift. \n\nI should make sure to explain all these parts in a clear way without getting too technical. Maybe start with the basic components and then move to the propulsion and lift. Also, include how the flight path is determined by the wind and the plane's position. Oh, and mention the control systems, like the ailerons and rudders. \n\nWait, did I miss anything? The user might be a student learning about aviation, so using simple terms would be best. Avoid jargon, but still be thorough. Let me check if I have all the main parts covered: fuselage, wings, engines, lift, aerodynamics, takeoff, landing, and control systems. Yes, that seems to cover it. Alright, time to put it all together in a coherent answer.\n</think>\n\nAirplanes fly based on a combination of aerodynamics, propulsion, and control systems. Here's a simplified breakdown:\n\n1. **Fuselage and Wings**:  \n   - The fuselage (body) and wings are the main structural components. The wings generate lift, which is the force pushing the plane upward. The shape of the wings (like an airfoil) and the airflow over them create this lift.\n\n2. **Propulsion**:  \n   - Engines provide thrust, which is the force pushing the plane forward. The engines use fuel and a combustion engine to generate power.\n\n3. **Lift**:  \n   - The wings create lift by causing the air above them to rise faster than below, according to Bernoulli's principle. This forces the plane upward and keeps it in the air.\n\n4. **Aerodynamics**:  \n   - The interaction between the air and the plane's shape is crucial. The airflow over the wings and under the fuselage affects how much lift is generated.\n\n5. **Takeoff and Landing**:  \n   - The engines start the plane, and the engines provide thrust to lift off. Once airborne, the plane continues to maneuver with ailerons (to control roll) and rudders (to control pitch). During landing, the plane slows down to touch down on the ground.\n\nIn essence, airplanes use the principles of physics (like lift, thrust, and aerodynamics) to move through the air, staying aloft and maneuvering as needed.", additional_kwargs={}, response_metadata={}, id='lc_run--019c1962-e1a4-79c2-9c92-0df3382f06cb-0', tool_calls=[], invalid_tool_calls=[]),
 AIMessage(content="<|im_start|>user\nWhat is quantum computing?<|im_end|>\n<|im_start|>assistant\n<think>\nOkay, the user is asking what quantum computing is. Let me start by explaining the basics. I know quantum computing uses qubits instead of classical bits. I should mention that qubits can be both 0 and 1 at the same time, which is superposition. Then, they can be entangled, so changing one affects the others. I should also talk about the difference from classical computers, like faster computation but with error rates.\n\nWait, I need to make sure I cover the key points: qubits, superposition, entanglement, and why quantum computing is different. Also, mention the current challenges and future potential. Let me check if I'm missing anything. Oh right, quantum computers can solve certain problems much faster than classical computers, like factoring large numbers or simulating molecules. But there are still hurdles like error correction. I should also touch on real-world applications, like cryptography or drug discovery. Alright, that should cover it.\n</think>\n\nQuantum computing is a revolutionary approach to computation that leverages the principles of quantum mechanics to process information in ways that classical computers cannot. Here's a breakdown of its key features and differences:\n\n1. **Qubits (Quantum Bits)**: Unlike classical bits (which are either 0 or 1), quantum bits (qubits) can exist in a superposition of both states simultaneously. This allows quantum computers to explore many possibilities at once, potentially solving complex problems much more efficiently.\n\n2. **Entanglement**: Qubits can be entangled, meaning the state of one qubit is directly correlated with the state of another, regardless of their spatial separation. This enables quantum computers to perform calculations that could be infeasible for classical machines.\n\n3. **Superposition and Coherence**: Qubits can be in multiple states at once (superposition) and maintain that state for a very long time (coherence), which is essential for quantum algorithms.\n\n4. **Speed and Power**: While quantum computers can solve certain problems exponentially faster than classical computers (e.g., factoring large numbers or simulating quantum systems), current models face challenges in error rates and scalability.\n\n5. **Challenges**: Errors due to decoherence and the need for error-corrected qubits (like surface codes) are significant hurdles. Additionally, quantum hardware is still not yet in a state where it can be reliably used for real applications.\n\n6. **Potential Applications**: Quantum computing could revolutionize fields like cryptography (breaking RSA encryption), drug discovery, optimization problems, and materials science. However, practical quantum computers are still in development and not yet widely available.", additional_kwargs={}, response_metadata={}, id='lc_run--019c1962-e1a5-7bf3-ab6c-7248f441e4b7-0', tool_calls=[], invalid_tool_calls=[])]
'''
相关推荐
傻小胖2 小时前
19.ETH-挖矿算法-北大肖臻老师客堂笔记
笔记·算法·区块链
紫罗兰盛开2 小时前
招商银行股票分析
经验分享·笔记
方安乐2 小时前
react笔记之useCallback/useEffect闭包陷阱
前端·笔记·react.js
gentle coder2 小时前
【langchain】agent部署的基础入门代码(持续更新中~)
python·langchain·react
蒸蒸yyyyzwd10 小时前
cpp对象模型学习笔记1.1-2.8
java·笔记·学习
dalong1010 小时前
A14:自定义动画演示
笔记·aardio
今儿敲了吗11 小时前
鸿蒙开发第一章学习笔记
笔记·学习·鸿蒙
闪闪发亮的小星星11 小时前
刚体运动学复习笔记
笔记
你大爷的,这都没注册了12 小时前
LangChain 安装
langchain