Struct Inference

The simplest demonstration of Turn's Cognitive Type Safety. Define a struct, then use infer to have the LLM populate it from a natural language prompt.

Turn compiles the struct definition into a JSON Schema at build time and sends it to the LLM as a hard constraint. The model must return valid JSON matching the schema. If it does not, the VM retries automatically before your code ever sees the result. You always receive a correctly typed value, or the infer call throws a catchable error after exhausting retries.

There is no json.loads(), no KeyError at runtime, no defensive casting. The type contract between your program and the model is enforced at the language level.

struct_infer.tn
// Turn Language: Struct Inference
// Demonstrates Cognitive Type Safety: the LLM is constrained to return
// a value matching the Sentiment schema. Turn validates before binding.

struct Sentiment {
  score: Num,
  reasoning: Str
};

call("echo", "Analyzing sentiment...");

let result = infer Sentiment {
  "I love this new language. Building agents finally feels natural.";
};

// Type-safe field access. No casting, no null checks.
call("echo", "Score:     " + result.score);
call("echo", "Reasoning: " + result.reasoning);

if result.score > 0.8 {
  call("echo", "Verdict: POSITIVE");
} else {
  call("echo", "Verdict: NEUTRAL / NEGATIVE");
}

return result;

How It Works

When the VM reaches infer Sentiment { ... }, it:

  1. Generates a JSON Schema from the Sentiment struct definition
  2. Passes your prompt together with the schema to the configured inference provider
  3. Validates the model's response against the schema before binding it to result
  4. If validation fails, retries up to three times before throwing

The struct fields are then accessible as typed values. result.score is a Num. result.reasoning is a Str. No runtime parsing required.

The confidence operator is available on any infer result and gives you the model's certainty score as a Num between 0 and 1:

with_confidence.tn
let result = infer Sentiment {
  "Evaluate this product review.";
};

if confidence result < 0.80 {
  call("echo", "Low confidence. Skipping automated action.");
  return null;
}

call("echo", "Score: " + result.score);

Running It

export TURN_LLM_PROVIDER=openai
export OPENAI_API_KEY=sk-...
turn run impl/examples/struct_infer.tn

The full source is in impl/examples/struct_infer.tn.


Next Steps