Langchain 使用 OpenAI 聊天模型

Langchain 使用 OpenAI 聊天模型

本笔记本介绍了如何开始使用 OpenAI 聊天模型。

示例代码,

from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain.schema import AIMessage, HumanMessage, SystemMessage
chat = ChatOpenAI(temperature=0)

上面的示例代码假设您的 OpenAI API 密钥已在环境变量中设置。如果您想手动指定 API 密钥和/或组织 ID,请使用以下代码:

chat = ChatOpenAI(temperature=0, openai_api_key="YOUR_API_KEY", openai_organization="YOUR_ORGANIZATION_ID")

如果 openai_organization 参数不适用于您,请将其删除。

messages = [
    SystemMessage(
        content="You are a helpful assistant that translates English to French."
    ),
    HumanMessage(
        content="Translate this sentence from English to French. I love programming."
    ),
]
chat(messages)

您可以通过使用 MessagePromptTemplate 来使用模板。

您可以从一个或多个 MessagePromptTemplates 构建 ChatPromptTemplate

您可以使用 ChatPromptTemplateformat_prompt —— 这会返回 PromptValue ,您可以将其转换为字符串或 Message 对象,具体取决于您是否想要使用格式化值作为 llm 或聊天模型的输入。

为了方便起见,模板上公开了一个 from_template 方法。如果您要使用此模板,它将如下所示:

template = (
    "You are a helpful assistant that translates {input_language} to {output_language}."
)
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages(
    [system_message_prompt, human_message_prompt]
)

# get a chat completion from the formatted messages
chat(
    chat_prompt.format_prompt(
        input_language="English", output_language="French", text="I love programming."
    ).to_messages()
)
chat_prompt = ChatPromptTemplate.from_messages(
    [system_message_prompt, human_message_prompt]
)

# get a chat completion from the formatted messages
chat(
    chat_prompt.format_prompt(
        input_language="English", output_language="French", text="I love programming."
    ).to_messages()
)

完结!

猜你喜欢

转载自blog.csdn.net/engchina/article/details/131873420