Reference Messages
messages.parse[A]
Asks for a reply shaped like A and decodes it (structured outputs).
Reference#
parse[A](request, options?)#
def parse[A](request: MessageRequest, options: RequestOptions)(implicit
schema: Schema[A],
F: MonadThrow[F]
): F[Parsed[A]]
def parse[A](request: MessageRequest)(implicit schema: Schema[A], F: MonadThrow[F]): F[Parsed[A]]
Parameters
A: the type of the reply. Needs aSchema[A]; case classes and sealed traits get one automatically.request: aMessageRequest. The JSON Schema ofAis added as its response format.options: optionalRequestOptionsfor this call.
Returns
final case class Parsed[A] private[anthropic4s] (value: A, message: Message)
The decoded value, with the message it came from (usage, stop reason, id).
Caveats
- Fails with
OutputParsewhen the model refuses, runs out of tokens or returns something that does not decode. The error carries the reply. - Fails with
InvalidSchema, before sending anything, whenAhas no strict schema (a recursive type or aMap, for example).
Usage#
A typed reply#
final case class Invoice(@description("ISO 4217 code") currency: String, total: BigDecimal)
client.messages.parse[Invoice](request).map(_.value.total)
import anthropic4s.schema.description
sealed trait Difficulty
object Difficulty { case object Easy extends Difficulty; case object Hard extends Difficulty }
final case class Recipe(
name: String,
@description("Total time in minutes") minutes: Int,
difficulty: Difficulty,
pairing: Option[String]
)
client.messages.parse[Recipe](request).map(_.value) // IO[Recipe]
Structured outputs explains the schema rules.
Every signature and example on this page is copied, character for character, from the public source of anthropic4s and its Scaladoc. The complete API, every type included, is in the Scaladoc of each module.