跳转至

人类学

介绍

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

import anthropic
import logfire

client = anthropic.Anthropic()

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

response = client.messages.create(
    max_tokens=1000,
    model='claude-3-haiku-20240307',
    system='You are a helpful assistant.',
    messages=[{'role': 'user', 'content': 'Please write me a limerick about Python logging.'}],
)
print(response.content[0].text)
  1. 如果您无权访问客户端实例,则可以传递一个类(例如 logfire.instrument_anthropic(anthropic.Anthropic)),或者干脆不传递任何参数(即 logfire.instrument_anthropic()) 来检测两者。人类学人类学。AsyncAnthropic 类。


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

有了它,您可以获得:

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

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

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

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

涵盖的方法

涵盖了以下人为学方法:

所有方法都涵盖了人为的方法。人类学人类学。异步人。

流式响应

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

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

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

client = anthropic.AsyncAnthropic()
logfire.configure()
logfire.instrument_anthropic(client)


async def main():
    console = Console()
    with logfire.span('Asking Anthropic to write some code'):
        response = client.messages.stream(
            max_tokens=1000,
            model='claude-3-haiku-20240307',
            system='Reply in markdown one.',
            messages=[{'role': 'user', 'content': 'Write Python to show a tree of files 🤞.'}],
        )
        content = ''
        with Live('', refresh_per_second=15, console=console) as live:
            async with response as stream:
                async for chunk in stream:
                    if chunk.type == 'content_block_delta':
                        content += chunk.delta.text
                        live.update(Markdown(content))


if __name__ == '__main__':
    import asyncio

    asyncio.run(main())

在 Logfire 中如下所示:

Logfire Anthropic Streaming
Anthropic streaming response

本文总阅读量