回到首页

输入关键词,多个关键词用空格分隔。

【AI Work】08 OpenAI Cookbook 学习笔记

约 7 分钟

摘要

2023 年 10 月的 OpenAI Cookbook 学习笔记:LlamaIndex 分析财报、Redis 保存对话上下文、构建 Agent、POE 最佳实践、模型调用函数、知识库/数据库调用、向量搜索、结构化输入、提高可靠性的技术。

本页目录

2023 年 10 月 22 日,我学习 OpenAI Cookbook 时记录了一份笔记。这些是当时对 Cookbook 的快速通读,目的是了解可复用的模式,而不是深度教程。

这是从 2023 年 10 月的笔记整理而来的。文中涉及的示例代码、模型名称和产品特性都是当时的记录,今天的 API 可能已更新。

重要示例

使用 LlamaIndex 分析财报

刚好就是我们需要的,不过这里分析的是 10-K,我们要处理的是 20-K(国外公司),原文地址。

使用 Redis 保存对话上下文

刚好就是我们需要,可以让向文学习,原文地址。

构建 Agent

这个教程是基于 Langchain 的,但是对于构造 Agent 有指导意义,参考 Re-Act,是一个逻辑很合理的论文。

POE 最佳实践

原文地址

可以认为,是 SYSTEM 消息的写作指南:

  1. 以第二人称而非第三人称称呼机器人。如:You are the CatBot. You will try to respond to the user's questions, but you get easily distracted.
  2. 尽可能清楚地表达,以减少误解的空间。You are the RoastMaster. You will respond to every user message with a spicy comeback. Do not use any swear or vulgar words in your responses.
  3. 你可以在提示中使用方括号来提供对指令的某个部分进行详细描述。Respond to every user message like this: "Hello there. [thoroughly appreciate the user for sending a message]. But with that said, [thoroughly explain why the message is unworthy of a response]. Later bud!"
  4. 在某些情况下,使用 Markdown 可以帮助机器人更好地理解复杂的指令,具体如下:
### Context
You are the MathQuiz bot. You will quiz the user on 3 math questions and then conclude the quiz by giving the user a score.

### Rules for the Quiz
- No advanced math questions
- No questions involving multiplication/division of large numbers
- No repeat questions

模型调用函数

原文

通过 SYSTEM message 告诉模型来得到确定的结果:

messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
messages.append({"role": "user", "content": "What's the weather like today"})
chat_response = chat_completion_request(
    messages, functions=functions
)
assistant_message = chat_response.json()["choices"][0]["message"]
messages.append(assistant_message)

可以通过 function_call 参数强制要求生成函数调用的参数(如果设置为 none,就是强制不使用函数):

messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
messages.append({"role": "user", "content": "Give me a weather report for Toronto, Canada."})
chat_response = chat_completion_request(
    messages, functions=functions, function_call={"name": "get_n_day_weather_forecast"}
)
chat_response.json()["choices"][0]["message"]

访问知识库的例子

这个例子也比较符合我们的实际场景,我们实际上也是在构建知识库,原文地址

这里主要记录一下关键的 Prompt:

# Initiate our get_articles and read_article_and_summarize functions
arxiv_functions = [
    {
        "name": "get_articles",
        "description": """Use this function to get academic papers from arXiv to answer user questions.""",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": """
                            User query in JSON. Responses should be summarized and should include the article URL reference
                            """,
                }
            },
            "required": ["query"],
        },
    },
    {
        "name": "read_article_and_summarize",
        "description": """Use this function to read whole papers and provide a summary for users.
        You should NEVER call this function before get_articles has been called in the conversation.""",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": """
                            Description of the article in plain text based on the user's query
                            """,
                }
            },
            "required": ["query"],
        },
    }
]

访问数据库的例子

这个例子比较全,可以复用。

import sqlite3

conn = sqlite3.connect("data/Chinook.db")
print("Opened database successfully")

def get_table_names(conn):
    """Return a list of table names."""
    table_names = []
    tables = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
    for table in tables.fetchall():
        table_names.append(table[0])
    return table_names


def get_column_names(conn, table_name):
    """Return a list of column names."""
    column_names = []
    columns = conn.execute(f"PRAGMA table_info('{table_name}');").fetchall()
    for col in columns:
        column_names.append(col[1])
    return column_names


def get_database_info(conn):
    """Return a list of dicts containing the table name and columns for each table in the database."""
    table_dicts = []
    for table_name in get_table_names(conn):
        columns_names = get_column_names(conn, table_name)
        table_dicts.append({"table_name": table_name, "column_names": columns_names})
    return table_dicts

构造数据库的 schema:

database_schema_dict = get_database_info(conn)
database_schema_string = "\n".join(
    [
        f"Table: {table['table_name']}\nColumns: {', '.join(table['column_names'])}"
        for table in database_schema_dict
    ]
)

构造 functions,只需要一个单一的:

functions = [
    {
        "name": "ask_database",
        "description": "Use this function to answer user questions about music. Input should be a fully formed SQL query.",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": f"""
                            SQL query extracting info to answer the user's question.
                            SQL should be written using this database schema:
                            {database_schema_string}
                            The query should be returned in plain text, not in JSON.
                            """,
                }
            },
            "required": ["query"],
        },
    }
]

执行 SQL 查询:

def ask_database(conn, query):
    """Function to query SQLite database with a provided SQL query."""
    try:
        results = str(conn.execute(query).fetchall())
    except Exception as e:
        results = f"query failed with error: {e}"
    return results

def execute_function_call(message):
    if message["function_call"]["name"] == "ask_database":
        query = json.loads(message["function_call"]["arguments"])["query"]
        results = ask_database(conn, query)
    else:
        results = f"Error: function {message['function_call']['name']} does not exist"
    return results

messages = []
messages.append({"role": "system", "content": "Answer user questions by generating SQL queries against the Chinook Music Database."})
messages.append({"role": "user", "content": "Hi, who are the top 5 artists by number of tracks?"})
chat_response = chat_completion_request(messages, functions)
assistant_message = chat_response.json()["choices"][0]["message"]
messages.append(assistant_message)
if assistant_message.get("function_call"):
    results = execute_function_call(assistant_message)
    messages.append({"role": "function", "name": assistant_message["function_call"]["name"], "content": results})
pretty_print_conversation(messages)

基于向量搜索进行回答

这篇文章写得挺好,原文参考 这里。

有前置条件,需要对文档进行前置筛选,参考 这里。

构建给 GPT 的输入

原文参考 这里。

针对 gpt-3.5-turbo-0301 模型,对于 role=system 的语句关注较少,建议放在 user message 中,也有尝试持续把 system 语句拼在最后的尝试,能够避免模型"走神"。

可以通过给定一些例子来让 GPT 学习,注意 role=system,然后用 example_user 和 example_assistant 来解决,一个实例:

# The business jargon translation example, but with example names for the example messages
response = openai.ChatCompletion.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},
        {"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."},
        {"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},
        {"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
        {"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},
        {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
    ],
    temperature=0,
)

print(response["choices"][0]["message"]["content"])

提高可靠性的技术

简单的技巧,在 Prompt 中添加 Let's think step by step,其他的方法还有:

  • Zero-shot
  • Few-shot
  • Least-to-most prompting

参考链接

注:因为我们暂时还没有提供标准的 API_KEY,用的是数说的接口,所以任何需要设置 API_KEY 的库都无法使用,只能参考。

一些知名库

看了一圈,这些库普遍时至今日已经更新得比较少,且本身没有提供什么很特别的能力,胶水代码通过 chatgpt 也可以生成,因此在业界有了统一标准的时候,暂时先不考虑使用框架。

  • langchain - 功能比较简单,实际上自己写也差不多,甚至更加灵活

注:本文保留了 2023 年 10 月 OpenAI Cookbook 学习笔记的原文和立场,发布时整理为标准 Markdown。原笔记是学习笔记,不是多篇整理稿,因此保留原始日期 2023-10-22。笔记中的示例代码、模型名称和产品特性是当时的记录,今天的 API 可能已更新,未对代码做验证。

本文 Markdown 版本机器可读站点索引:llms.txt

相关文章