0Pricing
LangChain / RAG / Vector DBs · 课时

提示、LLM 与基础链

掌握提示工程,连接不同的 LLM 提供商,并为基础任务创建简单的顺序链

提示、LLM 与基础链 是 CoddyKit 上的免费 LangChain / RAG / Vector DBs 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 LangChain / RAG / Vector DBs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 LangChain / RAG / Vector DBs 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Prompts, LLMs, & Chains

Welcome to this lesson! We'll explore the fundamental building blocks of LangChain: Prompts, Large Language Models (LLMs), and Chains.

These three components are at the heart of almost every application you'll build with LangChain, enabling powerful interactions with AI.

The Art of Prompt Engineering

A prompt is the input text you give to an LLM to guide its response. Crafting effective prompts is known as prompt engineering.

Good prompts are clear, concise, and provide enough context for the LLM to generate the desired output. They are crucial for getting useful results.

Dynamic Prompts with Templates

Instead of hardcoding prompts, LangChain uses PromptTemplate to create dynamic prompts. This allows you to insert variables into your prompt text.

Here's a simple example of how to define a template and format it:

from langchain_core.prompts import PromptTemplate

def main():
    template = "What is a good name for a company that makes {product}?"
    prompt = PromptTemplate.from_template(template)

    # Format the prompt with a specific product
    formatted_prompt = prompt.format(product="colorful socks")
    print(formatted_prompt)

if __name__ == "__main__":
    main()

Connecting to LLMs

LangChain provides a unified interface to interact with various Large Language Models (LLMs), such as OpenAI's GPT series or Google's Gemini.

You typically need an API key from your chosen provider. LangChain abstracts away the specifics, letting you swap models easily.

Making Your First LLM Call

Let's see how to connect to an LLM and make a simple call. We'll use ChatOpenAI as a common example, but the pattern is similar for others.

Remember to set your API key as an environment variable (OPENAI_API_KEY).

import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage

def main():
    # Make sure your OPENAI_API_KEY is set as an environment variable
    # os.environ["OPENAI_API_KEY"] = "your_api_key_here"

    if "OPENAI_API_KEY" not in os.environ:
        print("Please set the OPENAI_API_KEY environment variable.")
        return

    llm = ChatOpenAI(temperature=0.7)
    
    # Invoke the LLM with a simple message
    response = llm.invoke([HumanMessage(content="Tell me a short, funny story.")])
    print(response.content)

if __name__ == "__main__":
    main()

What are LangChain Chains?

Chains are a core concept in LangChain. They allow you to combine LLMs with other components, or even other chains, into multi-step workflows.

Instead of making individual LLM calls, chains let you define a sequence of operations, making your applications more structured and powerful.

The Simple LLMChain

The LLMChain is one of the simplest and most fundamental chains. It combines a PromptTemplate and an LLM (or ChatModel) into a single, executable unit.

It takes input variables, formats them into the prompt, sends the prompt to the LLM, and returns the LLM's response.

Building Your First LLMChain

Let's create an LLMChain to generate company names based on a product description. We'll use the prompt template and LLM we discussed.

This shows how easy it is to link a prompt and an LLM together.

import os
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate

def main():
    # Set your API key
    if "OPENAI_API_KEY" not in os.environ:
        print("Please set the OPENAI_API_KEY environment variable.")
        return

    # 1. Define the PromptTemplate
    prompt_template = PromptTemplate.from_template(
        "What is a creative name for a company that makes {product}?"
    )

    # 2. Initialize the LLM
    llm = ChatOpenAI(temperature=0.7)

    # 3. Create the LLMChain
    chain = LLMChain(llm=llm, prompt=prompt_template)

    # 4. Run the chain with an input
    response = chain.invoke({"product": "eco-friendly water bottles"})
    print(response["text"])

if __name__ == "__main__":
    main()

Chaining Multiple Inputs

An LLMChain can handle multiple input variables in its prompt template, making it highly flexible. Just ensure all variables are provided when invoking the chain.

Here's an example with two inputs: product and style.

import os
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate

def main():
    # Set your API key
    if "OPENAI_API_KEY" not in os.environ:
        print("Please set the OPENAI_API_KEY environment variable.")
        return

    # Define a prompt with multiple input variables
    prompt_template = PromptTemplate.from_template(
        "Suggest {num} {style} names for a company that sells {product}."
    )

    llm = ChatOpenAI(temperature=0.8)
    chain = LLMChain(llm=llm, prompt=prompt_template)

    # Invoke the chain with all required inputs
    response = chain.invoke({
        "num": 3,
        "style": "modern",
        "product": "handmade jewelry"
    })
    print(response["text"])

if __name__ == "__main__":
    main()

Quick Check

You've learned about prompts, LLMs, and basic chains. Let's test your understanding of how these pieces fit together in LangChain.

Recap & Next Steps

Great job! In this lesson, you've mastered the fundamentals:

  • Prompt Engineering: How to craft effective inputs for LLMs.
  • LLM Integration: Connecting to and making calls with Large Language Models using LangChain.
  • Basic Chains: Understanding and building your first LLMChain to sequence prompts and LLMs.

These skills are essential for building more complex applications. Next, we'll dive into Output Parsers and Callbacks to further control and monitor your LangChain applications.

常见问题解答

「提示、LLM 与基础链」课时是免费的吗?

是的 — 「提示、LLM 与基础链」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 LangChain / RAG / Vector DBs 课程的其余内容,请升级到 CoddyKit PRO。 LangChain / RAG / Vector DBs 课程共包含 4 节课。

「提示、LLM 与基础链」这节课中我会学到什么?

掌握提示工程,连接不同的 LLM 提供商,并为基础任务创建简单的顺序链 你通过在浏览器中直接运行的动手代码来练习 LangChain / RAG / Vector DBs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 LangChain / RAG / Vector DBs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 LangChain / RAG / Vector DBs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「提示、LLM 与基础链」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 LangChain / RAG / Vector DBs 课中编写并运行代码吗?

能。每节 LangChain / RAG / Vector DBs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设置您的 LangChain 环境
  2. 提示、LLM 与基础链
  3. 输出解析器与回调
  4. LangChain 中的记忆与对话上下文
← 返回 LangChain / RAG / Vector DBs