使用聊天
用于表示与 LLM 聊天对话的 API
SDK 方法如 llm.respond()、llm.applyPromptTemplate() 或 llm.act() 均接受一个 chat 参数作为输入。使用该 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?" },
]})