LLM开发指南

韩乔落

基础知识

参考链接 0 参考链接 1 参考链接 2 参考链接 3 参考链接 4

环境准备

vscode 创建 python 3.13 虚拟环境。

安装以下包:

并非全部要用到,后面打算更新的也在这里了

1
pip install langchain langchain-core langchain-community langchain-openai langgraph langsmith langserve langchain-tavily langchain-text-splitters langchain-huggingface -qU

跟着 参考链接 0 配置好.env文件。最好把链接中的基础概念,小实验做一遍再来学习。

1
2
3
4
5
6
7
8
9
OPENAI_API_KEY="*"
OPENAI_API_BASE="*"

LANGSMITH_TRACING=true
LANGSMITH_API_KEY="*"
LANGSMITH_ENDPOINT="*"
LANGSMITH_PROJECT="*"

TAVILY_API_KEY="*"

也可以设置好环境变量,然后通过程序获取(配置了.env不用执行下面的函数):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def get_env_llms_api():
import getpass
import os
"""
Get the environment variables for the LLMS API."
"""
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")
if not os.environ.get("OPENAI_API_BASE"):
os.environ["OPENAI_API_BASE"] = getpass.getpass("Enter the OpenAI API base URL: ")
if not os.environ.get("LANGSMITH_TRACING"):
os.environ["LANGSMITH_TRACING"] = "true"
if not os.environ.get("LANGSMITH_API_KEY"):
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your Langsmith API key: ")
# ......

教程说明

本教程持续更新,通过实验来学习LangChain、LangGraph、LangSmith,项目源码链接 LangChallenge

LangChain

#1 结构化输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def EasyTranslate():
"""
EasyTranslate using langchain and openai
轻松翻译,使用 langchain 和 openai
"""
from langchain_openai import ChatOpenAI # openai for langchain
from langchain_core.prompts import PromptTemplate # prompt template for langchain

llm = ChatOpenAI (
model_name="gpt-4o", # gpt-4o for openai
temperature=0, # 创作自由度,越高越自由,越低越严谨
max_tokens=4096, # 输出长度
streaming=True # streaming for openai
)

# prompt template
prompt = PromptTemplate.from_template(
"把下面这句话从{src_language}翻译成{dst_language} : {text_message}"
)

src_language = input("请输入源语言: ")
dst_language = input("请输入目标语言: ")
text_message = input("请输入要翻译的文本: ")

# message for prompt template
message = prompt.format(
src_language=src_language,
dst_language=dst_language,
text_message=text_message,
)

print(message)

# # with_structured_output

from typing import Optional
from pydantic import BaseModel, Field
# Pydantic
class TranslationRequest(BaseModel):
"""Translation request."""

src_language: str = Field(description="源语言")
dst_language: str = Field(description="目标语言")
text_message: str = Field(description="要翻译的文本")
response: Optional[str] = Field(
default=None, description="翻译后的文本"
)

structured_llm = llm.with_structured_output(TranslationRequest)

for chunk in structured_llm.stream([message]):
print(f"源语言:{chunk.src_language}")
print(f"目标语言:{chunk.dst_language}")
print(f"要翻译的文本:{chunk.text_message}")
print(f"翻译后的文本:{chunk.response}")


if __name__ == "__main__":
EasyTranslate()
1
2
3
4
5
6
7
8
请输入源语言: 中文
请输入目标语言: 韩语
请输入要翻译的文本: 你好
把下面这句话从中文翻译成韩语 : 你好
源语言:中文
目标语言:韩国语
要翻译的文本:你好
翻译后的文本:안녕하세요

#2 工具调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def caclulate():
from langchain_core.tools import tool
from langchain.chat_models import init_chat_model
from pydantic import BaseModel, Field

llm = init_chat_model(model="gpt-4o", model_provider="openai")

# 加法运算参数描述
class AdditionInput(BaseModel):
a: int = Field(..., description="First number")
b: int = Field(..., description="Second number")

# 定义加法运算工具,绑定参数,函数描述不可少
# 修饰器tool的第一个参数是工具名称,第二个参数是参数描述
@tool("Addition", args_schema=AdditionInput)
def Addition(a: int, b: int) -> int:
"""Add two numbers"""
return a + b

# 乘法运算参数描述
class MultiplyInput(BaseModel):
a: int = Field(..., description="First number")
b: int = Field(..., description="Second number")

# 定义乘法运算工具,绑定参数,函数描述不可少
# 修饰器tool的第一个参数是工具名称,第二个参数是参数描述
@tool("Multiply", args_schema=MultiplyInput)
def Multiply(a: int, b: int) -> int:
"""Multiply two numbers"""
return a * b

tools = [Addition, Multiply]
llm_with_tools = llm.bind_tools(tools)

from langchain_core.messages import HumanMessage

question = "What is 2 + 3? Also what is 5 * 6?"
messages = [HumanMessage(question)]

ai_msg = llm_with_tools.invoke(messages)

# tool_calls 调用工具,返回参数描述符号
print(ai_msg.tool_calls)

for tool_call in ai_msg.tool_calls:
# AI选择了哪个工具
selected_tool = {"Addition": Addition, "Multiply": Multiply}[tool_call["name"]]
# 调用工具,返回消息
tool_msg = selected_tool.invoke(tool_call)
# 加入到历史消息中
messages.append(tool_msg)

print(messages)

if __name__ == '__main__':
caclulate()
1
2
3
4
5
6
7
8
9
10
11
[{
'name': 'Addition',
'args': {'a': 2, 'b': 3}, 'id': 'call_cgQpK9TzPOJnntRwae3MBoTL', 'type': 'tool_call'
},
{
'name': 'Multiply',
'args': {'a': 5, 'b': 6}, 'id': 'call_RNF0ZbEZwpkK10lmqyi0jKk4', 'type': 'tool_call'
}]
[
HumanMessage(content='What is 2 + 3? Also what is 5 * 6?', additional_kwargs={}, response_metadata={}), ToolMessage(content='5', name='Addition', tool_call_id='call_cgQpK9TzPOJnntRwae3MBoTL'), ToolMessage(content='30', name='Multiply', tool_call_id='call_RNF0ZbEZwpkK10lmqyi0jKk4')
]

LangGraph

LangSmith

  • Title: LLM开发指南
  • Author: 韩乔落
  • Created at : 2025-03-21 10:47:22
  • Updated at : 2025-03-28 14:33:03
  • Link: https://jelasin.github.io/2025/03/21/LLM开发指南/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments