anthropic4s
GitHub

Docs Learn

Structured outputs

Ask for a case class and get one back. The JSON Schema is derived from the type and sent as the response format, so the API guarantees a reply that fits.

You will learn

  • How to get a typed value from client.messages.parse
  • How @description tells the model what a field means
  • When to cache a Schema instance
  • How to handle a reply that does not decode
  • How to drive it from your Play JSON Formats instead

From a case class#

Describe the answer you want as ordinary Scala types. Sealed traits of case objects become a choice of strings; Option fields may be left empty. Then call parse instead of create:

README.md · Structured outputs
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]

One derivation yields the schema, the decoder and the encoder, so they cannot disagree. No instance to declare: case classes and sealed traits get a Schema automatically.

Deep dive Caching the derived schema

The schema is derived at every use unless you cache it. To derive it once, put an instance in the companion: object Recipe { implicit val schema: Schema[Recipe] = Schema.derived }.

A complete program#

The StructuredOutput example nests a list of case classes inside the reply and recovers from a reply that cannot be decoded, which arrives as AnthropicError.OutputParse:

examples/…/Basics.scala · StructuredOutput
sealed trait Difficulty
object Difficulty {
  case object Easy   extends Difficulty
  case object Medium extends Difficulty
  case object Hard   extends Difficulty
}
final case class Ingredient(name: String, @description("Amount with its unit, e.g. '200 g'") quantity: String)
final case class Recipe(
    name: String,
    @description("Total time in minutes, preparation included") minutes: Int,
    difficulty: Difficulty,
    ingredients: List[Ingredient],
    @description("A wine that goes with it, if any") pairing: Option[String]
)

/** Structured output: the reply arrives as a `Recipe`, not as text to parse. No JSON in sight. */
object StructuredOutput extends IOApp.Simple {

  def run: IO[Unit] =
    Anthropic4s.fromEnv[IO].use { client =>
      val request = MessageRequest(
        Model.ClaudeOpus5_5,
        maxTokens = 16000,
        MessageParam.user("A weeknight vegetarian pasta, please.")
      )

      client.messages
        .parse[Recipe](request)
        .flatMap { parsed =>
          val recipe = parsed.value
          IO.println(s"${recipe.name}: ${recipe.minutes} min, ${recipe.difficulty}") *>
            recipe.ingredients.traverse_(i => IO.println(s"  - ${i.quantity} ${i.name}"))
        }
        .recoverWith { case e: AnthropicError.OutputParse => IO.println(s"No recipe today: ${e.detail}") }
    }
}

With Play JSON#

If your types already have Play JSON Formats, add anthropic4s-play-json and pair the schema with your Format:

README.md · With Play JSON
object Recipe {
  implicit val config: JsonConfiguration = PlaySchema.configuration
  implicit val format: OFormat[Recipe]   = Json.format[Recipe]
  implicit val schema: Schema[Recipe]    = PlaySchema.derived[Recipe]
}

Recap

  • client.messages.parse[A](request).map(_.value) gives you an A.
  • @description on a field is sent to the model as part of the schema.
  • A reply that does not decode fails with AnthropicError.OutputParse.
  • With Play JSON, use PlaySchema.configuration and PlaySchema.derived.

Every snippet on this page is copied, character for character, from the anthropic4s repository: its README, docs/play.md or examples/, which compiles with the build.