API Key设置

方案一:

import os
os.environ["OPENAI_API_KEY"] = "..."

方案二:

import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass()

模型创建

from langchain_oepnai import ChatOpenAI
model = ChatOpenAI(model="gpt4")

导入消息类型

from langchain_core.messages import (
    SystemMessage,
    HumanMessage,
    AIMessage,
)

使用invoke方法运行模型
方案一:

messages = [
  SystemMessage(content="Translate the following from English to Chinese"),
  HumanMessage(content="hi!"),
]

model.invoke(messages)

方案二:

from langchain_core.output_parsers import StrOutputParser
parser = StrOutputParser()

messages = [
  SystemMessage(content="Translate the following from English to Chinese"),
  HumanMessage(content="hi!"),
]

result = model.invoke(messages)
parser.invoke(result)

方案三:

from langchain_core.output_parsers import StrOutputParser
parser = StrOutputParser()

chain = model | parser
chain.invoke(messages)

使用提示词模板

from langchain_core.pormpts import ChatPromptTemplate

system_template = "Translate the following into {language}:"

prompt_template = ChatPromptTemplate.from_messages(
    [ ("system", system_template),
      ("user", "{text}"),
    ]
)

model = ChatOpenAI(model="gpt-4")
parser = StrOutputParser()

chain = prompt_template | model | parser

chain.invoke({"language": "Chinese", "text": "hi"})

整理各种导包

import os
import getpass

from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
#from langchain_core.prompts import MessagePlaceholder
最后修改:2024 年 09 月 11 日
如果觉得我的文章对你有用,请随意赞赏