Coder Social home page Coder Social logo

gbnfgen's Introduction

logo

npm NPM Publish

What is it?

gbnfgen is a library for generating grammars based on your typed JSON objects, described through normal TypeScript interfaces and enums.

Generate API calls (and responses) parse free text into structured formats, and build your own llama.cpp-powered agents with ease!

Check out the Live Demo.

Installation

npm i --save @intrinsicai/gbnfgen

Quickstart

import { compile, serializeGrammar } from "@intrinsicai/gbnfgen";

// Supporting Enum for multiple choices (cannot be numbers)
const grammar = compile(
    `enum Mood {
      Happy = "happy",
      Sad = "sad",
      Grateful = "grateful",
      Excited = "excited", 
      Angry = "angry, 
      Peaceful = "peaceful"
    }
    
    interface Person {
         name: string;
         occupation: string;
         age: number;
         mood: Mood,
     }`, "Person");

Why?

Language models allow for open-ended generation of text via autoregressive execution, whereby they generate one token, feed it through a decoder to get a probability distribution of follow-on tokens, and sample from that distribution in an iterative process to generate text.

This is great for activities like generating marketing prose or writing stories, but some of the most exciting usecases involve plugging autonomous LLM agents into existing systems. Interacting with databases and REST APIs requires the model's output to fit a pre-existing schema, usually serialized as JSON.

llama.cpp recently incorporated grammar-based sampling as part of an effort to make it easier to constrain LLM output. Users do this by authoring GBNF files, which are a constrained flavor of Backus-Naur notation for defining a context-free language.

gbnfgen takes the difficulty out of building grammars to let your LLM apps interact with external systems.

What TypeScript types are supported?

Currently the library is narrowly focused, we only provide support for the following types

  • string and string[]
  • number and number[]
  • boolean
  • Interface types and single-dimensional arrays of interface types. These must be interface types that you define within a single call to compile
  • String enums, as defined in this section of the TypeScript handbook.

Inspiration

Microsoft's TypeChat is a similar solution but targeted at OpenAI and other cloud-hosted models. They effectively take an interface definition from the user code, then generate text with GPT4. They use the TypeScript Compiler API to type-check the output of the code to see if it's valid JSON that conforms to the typing.

Most users of llama.cpp are either using the C++ code directly or using it via the llama-cpp-python bindings to Python. TypeScript interfaces provide both humand and machine-friendly representations of typed objects that millions of users are already familiar with, so we decided that it served as a great description format that users of llama.cpp could use to bridge between the other


Up Next

  • Improved type-checking of code passed to compile. Currently we just extract the AST without doing any explicit type-checking, so things like duplicate property declarations and other simple mistakes will not be caught.
  • Support for more type declarations
    • Literals
    • Union types
    • Type aliases

gbnfgen's People

Contributors

a10y avatar dependabot[bot] avatar nova-land avatar

Stargazers

unaudited-wallaby avatar Yixin Dong avatar matan h avatar Andrew Mason avatar  avatar Dmitrii Tyrylgin avatar Bharath Bhushan avatar Peter A. avatar Julian Passebecq avatar  avatar Jay Wang avatar bitsofinfo avatar Dionis Totsila avatar  avatar Biswajit Das avatar yuiseki avatar Mike Ng avatar Philip avatar Lockinwize Lolite avatar dwang avatar Sparx avatar hsnmkls avatar  avatar Clint Herron avatar  avatar Jeff Blake avatar  avatar 昱彤 avatar Halit Sever avatar  avatar Mike DuPont avatar Felipe S. S. Schneider avatar diedinyourthoughts avatar yixinzhang avatar  avatar  avatar Viraj Mehta avatar Syahmi Azhar avatar Yasin avatar Rémi Louf avatar XYZ avatar Sanju avatar Lee Gao avatar Sematre avatar Frank Polte avatar Dmytro Sadovnychyi avatar Dmitriy Che avatar Cory Gross avatar Tariq Hassan avatar Mahyar avatar Fouquet François avatar Greg Richardson avatar Andrew Chin avatar Andrei Surugiu avatar Joel Boehland avatar Ignas Bernotas avatar Jeff Carpenter avatar 饭食钢 avatar  avatar Adrien Brault avatar  avatar Phu Tran avatar Muhammad Fakhri Putra Supriyadi avatar 爱可可-爱生活 avatar 祀画 avatar 段清华DEAN avatar Matt Hoffner avatar Evan Armstrong avatar Patrick Lee avatar rnr channel avatar Ivan Stepanov avatar Luc Chartier avatar Ishan Marikar avatar Eli Broderick avatar Fernando Mumbach avatar  avatar  avatar  avatar Oguzhan Mete Ozturk avatar carbon based lifeform avatar  avatar Valtteri Karesto avatar Michael Su avatar Alfred.Liu avatar Laura avatar yibit avatar  avatar Nico avatar Christian Stewart avatar  avatar Amit Karamchandani Batra avatar Koolen Dasheppi avatar Jacques avatar spuun avatar Marc avatar afrideva avatar  avatar Benjamin Babik avatar Filipe Almeida avatar İsmail Codar avatar

Watchers

Tarrek Shaban avatar  avatar

gbnfgen's Issues

Exclude unicode characters from string?

Hi, I can't find any documentation but would like to exclude unicode characters from strings.

I.e. 0x00-0x08 and 0x0B-0x1F so that I don't get crap. Is there a way in GBNF to eliminate these? It would be useful to have this in the string set.

An enum member name must be followed by a ',', '=', or '}

Running the quick start, node 20.x

Error: Compilation failed: Unterminated string literal.
An enum member name must be followed by a ',', '=', or '}'.
    at compileSync (file:///path/to/ai/experiments/grammer-gen/node_modules/@intrinsicai/gbnfgen/dist/compiler.js:169:15)
    at file:///path/to/ai/experiments/grammer-gen/node_modules/@intrinsicai/gbnfgen/dist/compiler.js:137:29
    at new Promise (<anonymous>)
    at compile (file:///path/to/ai/experiments/grammer-gen/node_modules/@intrinsicai/gbnfgen/dist/compiler.js:135:12)
    at file:///path/to/ai/experiments/grammer-gen/gen.js:4:17
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12)

String should not contain control characters.

Right now, strings can for example contain a new line, not an escaped one.

Which will lead to incorrect json generation

Here is my suggestion :

string ::= "\"" (char | escapeSequence)* "\""
char ::= [^"\\\x7F\x00-\x1F]
escapeSequence ::= "\\\"" | "\\\\" | "\\n" | "\\r" | "\\t" | "\\b" | "\\f" 


I could open a PR but I could be missing something so I open an issue to discuss this

top level array

how to declare top level object array ?
compile(interface Character { name: string; }, Character[]); #=> Error: Root type Character[] is not one of the declared types
compile(interface Character { name: string; } type Root = Character[];, Root); #=> Error: Invalid top-level declaration of kind TypeAliasDeclaration

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.