2023年10月4日

使用Weights & Biases Weave监控OpenAI API

Weights & Biases Open In Colab

注意:你需要一个OpenAI API key才能运行这个colab。

使用W&B的OpenAI集成来监控OpenAI API调用,了解您的项目和团队如何利用LLM。 在这个示例中,我们将生成模板化的Weave Boards:LLM使用监控仪表板,您可以从UI界面探索和自定义这些仪表板。

  • 自动追踪LLM使用情况,并汇总项目/团队中的关键指标,如成本、延迟和吞吐量
  • 动态查询并从所有OpenAI API调用的日志中获取洞察
  • 通过可视化方式迭代切片、聚合和探索数据;自定义面板以聚焦有趣模式;通过交互式仪表板更轻松地与团队分享进展

体验这个Weave Board的在线版本 →

初次使用Weights & Biases?-> 点击此处注册账号 <-

步骤0:设置

安装依赖项,登录W&B以便保存和分享您的工作,并通过OpenAI进行认证。

# if not already installed
!pip install -qqq weave openai tiktoken wandb
import wandb
wandb.login()
import weave
import os
WANDB_BASE_URL = "https://api.wandb.ai"
os.environ["WANDB_BASE_URL"] = WANDB_BASE_URL
# authenticate with OpenAI
from getpass import getpass

if os.getenv("OPENAI_API_KEY") is None:
  os.environ["OPENAI_API_KEY"] = getpass("Paste your OpenAI key from: https://platform.openai.com/account/api-keys\n")
assert os.getenv("OPENAI_API_KEY", "").startswith("sk-"), "This doesn't look like a valid OpenAI API key"
print("OpenAI API key configured")
WB_ENTITY = "" # set to your wandb username or team name
WB_PROJECT = "weave" # top-level directory for this work
STREAM_NAME = "openai_logs" # record table which stores the logs of OpenAI API calls as they stream in

步骤2:调用init_monitor()

要开始监控OpenAI API使用情况,请调用init_monitor(),其中的格式为//。该数据流会记录并存储所有OpenAI API调用。

运行此单元格将打印出一个链接,用于在Weave UI中查看当前项目。

from weave.monitoring import openai, init_monitor
m = init_monitor(f"{WB_ENTITY}/{WB_PROJECT}/{STREAM_NAME}")

# specifying a single model for simplicity
OPENAI_MODEL = 'gpt-3.5-turbo'

# prefill with some sample logs
r = openai.ChatCompletion.create(model=OPENAI_MODEL, messages=[{"role": "user", "content": "hello world!"}])
r = openai.ChatCompletion.create(model=OPENAI_MODEL, messages=[{"role": "user", "content": "what is 2+2?"}])

步骤3:预览监控仪表板

点击上方链接预览数据流,然后点击右侧边栏中的"OpenAI Monitor Board"为此数据流创建Weave Board。

步骤4:探索并理解您的LLM使用情况

要保存您的工作,请点击页面顶部的自动生成名称来重命名看板。要分享您的看板,请点击右上角的"发布"按钮。

为了在迭代过程中实时可视化您的工作,您可以:

  • 将Board保持在一个单独的标签页中打开并刷新以查看最新数据
  • 重命名Board以便随时轻松引用,并"发布"该版本以与他人分享链接
  • 通过从weave.wandb.ai导航到相关的W&B实体和W&B项目名称,查找之前保存的Boards
  • 或者打开一个新的Board模板实例,从头开始使用迄今为止积累的所有数据

接下来我们将展示几种跟踪OpenAI API调用的方法。根据您的具体使用场景,还有更多可能性,我们迫不及待想看到您基于这些入门模板创造出什么。

示例

示例0:记录提示词及其补全结果

监控ChatCompletion请求并打印对应的响应,仅提取完成部分的文本内容。

response = openai.ChatCompletion.create(model=OPENAI_MODEL, messages=[
        {"role": "user", "content": f"What is the meaning of life, the universe, and everything?"},
    ])
print(response['choices'][0]['message']['content'])

示例1:将相关参数作为属性跟踪

提取出关注的参数并将其作为日志记录的属性进行跟踪。 这里我们将"系统提示"与"提示模板"和"方程"参数分开跟踪。这次我们将打印ChatCompletion调用的完整结构化响应。

system_prompt = "you always write in bullet points"
prompt_template = 'solve the following equation step by step: {equation}'
params = {'equation': '4 * (3 - 1)'}
openai.ChatCompletion.create(model=OPENAI_MODEL,
                             messages=[
                                    {"role": "system", "content": system_prompt},
                                    {"role": "user", "content": prompt_template.format(**params)},
                                ],
                             # you can add additional attributes to the logged record
                             # see the monitor_api notebook for more examples
                             monitor_attributes={
                                 'system_prompt': system_prompt,
                                 'prompt_template': prompt_template,
                                 'params': params
                             })
from weave.monitoring.openai import message_from_stream
r = openai.ChatCompletion.create(model=OPENAI_MODEL, messages=[
        {"role": "system", "content": "You are a robot and only speak in robot, like beep bloop bop."},
        {"role": "user", "content": "Tell me a 50-word story."},
    ], stream=True)
for s in message_from_stream(r):
    print(s, end='')

示例3:结构化提示工程实验

这里我们比较了几种针对系统提示、用户问题和目标受众的简单选项。尝试您自己的实验,看看在Board中探索并按不同参数分组时是否会出现有趣的见解。

def explain_math(system_prompt, prompt_template, params):
    openai.ChatCompletion.create(model=OPENAI_MODEL,
                             messages=[
                                    {"role": "system", "content": system_prompt},
                                    {"role": "user", "content": prompt_template.format(**params)},
                                ],
                             # you can add additional attributes to the logged record
                             # see the monitor_api notebook for more examples
                             monitor_attributes={
                                 'system_prompt': system_prompt,
                                 'prompt_template': prompt_template,
                                 'params': params
                             })
# feel free to substitute your own prompts :)
system_prompts = ["you're extremely flowery and poetic", "you're very direct and precise", "balance brevity with insight"]
prompt_template = 'explain the solution of the following to a {audience}: {equation}'
equations = ['x^2 + 4x + 9 = 0', '15 * (2 - 6) / 4']
audience = ["new student", "math genius"]

for system_prompt in system_prompts:
    for equation in equations:
        for person in audience:
            params = {"equation" : equation, "audience" : person}
            explain_math(system_prompt, prompt_template, params)