文档

基础知识

使用聊天

用于表示与 LLM 聊天对话的 API

SDK 方法,例如 llm.respond()llm.applyPromptTemplate()llm.act(),都将聊天参数作为输入。在使用 SDK 时,有几种方法可以表示聊天。

选项 1:输入单个字符串

如果您的聊天只有一个用户消息,您可以使用单个字符串来表示聊天。以下是使用 .respond 方法的示例。

prediction = llm.respond("What is the meaning of life?")

选项 2:使用 Chat 辅助类

对于更复杂的任务,建议使用 Chat 辅助类。它提供了各种常用的方法来管理聊天。以下是使用 Chat 类的示例,其中在初始化聊天实例时提供了初始系统提示,然后通过相应的方法调用添加了初始用户消息。

chat = Chat("You are a resident AI philosopher.")
chat.add_user_message("What is the meaning of life?")

prediction = llm.respond(chat)

您还可以使用 Chat.from_history 方法快速构造一个 Chat 对象。

chat = Chat.from_history({"messages": [
  { "role": "system", "content": "You are a resident AI philosopher." },
  { "role": "user", "content": "What is the meaning of life?" },
]})

选项 3:直接提供聊天历史数据

由于接受聊天历史记录的 API 内部使用 Chat.from_history,它们也接受常规字典形式的聊天历史数据。

prediction = llm.respond({"messages": [
  { "role": "system", "content": "You are a resident AI philosopher." },
  { "role": "user", "content": "What is the meaning of life?" },
]})

本页源代码可在 GitHub 上获取