from langchain.chat_models import ChatOpenAI
from langchain.schema import HumanMessage
# 定义函数调用示例(如不需要可忽略此段)
functions = [
{
"name": "get_stock_price",
"description": "Retrieve real-time stock price for a given symbol",
"parameters": {
"type": "object",
"properties": {
"symbol": {
"type": "string",
"description": "The stock ticker symbol, e.g. AAPL"
}
},
"required": ["symbol"]
}
}
]
# 初始化 ChatGPT 模型(带所有行为控制参数)
chat = ChatOpenAI(
model="gpt-4", # 模型名称
temperature=0.2, # 控制随机性,越低越确定
top_p=0.9, # nucleus sampling:越低越保守
max_tokens=512, # 最长生成长度
stop=["\n\n"], # 遇到特定字符停止生成
frequency_penalty=0.1, # 避免重复
presence_penalty=0.3, # 鼓励引入新词
logit_bias={ # 控制某些词出现概率(示例:限制“buy”)
# 这里的 token_id 需要通过 tokenizer 查找
1234: -100 # 将 token 1234 的概率大幅降低
},
functions=functions # 使用函数调用能力(OpenAI function-calling)
)
# 构造用户输入
messages = [
HumanMessage(content="What is the stock price of AAPL?")
]
# 模型输出
response = chat(messages)
print(response.content)
📝 注意事项:
logit_bias 参数中使用的是 token ID,你可以用 OpenAI Tokenizer 工具或 tiktoken 库来找出目标词的 token ID。
functions 参数只能用于 gpt-4-0613, gpt-4-1106-preview, gpt-3.5-turbo-0613 等支持 Function Calling 的模型。
- 如果使用 LangChain 的 Agent + Tool 调度,还需额外封装成 tool 调用格式。