mochi-neko / clust

An unofficial Rust client for the Anthropic/Claude API.
Apache License 2.0
22 stars 11 forks source link

Add example for extracting text from MesagesResponseBody #1

Closed mikecvet closed 7 months ago

mikecvet commented 7 months ago

Adds some code to the create_a_message example to demonstrate how to extract the actual response text from the MessagesResponseBody and its Content::MultipleBlock content field.

I was also thinking that it might be nice to have a simple text extractor function within MessagesResponseBody which returns something like a Result<String, Err> like body.content.text, which returns the text from either the SingleText or first MultipleBlock if it exists (and the number of ContentBlocks is 1).

What do you think?

  ~/code/m-clust ~>> git branch
    main
  * textblock_example
  ~/code/m-clust ~>> cargo run --example create_a_message -- -p hello -m hello
      Finished dev [unoptimized + debuginfo] target(s) in 0.24s
       Running `target/debug/examples/create_a_message -p hello -m hello`
  Entire result:
  {
    "id": "msg_013vikkX9jdN9sHnhphbQ7ZY",
    "type": "message",
    "role": "assistant",
    "content": [
      {
        "type": "text",
        "text": "Hello! How can I assist you today?"
      }
    ],
    "model": "claude-3-haiku-20240307",
    "stop_reason": "end_turn",
    "stop_sequence": null,
    "usage": {
      "input_tokens": 9,
      "output_tokens": 12
    }
  }
  Multi-block response text: Hello! How can I assist you today?
mochi-neko commented 7 months ago

@mikecvet

Thank you for your pull request.

I was also thinking that it might be nice to have a simple text extractor function within MessagesResponseBody which returns something like a Result<String, Err> like body.content.text, which returns the text from either the SingleText or first MultipleBlock if it exists (and the number of ContentBlocks is 1).

That is a good idea!

I implemented clust::messages::Content::flatten_into_text() along with your idea:

https://github.com/mochi-neko/clust/blob/4500a91e92240fd1e707c1279ed39171599d454d/src/messages/content.rs#L88

and add code for examples:

https://github.com/mochi-neko/clust/blob/4500a91e92240fd1e707c1279ed39171599d454d/examples/create_a_message.rs#L66

on the latest main branch.

If there seem to be no issues, I'm going to release it in v0.6.0.

mikecvet commented 7 months ago

That is a good idea!

I implemented clust::messages::Content::flatten_into_text() along with your idea

This looks great. Thanks!

mochi-neko commented 7 months ago

Thank you, too!