Instructor

repository·main·Indexed 11 days ago

https://github.com/567-labs/instructor

A library for obtaining reliable, structured JSON from any LLM using Pydantic for schema definition, validation, and type safety. Version 1.16.0 supports in-memory and persistent caching via AutoCache and DiskCache, a CLI for managing batch jobs, and integration with providers like OpenAI, Anthropic, and Google.

Tokens
351.4K
Snippets
886
Records
1.1K
Agent score
93%

What's inside Instructor

  1. Supported LLM providers

    main

    Instructor supports a wide range of providers, including:

    • OpenAI (GPT models)
    • Anthropic (Claude models)
    • Google (Gemini models)
    • Cohere
    • Mistral AI
    • Groq
    • LiteLLM (meta-provider)
    • TrueFoundry AI Gateway
    • Open-source models via Ollama, llama.cpp, etc.
  2. Manage OpenAI fine-tuning jobs with the Instructor CLI

    main

    The Instructor CLI allows you to manage fine-tuning jobs on OpenAI directly from your terminal. You can use it to create new fine-tuning jobs, view existing jobs, and manage files.

    Note: The CLI is currently under development and does not support all OpenAI API features. If a specific feature is missing, you may need to use the Python library directly.

  3. Core concepts in Instructor

    main

    Instructor's functionality is organized into several key domains:

    Core API & Setup

    • Models: Using Pydantic to define output structures.
    • Patching: How Instructor modifies existing LLM clients.
    • from_provider: The unified interface for creating clients across different providers (e.g., OpenAI, Anthropic).
    • Multimodal: Handling Audio, Images, and PDFs.

    Data Handling

    • Complex Types: Working with Lists, Arrays, Union Types, Enums, and TypedDicts.
    • Field Control: Using Fields for attributes, Alias for renaming, and handling Missing (optional) values.
    • Citations: Extracting and validating source text citations.

    Advanced Features

    • Streaming: Using Stream Partial for partial responses or Stream Iterable for collections of objects.
    • Reliability: Using Retrying for automatic error recovery and Validators for custom logic.
    • Optimization: Implementing Caching, Prompt Caching, and tracking Usage Tokens.
    • Integrations: Using FastAPI, TypeAdapter, and Distillation for production workflows.
  4. Common features across all Instructor integrations

    main

    While specific capabilities vary by provider, all Instructor integrations support a core set of features:

    • Model Patching: Enhancing provider clients with structured output capabilities.
    • Response Models: Defining expected response schemas using Pydantic.
    • Validation: Ensuring LLM responses strictly match your schema definitions.
    • Streaming: Supporting partial or iterative responses via Partial or Iterable modes.
    • Hooks: Providing callbacks for monitoring, logging, and debugging the extraction process.
  5. Understand the Instructor repository structure

    main

    The Instructor repository is organized into several key directories that separate the core library from its supporting tools:

    • instructor/: Contains the core library, including clients, adapters, and utilities required to achieve structured outputs from LLMs.
    • cli/: Contains the command-line interface used for job management and usage tracking.
    • docs/: Contains the source files for the project documentation (built with MkDocs).
    • examples/: Provides practical examples and cookbooks to demonstrate various usage patterns.
    • tests/: Contains the test suite and evaluation scripts used to verify library functionality.
  6. Instructor V2 Module Organization and Exports

    main

    The Instructor V2 architecture is organized into core logic and provider-specific implementations.

    Core Exports (instructor.v2)

    • ModeHandler: Abstract base class for mode implementations.
    • mode_registry: The central registry for mode handlers.
    • RequestHandler: Protocol for handling requests.
    • ReaskHandler: Protocol for handling re-asking/retry logic.
    • ResponseParser: Protocol for parsing LLM responses.
    • from_anthropic: Factory function for Anthropic clients.

    Module Structure

    • instructor.v2.core: Contains Protocols, Registry, decorators.py (@register_mode_handler), exceptions.py, handler.py, patch.py, and retry.py.
    • instructor.v2.providers.anthropic: Contains the Anthropic implementation, including the from_anthropic factory and specific handlers (e.g., TOOLS, JSON).
    # Example of available top-level exports
    from instructor.v2 import ModeHandler, mode_registry, RequestHandler, ReaskHandler, ResponseParser, from_anthropic
  7. What is Self-Refine and how does it work?

    main

    Self-refine is an iterative prompting approach where an LLM is used to perform three distinct roles in a loop:

    1. Generate: Produce an initial response.
    2. Feedback: Evaluate the response and provide specific suggestions for improvement.
    3. Refine: Generate a new version of the response based on that feedback.

    This loop repeats until a predefined stopping condition is met (e.g., the LLM signals it is 'done' or a maximum number of iterations is reached). This pattern is useful for tasks requiring high precision, such as code generation or complex reasoning.

    graph TD
        A[Generate initial response]:::blue --> B[Generate feedback]:::orange
        B --> C{Stopping<br>condition<br>met?}:::orange
        C -->|No| D[Refine response]:::orange
        C -->|Yes| E[Final output]:::green
        D --> B
  8. What is the Self-Ask technique?

    main

    Self-Ask is a prompting strategy designed to solve the compositionality gap in LLMs. The compositionality gap occurs when a model can solve individual sub-components of a problem but fails to synthesize them into the correct final answer.

    By using a structured response_model with instructor, you can force the model to perform a chain-of-thought style reasoning within a single prompt by explicitly generating and answering intermediate questions before arriving at the final conclusion.

  9. What is Universal Self Prompting (USP)?

    main

    Universal Self Prompting (USP) is a two-stage prompting technique designed to improve LLM performance by using unlabeled data to generate high-quality exemplars (few-shot examples) and a scoring function to select them.

    Unlike standard few-shot prompting where examples are manually curated, USP automates the selection process through two stages:

    1. Generate Examples: The LLM is prompted to generate candidate responses for a set of test prompts. These responses are then evaluated using task-specific metrics.
    2. Answer Query: The best-scoring model-generated responses are selected and appended to the final prompt to obtain a prediction via a single forward pass (typically using greedy decoding).

    This method allows the model to self-adapt to the specific task and distribution of the data it is processing.

  10. What is Consistency Based Self Adaptive Prompting (COSP)?

    main

    Consistency Based Self Adaptive Prompting (COSP) is an ensembling technique designed to improve LLM output quality by automatically generating high-quality few-shot examples to include in the final prompt.

    Since these examples are generated from questions without ground truth labels, COSP uses two metrics to select the best ones:

    1. Normalized Entropy: Measures the uncertainty of the model's answers. Low entropy (high agreement among sampled answers) is used as a proxy for correctness.
    2. Repetitiveness: Measures redundancy in the Chain of Thought (CoT) rationale using cosine similarity between sentence embeddings. High repetitiveness is penalized.

    The process follows two main steps:

    1. Selecting Examples: Generate multiple reasoning chains for a set of questions, score them using a weighted sum of entropy and repetitiveness, and select the top k examples with the lowest scores.
    2. Self-Consistency: Append these k examples to the target prompt, sample the model multiple times, and use a majority vote to determine the final answer.
  11. What is CitationMixin?

    main

    Concept

    CitationMixin is a Pydantic mixin that adds citation validation to your models. It introduces a substring_quotes field (a list of strings) which contains quotes from the source text.

    Key Features

    • Hallucination Prevention: Ensures extracted data is grounded in the provided context.
    • Fuzzy Matching: Handles minor differences like extra whitespace, slight wording variations, or punctuation differences (defaulting to up to 5 character errors).
    • Automatic Correction: Automatically corrects LLM-provided quotes to match exact spans in the source text.

    When to use it

    • Building RAG (Retrieval Augmented Generation) systems.
    • When you need to verify extracted information against source text.
    • When you need exact quote spans for UI highlighting or display.

    Limitations

    • You must pass the source text in context={"context": source_text}.
    • It only validates that the quotes exist; it does not validate the accuracy of the extracted facts themselves.
    • Fuzzy matching may not catch all forms of paraphrasing.
  12. What is Prompt Caching and how does it work?

    main

    Prompt Caching is a feature that allows you to cache portions of your prompt to optimize performance for multiple API calls that share the same context. Using prompt caching helps reduce costs and improves response times by minimizing redundant processing of large, static prompt segments.

    To maximize cache hits, use prefix matching: ensure that common instructions or static context (like a system prompt) are placed at the beginning of the prompt, and move all variable parts (like user queries or dynamic data) to the end of the message.