Back to Baml

Ruby

fern/01-guide/02-languages/ruby.mdx

0.222.02.3 KB
Original Source

<Note>You can check out this repo: https://github.com/BoundaryML/baml-examples/tree/main/ruby-starter</Note>

To set up BAML with Ruby do the following:

<Steps> ### Install BAML VSCode Extension https://marketplace.visualstudio.com/items?itemName=boundary.baml-extension
  - syntax highlighting
  - testing playground
  - prompt previews

Install BAML

  ```bash bundle
  bundle add baml sorbet-runtime
  ```

Add BAML to your existing project

  This will give you some starter BAML code in a `baml_src` directory.

  ```bash
  bundle exec baml-cli init
  ```

Generate Ruby code from .baml files

```bash
bundle exec baml-cli generate
```
`
See [What is baml_src](/guide/introduction/baml_src) to learn more about how this works.


As fun as writing BAML is, we want you be able to leverage BAML with existing ruby modules. This command gives you a ruby module that is a type-safe interface to every BAML function.

<Tip>
  Our [VSCode extension](https://marketplace.visualstudio.com/items?itemName=Boundary.baml-extension) automatically runs this command when you save a BAML file.
</Tip>

Use a BAML function in Ruby!

<Error>If `baml_client` doesn't exist, make sure to run the previous step!</Error>

<Tabs>
<Tab title="Regular" language="ruby">
```ruby main.rb
require_relative "baml_client/client"

def example(raw_resume)
    # r is an instance of Baml::Types::Resume, defined in baml_client/types
    r = Baml.Client.ExtractResume(resume: raw_resume)

    puts "ExtractResume response:"
    puts r.inspect
end

example 'Grace Hopper created COBOL'
```
</Tab>

<Tab title="Streaming" language="ruby">
```ruby stream_example.rb
require_relative "baml_client/client"

def example_stream(raw_resume)
    stream = Baml.Client.stream.ExtractResume(resume: raw_resume)

    stream.each do |msg|
        # msg is an instance of Baml::PartialTypes::Resume
        # defined in baml_client/partial_types
        puts msg.inspect
    end

    stream.get_final_response
end

example_stream 'Grace Hopper created COBOL'
```
</Tab>
</Tabs>
</Steps>