跳转至

OpenAI的

介绍

Logfire 支持使用一行额外的代码来检测对 OpenAI 的调用。

import openai
import logfire

client = openai.Client()

logfire.configure()
logfire.instrument_openai(client)  # (1)!

response = client.chat.completions.create(
    model='gpt-4',
    messages=[
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': 'Please write me a limerick about Python logging.'},
    ],
)
print(response.choices[0].message)
  1. 如果您无法访问客户端实例,则可以传递一个类(例如 logfire.instrument_openai(openai.Client)),或者不传递任何参数(即 logfire.instrument_openai()) 来检测 openai。客户端openai。AsyncClient 类。


更多信息,请参见【instrument_openai() API参考】[logfire。Logfire.instrument_openai]。

有了它,您可以获得:

  • 围绕对 OpenAI 的调用的跨度,该调用记录持续时间并捕获可能发生的任何异常

  • 与座席的对话的人类可读显示

  • 响应的详细信息,包括使用的令牌数

Logfire OpenAI
OpenAI span and conversation
Logfire OpenAI Arguments
Span arguments including response details

涵盖的方法

涵盖以下 OpenAI 方法:

所有方法都包含在 openai 中。客户端openai。AsyncClient

例如,下面是图像生成调用的检测:

import openai
import logfire

async def main():
    client = openai.AsyncClient()
    logfire.configure()
    logfire.instrument_openai(client)

    response = await client.images.generate(
        prompt='Image of R2D2 running through a desert in the style of cyberpunk.',
        model='dall-e-3',
    )
    url = response.data[0].url
    import webbrowser
    webbrowser.open(url)

if __name__ == '__main__':
    import asyncio
    asyncio.run(main())

给:

Logfire OpenAI Image Generation
OpenAI image generation span

OpenAI 图像生成跨度

流式响应

在检测流式响应时,Logfire 会创建两个跨度 — 一个围绕初始请求,另一个围绕流式响应。

在这里,我们还使用 Rich 的 LiveMarkdown 类型在终端中实时渲染响应。:舞蹈家:

import openai
import logfire
from rich.console import Console
from rich.live import Live
from rich.markdown import Markdown

client = openai.AsyncClient()
logfire.configure()
logfire.instrument_openai(client)

async def main():
    console = Console()
    with logfire.span('Asking OpenAI to write some code'):
        response = await client.chat.completions.create(
            model='gpt-4',
            messages=[
                {'role': 'system', 'content': 'Reply in markdown one.'},
                {'role': 'user', 'content': 'Write Python to show a tree of files 🤞.'},
            ],
            stream=True
        )
        content = ''
        with Live('', refresh_per_second=15, console=console) as live:
            async for chunk in response:
                if chunk.choices[0].delta.content is not None:
                    content += chunk.choices[0].delta.content
                    live.update(Markdown(content))

if __name__ == '__main__':
    import asyncio
    asyncio.run(main())

在 Logfire 中如下所示:

Logfire OpenAI Streaming
OpenAI streaming response

本文总阅读量