org.llm4s.schema

Members list

Packages

Type members

Classlikes

@Experimental
object PartialJson

A tolerant parser for the JSON a model has written so far: given a prefix of a JSON document, it closes the open strings, arrays and objects and returns the value the prefix describes.

A tolerant parser for the JSON a model has written so far: given a prefix of a JSON document, it closes the open strings, arrays and objects and returns the value the prefix describes.

What the prefix does not finish is left out rather than guessed:

  • a property whose value has not started, or whose key is still being written, is absent;
  • a number is surfaced only once a character after it shows that it is complete, so 12.5 never shows as 1;
  • true, false and null are surfaced only once complete;
  • a string still being written is surfaced as its prefix (without an escape that has not finished), or left out with partialStrings = false.

So the value for a prefix is always a prefix of the value for the whole document: every property it has, the whole document has with the same or a longer value. Text after the first value, or after JSON that is not valid, is ignored: the value is what came before it. Nesting deeper than 512 levels is cut there, as BoundedJson refuses it. The parser never throws.

client.streamStructuredOf[A] uses it to turn a streamed reply into typed partial values.

Attributes

Source
PartialJson.scala
Supertypes
class Object
trait Matchable
class Any
Self type
@Experimental
sealed trait PartialOf[A]

The type of a partly written A, and how to read one from the JSON a model has streamed so far: what client.streamStructuredOf[A] hands its callback.

The type of a partly written A, and how to read one from the JSON a model has streamed so far: what client.streamStructuredOf[A] hands its callback.

For a case class A, Out is a named tuple with A's field names, each an Option of the field's partial value, None until the field has started to arrive:

case class LineItem(sku: String, quantity: Int)
case class Invoice(vendor: String, items: List[LineItem], status: Status)

// the Out of PartialOf[Invoice] is
// (vendor: Option[String], items: Option[List[(sku: Option[String], quantity: Option[Int])]], status: Option[Status])

A field's partial value follows its type:

  • String: the text so far;
  • a case class with fields: its own partial named tuple, recursively;
  • List, Vector and Seq: the elements so far, the last one partial when its type has partial values;
  • Option[T]: Some(None) once the model has written null, else T's partial value in a Some;
  • anything else (numbers, Boolean, enums, sum types, Set, BigDecimal): the value, only once complete, read with its uPickle Reader. A number is never shown while more digits may follow.

An instance is derived for any case class with fields (no derives clause), from the same field names, and the same @upickle.implicits.keys, that its SchemaOf and uPickle use. The type is computed at compile time rather than as a match type, since a match type cannot tell a case class from an enum or a sealed trait. To name it in a signature, take it from the instance: val invoices = summon[PartialOf[Invoice]] and def show(p: invoices.Out).

Type parameters

A

the case class being streamed

Attributes

Companion
object
Source
PartialOf.scala
Supertypes
class Object
trait Matchable
class Any
@Experimental
object PartialOf

Attributes

Companion
trait
Source
PartialOf.scala
Supertypes
class Object
trait Matchable
class Any
Self type
PartialOf.type
@Experimental
trait SchemaOf[A]

The JSON schema of A, derived from the type itself so that it cannot drift from it.

The JSON schema of A, derived from the type itself so that it cannot drift from it.

case class Invoice(vendor: String, amount: Double, lines: List[String], note: Option[String]) derives SchemaOf

SchemaOf[Invoice].toJsonSchema()    // the schema `completeStructured` sends

The schema describes what uPickle's derived ReadWriter reads and writes (field names, Option as the value or null, an enum as its case name, a BigDecimal as a string), so a reply that matches the schema reads back into A. The module's tests check that round trip for every supported shape.

Supported: String, Int, Long, Double, Float, Boolean, BigDecimal, BigInt; Option; List, Seq, Vector and Set of a supported type; case classes whose fields are supported; enums and sealed hierarchies of singletons (as a string with the case names, or a case's @upickle.implicits.key); and sum types, enums and sealed traits whose cases have fields (as a JSON Schema anyOf of one object per case, each with the discriminator uPickle writes: "$type", or the trait's @upickle.implicits.key, holding the case's tag); and named tuples, (city: String, days: Int), as an object with one property per element (see SchemaOf.namedTuple). Not supported, and refused at compile time with a message naming the type: Map (core's ObjectSchema has a fixed set of properties and cannot describe map values), recursive types (they need a JSON Schema $ref), a sealed hierarchy nested in another or with a generic case, and Option directly inside Option and tuples without names (uPickle writes both as JSON arrays). Other types need a given SchemaOf of their own: see SchemaOf.string and SchemaOf.stringEnum. A hand-written given is used as it is, so it can also describe a type the derivation would refuse.

A recursion that runs through hand-written givens which themselves call SchemaOf.derived (for mutually recursive P and Q, given SchemaOf[P] = SchemaOf.derived[P] and given SchemaOf[Q] = SchemaOf.derived[Q]) cannot be seen at compile time, because the check does not look inside a hand-written given. Building that schema (schema, definition, toJsonSchema) throws an IllegalStateException naming the recursive type instead, on first use; it never hangs.

A generic case class may be nested in itself at most 16 deep: W[W[...[Int]]] with 16 Ws is described, with 17 it is taken for a recursion. Spelled out in a field's type, the deeper nesting is refused at compile time; reached through the generic derives SchemaOf instance (SchemaOf[W[...[Int]]]) it is refused when the schema is built, with the same IllegalStateException.

A sum type with fields, and a type that holds one, has no schema in core's model, which has no union: its toJsonSchema is the JSON Schema, while schema and definition throw an UnsupportedOperationException saying so. completeStructuredOf sends such a schema as it is, and a tool refuses it.

Type parameters

A

the described type

Attributes

Companion
object
Source
SchemaOf.scala
Supertypes
class Object
trait Matchable
class Any
@Experimental
object SchemaOf

Attributes

Companion
trait
Source
SchemaOf.scala
Supertypes
class Object
trait Matchable
class Any
Self type
SchemaOf.type
@Experimental
object Tool

Tools defined from a function over a case class: the parameter schema is derived from the argument type (SchemaOf), the arguments are decoded into it, and the result is written with its uPickle writer, so the schema the model sees, the argument parsing and the function cannot drift apart.

Tools defined from a function over a case class: the parameter schema is derived from the argument type (SchemaOf), the arguments are decoded into it, and the result is written with its uPickle writer, so the schema the model sees, the argument parsing and the function cannot drift apart.

@description("Where to look up the weather")
case class WeatherArgs(@description("City name") city: String, @description("Days ahead") days: Int)
 derives SchemaOf, ReadWriter

val weather: Result[ToolFunction[WeatherArgs, Forecast]] =
 Tool.of[WeatherArgs, Forecast]("get_weather", "Gets a forecast")(args => forecast(args.city, args.days))

The result is the ToolFunction that ToolBuilder builds, registered in a ToolRegistry like any other.

Attributes

Source
Tool.scala
Supertypes
class Object
trait Matchable
class Any
Self type
Tool.type
@Experimental
final class ToolScope

The call a Tool.scoped handler is serving, given to the handler and nowhere else: reject, ensure, ?, ToolScope.call and ToolScope.idempotencyKey need one, so using them outside a scoped handler does not compile.

The call a Tool.scoped handler is serving, given to the handler and nowhere else: reject, ensure, ?, ToolScope.call and ToolScope.idempotencyKey need one, so using them outside a scoped handler does not compile.

reject ends the call with scala.util.boundary's break, which is an exception the handler's own Try or catch NonFatal would catch: do not wrap a call to reject, ensure or ? in either. Nor keep the scope after the handler returns, or use it on another thread: the call has then ended, and there is nothing to end.

Attributes

Companion
object
Source
ToolScope.scala
Supertypes
class Object
trait Matchable
class Any
@Experimental
object ToolScope

Attributes

Companion
class
Source
ToolScope.scala
Supertypes
class Object
trait Matchable
class Any
Self type
ToolScope.type
@Experimental
object Tools

Tools derived from a whole service: one per public method of a trait or class.

Tools derived from a whole service: one per public method of a trait or class.

trait CustomerService:
 /** Orders placed by a customer, newest first.
   * @param customerId the customer's id, for example C-1001
   */
 def findOrders(customerId: String): Result[List[Order]]

val tools: Result[Seq[ToolFunction[?, ?]]] = Tools.derive[CustomerService](liveService)

Attributes

Source
Tools.scala
Supertypes
class Object
trait Matchable
class Any
Self type
Tools.type
@Experimental
final class description(val text: String) extends StaticAnnotation

The description the model sees for a derived schema: on a case class parameter it describes the field, on a case class, enum or sealed trait it describes the type.

The description the model sees for a derived schema: on a case class parameter it describes the field, on a case class, enum or sealed trait it describes the type.

The text must be a string literal (@description("Total amount")), because the annotation is read at compile time and a macro cannot evaluate an expression. Without it, a field is described by its name and a type by its name.

@description("An invoice extracted from text")
case class Invoice(
 @description("Name of the vendor or supplier") vendor: String,
 amount: Double
) derives SchemaOf

Attributes

Source
description.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
@Experimental
object namedtuples

A uPickle ReadWriter for named tuples, which uPickle does not provide, so that a named tuple can be a structured output or a tool's arguments and result with no case class to declare:

A uPickle ReadWriter for named tuples, which uPickle does not provide, so that a named tuple can be a structured output or a tool's arguments and result with no case class to declare:

import org.llm4s.schema.*
import org.llm4s.schema.namedtuples.given

val review = client.completeStructuredOf[(sentiment: Sentiment, confidence: Double)](conversation)
review.map(_.sentiment)

A named tuple is written as uPickle writes a case class with the same fields and no default values: a JSON object keyed by the names, in order, with null for a None. It is read the same way, except that an absent Option element reads as None (a case class needs a default for that); any other absent element is an error naming it, and keys the tuple has no element for are ignored. Each element needs a ReadWriter of its own.

It is imported explicitly, never found on its own, so that it cannot compete with an instance uPickle may add later.

Attributes

Source
namedtuples.scala
Supertypes
class Object
trait Matchable
class Any
Self type
@Experimental
final class notATool extends StaticAnnotation

Leaves a public method out of the tools Tools.derive makes from its trait or class: a helper the model should not call, or a method whose parameters no tool could take.

Leaves a public method out of the tools Tools.derive makes from its trait or class: a helper the model should not call, or a method whose parameters no tool could take.

trait Orders:
 def findOrders(customerId: String): List[Order]
 @notATool
 def connection: java.sql.Connection

Attributes

Source
notATool.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
@Experimental
final class toolName(val name: String) extends StaticAnnotation

The name the model calls a tool derived from a method by (Tool.fromMethod or Tools.derive), instead of the method's name in snake_case.

The name the model calls a tool derived from a method by (Tool.fromMethod or Tools.derive), instead of the method's name in snake_case.

The name must be a string literal of 1 to 64 letters, digits, _ or - (what every provider accepts), because it is read and checked at compile time.

trait Orders:
 @toolName("orders_search")
 def findOrders(customerId: String): List[Order]

Attributes

Source
toolName.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any

Value members

Concrete methods

def ensure(condition: Boolean, message: => String)(using ToolScope): Unit

Ends the Tool.scoped call being served with message as its error unless condition holds.

Ends the Tool.scoped call being served with message as its error unless condition holds.

Attributes

Source
ToolScope.scala
def reject(message: String)(using scope: ToolScope): Nothing

Ends the Tool.scoped call being served: message is the tool's error, which the model sees, and the rest of the handler does not run.

Ends the Tool.scoped call being served: message is the tool's error, which the model sees, and the rest of the handler does not run.

Attributes

Source
ToolScope.scala

Extensions

Extensions

extension (client: LLMClient)
def completeStructuredOf[A](conversation: Conversation, options: CompletionOptions)(using schemaOf: SchemaOf[A], reader: Reader[A]): Result[A]

org.llm4s.llmconnect.LLMClient.completeStructured with the schema derived from A instead of written by hand: client.completeStructuredOf[Invoice](conversation).

org.llm4s.llmconnect.LLMClient.completeStructured with the schema derived from A instead of written by hand: client.completeStructuredOf[Invoice](conversation).

A is a case class (the model answers with a JSON object) or a sum type: an enum or sealed trait whose cases have fields, which SchemaOf describes as a JSON Schema anyOf. A case class whose schema core's model can express is sent and read exactly as completeStructured sends and reads it. One that holds a sum type is sent as its JSON Schema in a ResponseFormat.JsonSchema. A sum type itself is wrapped, since OpenAI's strict mode refuses an anyOf at the root: the model is asked for {"value": <the sum>}, and the reply's value is read into A.

Any other derived type, such as an enum of singletons, is refused with a Left, since the reply must be a JSON object. So is a schema that cannot be built, such as a recursion through a hand-written given that derives its type, which SchemaOf.toJsonSchema throws for: the model is not called.

Type parameters

A

the type to extract; needs a SchemaOf (derives SchemaOf) and a uPickle reader

Value parameters

conversation

the conversation to send

options

completion options, as for completeStructured

Attributes

Source
StructuredOutput.scala
def streamStructuredOf[A](conversation: Conversation, options: CompletionOptions)(using schemaOf: SchemaOf[A], reader: Reader[A], partial: PartialOf[A])(onPartial: partial.Out => Unit): Result[A]

completeStructuredOf, streamed: onPartial sees the value take shape while the model writes it, and the result is the finished value.

completeStructuredOf, streamed: onPartial sees the value take shape while the model writes it, and the result is the finished value.

The request is the one completeStructuredOf sends (the same response format, through streamComplete), and the result is the reply read exactly as completeStructuredOf reads it, with the same errors. As text arrives, it is parsed with PartialJson and read into A's partial type (PartialOf): a named tuple with A's field names, each None until it starts to arrive. onPartial is called, on the thread that streams, each time that value changes, and each value it sees extends the one before: a string grows, a list gains elements, a field once present stays present. A number, an enum or any other value with no partial form is shown only once complete. Thinking deltas are not parsed, and nor is text before the first { (a fence or a preamble).

client.streamStructuredOf[Invoice](conversation) { p =>
 p.vendor.foreach(ui.setTitle)                  // p.vendor: Option[String]
 ui.setRows(p.items.getOrElse(Nil).size)        // p.items: Option[List[(sku: Option[String], ...)]]
}

The whole reply is parsed again on each chunk, so the cost grows with the square of its length: fine for the replies structured output is used for, slow for one of many megabytes.

Type parameters

A

the case class to extract; needs a SchemaOf and a uPickle reader, and, for each field type with no partial form, a uPickle reader of that type

Value parameters

conversation

the conversation to send

onPartial

called with each new partial value; an exception it throws is the stream's

options

completion options, as for completeStructuredOf

Attributes

Source
StructuredOutput.scala
extension [T](either: Either[String, T])
def ?(using ToolScope): T

The value of a Right; a Left ends the Tool.scoped call being served with its message as the tool's error.

The value of a Right; a Left ends the Tool.scoped call being served with its message as the tool's error.

Attributes

Source
ToolScope.scala
extension [T](result: Result[T])
def ?(using ToolScope): T

The value of a Right; a Left ends the Tool.scoped call being served with the error's formatted message (LLMError.formatted) as the tool's error.

The value of a Right; a Left ends the Tool.scoped call being served with the error's formatted message (LLMError.formatted) as the tool's error.

Attributes

Source
ToolScope.scala