riffer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 28ba9aa31a3f79392de37c769531f765a1b32aff4272fd727efeef8eb1435996
4
+ data.tar.gz: 97328dee069286c025a7478414816b032682e34ce3e1649d1f96634f2fbc0b43
5
+ SHA512:
6
+ metadata.gz: 961a2559a012e481273fe92ac2ae81b4cdb827a00433c74b62c6a3041a78b64b4b374a41ea380ff1874ea11e7c883bddda391276e32bef043134c6fdbefc245e
7
+ data.tar.gz: dd824a10a31dc4eac9732dac2d864698ec6118f6753001b92a8fadddf8d695e8c28240adf250341d16c5c3f93c8523bd22d81e9f5a0f7f2a9889ef020673e9da
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,6 @@
1
+ plugins:
2
+ - rubocop-rspec
3
+
4
+ RSpec/MultipleExpectations:
5
+ Enabled: true
6
+ Max: 1
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.4.8
data/.standard.yml ADDED
@@ -0,0 +1,2 @@
1
+ extend_config:
2
+ - .rubocop_rspec.yml
data/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2024-12-20
9
+
10
+ ### Added
11
+
12
+ - **Core Framework**: Foundation for building AI-powered applications and agents
13
+ - **Configuration System**: Global and instance-level configuration management
14
+ - **Agents**: Base agent class for building conversational agents
15
+ - **Messages**: Complete message system with support for User, Assistant, System, and Tool messages
16
+ - **Providers**: Pluggable provider architecture
17
+
18
+ - **OpenAI Provider**: Full integration with OpenAI API for text generation and streaming
19
+ - **Test Provider**: Built-in test provider for development and testing
20
+
21
+ - **Stream Events**: Streaming response support with TextDelta and TextDone events
22
+ - **Zeitwerk Autoloading**: Modern Ruby autoloading for clean code organization
23
+ - **Comprehensive Test Suite**: Full RSpec test coverage with VCR cassettes for API mocking
24
+ - **StandardRB Code Style**: Enforced code formatting and linting
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/Guardfile ADDED
@@ -0,0 +1,70 @@
1
+ # A sample Guardfile
2
+ # More info at https://github.com/guard/guard#readme
3
+
4
+ ## Uncomment and set this to only include directories you want to watch
5
+ # directories %w(app lib config test spec features) \
6
+ # .select{|d| Dir.exist?(d) ? d : UI.warning("Directory #{d} does not exist")}
7
+
8
+ ## Note: if you are using the `directories` clause above and you are not
9
+ ## watching the project directory ('.'), then you will want to move
10
+ ## the Guardfile to a watched dir and symlink it back, e.g.
11
+ #
12
+ # $ mkdir config
13
+ # $ mv Guardfile config/
14
+ # $ ln -s config/Guardfile .
15
+ #
16
+ # and, you'll have to watch "config/Guardfile" instead of "Guardfile"
17
+
18
+ # Note: The cmd option is now required due to the increasing number of ways
19
+ # rspec may be run, below are examples of the most common uses.
20
+ # * bundler: 'bundle exec rspec'
21
+ # * bundler binstubs: 'bin/rspec'
22
+ # * spring: 'bin/rspec' (This will use spring if running and you have
23
+ # installed the spring binstubs per the docs)
24
+ # * zeus: 'zeus rspec' (requires the server to be started separately)
25
+ # * 'just' rspec: 'rspec'
26
+
27
+ guard :rspec, cmd: "bundle exec rspec" do
28
+ require "guard/rspec/dsl"
29
+ dsl = Guard::RSpec::Dsl.new(self)
30
+
31
+ # Feel free to open issues for suggestions and improvements
32
+
33
+ # RSpec files
34
+ rspec = dsl.rspec
35
+ watch(rspec.spec_helper) { rspec.spec_dir }
36
+ watch(rspec.spec_support) { rspec.spec_dir }
37
+ watch(rspec.spec_files)
38
+
39
+ # Ruby files
40
+ ruby = dsl.ruby
41
+ dsl.watch_spec_files_for(ruby.lib_files)
42
+
43
+ # Rails files
44
+ rails = dsl.rails(view_extensions: %w[erb haml slim])
45
+ dsl.watch_spec_files_for(rails.app_files)
46
+ dsl.watch_spec_files_for(rails.views)
47
+
48
+ watch(rails.controllers) do |m|
49
+ [
50
+ rspec.spec.call("routing/#{m[1]}_routing"),
51
+ rspec.spec.call("controllers/#{m[1]}_controller"),
52
+ rspec.spec.call("acceptance/#{m[1]}")
53
+ ]
54
+ end
55
+
56
+ # Rails config changes
57
+ watch(rails.spec_helper) { rspec.spec_dir }
58
+ watch(rails.routes) { "#{rspec.spec_dir}/routing" }
59
+ watch(rails.app_controller) { "#{rspec.spec_dir}/controllers" }
60
+
61
+ # Capybara features specs
62
+ watch(rails.view_dirs) { |m| rspec.spec.call("features/#{m[1]}") }
63
+ watch(rails.layouts) { |m| rspec.spec.call("features/#{m[1]}") }
64
+
65
+ # Turnip features and steps
66
+ watch(%r{^spec/acceptance/(.+)\.feature$})
67
+ watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) do |m|
68
+ Dir[File.join("**/#{m[1]}.feature")][0] || "spec/acceptance"
69
+ end
70
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Jake Bottrall
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # Riffer
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/riffer`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ ```bash
14
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
15
+ ```
16
+
17
+ If bundler is not being used to manage dependencies, install the gem by executing:
18
+
19
+ ```bash
20
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/riffer. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/riffer/blob/main/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the Riffer project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/riffer/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[spec standard]
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Agents
4
+ class Base
5
+ class << self
6
+ def model(model_string = nil)
7
+ return @model if model_string.nil?
8
+
9
+ raise ArgumentError, "model must be a String" unless model_string.is_a?(String)
10
+ raise ArgumentError, "model cannot be empty" if model_string.strip.empty?
11
+
12
+ @model = model_string
13
+ end
14
+
15
+ def instructions(instructions_text = nil)
16
+ return @instructions if instructions_text.nil?
17
+
18
+ raise ArgumentError, "instructions must be a String" unless instructions_text.is_a?(String)
19
+ raise ArgumentError, "instructions cannot be empty" if instructions_text.strip.empty?
20
+
21
+ @instructions = instructions_text
22
+ end
23
+ end
24
+
25
+ attr_reader :messages
26
+
27
+ def initialize
28
+ @messages = []
29
+ @model_string = self.class.model
30
+ @instructions_text = self.class.instructions
31
+
32
+ provider_name, model_name = @model_string.split("/", 2)
33
+
34
+ raise ArgumentError, "Invalid model string: #{@model_string}" unless [provider_name, model_name].all? { |part| part.is_a?(String) && !part.strip.empty? }
35
+
36
+ @provider_name = provider_name
37
+ @model_name = model_name
38
+ end
39
+
40
+ def generate(prompt)
41
+ initialize_messages(prompt)
42
+
43
+ loop do
44
+ response = call_llm
45
+ @messages << response
46
+
47
+ break unless has_tool_calls?(response)
48
+
49
+ execute_tool_calls(response)
50
+ end
51
+
52
+ extract_final_response
53
+ end
54
+
55
+ private
56
+
57
+ def initialize_messages(prompt)
58
+ @messages = [] # Reset messages for each generation call
59
+ @messages << Riffer::Messages::System.new(@instructions_text) if @instructions_text
60
+ @messages << Riffer::Messages::User.new(prompt)
61
+ end
62
+
63
+ def call_llm
64
+ provider_instance.generate_text(messages: @messages, model: @model_name)
65
+ end
66
+
67
+ def provider_instance
68
+ @provider_instance ||= Riffer::Providers::Base.find_provider(@provider_name).new
69
+ end
70
+
71
+ def has_tool_calls?(response)
72
+ response.is_a?(Riffer::Messages::Assistant) && !response.tool_calls.empty?
73
+ end
74
+
75
+ def execute_tool_calls(response)
76
+ response.tool_calls.each do |tool_call|
77
+ tool_result = execute_tool_call(tool_call)
78
+ @messages << Riffer::Messages::Tool.new(
79
+ tool_result,
80
+ tool_call_id: tool_call[:id],
81
+ name: tool_call[:name]
82
+ )
83
+ end
84
+ end
85
+
86
+ def execute_tool_call(tool_call)
87
+ "Tool execution not implemented yet"
88
+ end
89
+
90
+ def extract_final_response
91
+ last_assistant_message = @messages.reverse.find { |msg| msg.is_a?(Riffer::Messages::Assistant) }
92
+ last_assistant_message&.content || ""
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Agents
4
+ class Error < StandardError; end
5
+ class InvalidInputError < Error; end
6
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer
4
+ class Config
5
+ attr_reader :openai
6
+
7
+ def initialize
8
+ @openai = Struct.new(:api_key).new
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "logger"
4
+
5
+ module Riffer
6
+ class Core
7
+ attr_reader :logger
8
+
9
+ def initialize
10
+ @logger = Logger.new($stdout)
11
+ @logger.level = Logger::INFO
12
+ @storage_registry = {}
13
+ end
14
+
15
+ def configure
16
+ yield self if block_given?
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::DependencyHelper
4
+ class LoadError < ::LoadError; end
5
+
6
+ class VersionError < ScriptError; end
7
+
8
+ def depends_on(gem_name, req: true)
9
+ gem(gem_name)
10
+
11
+ return true unless defined?(Bundler)
12
+
13
+ gem_version = Gem.loaded_specs[gem_name].version
14
+ gem_dependency = Bundler.load.dependencies.find { |g| g.name == gem_name }
15
+ gem_requirement = gem_dependency&.requirement
16
+
17
+ unless gem_requirement
18
+ raise VersionError, "The #{gem_name} gem is installed but not specified in your Bundler dependencies (e.g., Gemfile)."
19
+ end
20
+
21
+ unless gem_requirement.satisfied_by?(gem_version)
22
+ raise VersionError, "The #{gem_name} gem is installed, but version #{gem_requirement} is required. You have #{gem_version}."
23
+ end
24
+
25
+ lib_name = gem_name if req == true
26
+ lib_name = req if req.is_a?(String)
27
+
28
+ require(lib_name) if lib_name
29
+
30
+ true
31
+ rescue ::LoadError
32
+ raise LoadError, "Could not load #{gem_name}. Please ensure that the #{gem_name} gem is installed."
33
+ end
34
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Messages
4
+ class Assistant < Base
5
+ attr_reader :tool_calls
6
+
7
+ def initialize(content, tool_calls: [])
8
+ super(content)
9
+ @tool_calls = tool_calls
10
+ end
11
+
12
+ def role
13
+ "assistant"
14
+ end
15
+
16
+ def to_h
17
+ hash = {role: role, content: content}
18
+ hash[:tool_calls] = tool_calls unless tool_calls.empty?
19
+ hash
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Messages
4
+ class Base
5
+ attr_reader :content
6
+
7
+ def initialize(content)
8
+ @content = content
9
+ end
10
+
11
+ def to_h
12
+ {role: role, content: content}
13
+ end
14
+
15
+ def role
16
+ raise NotImplementedError, "Subclasses must implement #role"
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Messages
4
+ class System < Base
5
+ def role
6
+ "system"
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Messages
4
+ class Tool < Base
5
+ attr_reader :tool_call_id, :name
6
+
7
+ def initialize(content, tool_call_id:, name:)
8
+ super(content)
9
+ @tool_call_id = tool_call_id
10
+ @name = name
11
+ end
12
+
13
+ def role
14
+ "tool"
15
+ end
16
+
17
+ def to_h
18
+ {role: role, content: content, tool_call_id: tool_call_id, name: name}
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Messages
4
+ class User < Base
5
+ def role
6
+ "user"
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Messages
4
+ end
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Providers
4
+ class Base
5
+ include Riffer::DependencyHelper
6
+
7
+ class << self
8
+ def identifier(value = nil)
9
+ return @identifier if value.nil?
10
+
11
+ @identifier = value
12
+ end
13
+
14
+ def find_provider(identifier)
15
+ ensure_providers_loaded
16
+
17
+ provider = subclasses.find { |provider_class| provider_class.identifier == identifier }
18
+
19
+ raise InvalidInputError, "Provider not found for identifier: #{identifier}" if provider.nil?
20
+
21
+ provider
22
+ end
23
+
24
+ private
25
+
26
+ def ensure_providers_loaded
27
+ return if @providers_loaded
28
+
29
+ Zeitwerk::Loader.eager_load_namespace(Riffer::Providers)
30
+
31
+ @providers_loaded = true
32
+ end
33
+ end
34
+
35
+ def generate_text(prompt: nil, system: nil, messages: nil, model: nil)
36
+ validate_input!(prompt: prompt, system: system, messages: messages)
37
+ normalized_messages = normalize_messages(prompt: prompt, system: system, messages: messages)
38
+ perform_generate_text(normalized_messages, model: model)
39
+ end
40
+
41
+ def stream_text(prompt: nil, system: nil, messages: nil, model: nil)
42
+ validate_input!(prompt: prompt, system: system, messages: messages)
43
+ normalized_messages = normalize_messages(prompt: prompt, system: system, messages: messages)
44
+ perform_stream_text(normalized_messages, model: model)
45
+ end
46
+
47
+ private
48
+
49
+ def perform_generate_text(messages, model: nil)
50
+ raise NotImplementedError, "Subclasses must implement #perform_generate_text"
51
+ end
52
+
53
+ def perform_stream_text(messages, model: nil)
54
+ raise NotImplementedError, "Subclasses must implement #perform_stream_text"
55
+ end
56
+
57
+ def validate_input!(prompt:, system:, messages:)
58
+ if messages.nil?
59
+ raise InvalidInputError, "prompt is required when messages is not provided" if prompt.nil?
60
+ else
61
+ raise InvalidInputError, "cannot provide both prompt and messages" unless prompt.nil?
62
+ raise InvalidInputError, "cannot provide both system and messages" unless system.nil?
63
+ raise InvalidInputError, "messages must include at least one user message" unless has_user_message?(messages)
64
+ end
65
+ end
66
+
67
+ def normalize_messages(prompt:, system:, messages:)
68
+ if messages
69
+ return messages.map { |msg| convert_to_message_object(msg) }
70
+ end
71
+
72
+ result = []
73
+ result << Riffer::Messages::System.new(system) if system
74
+ result << Riffer::Messages::User.new(prompt)
75
+ result
76
+ end
77
+
78
+ def convert_to_message_object(msg)
79
+ if msg.is_a?(Riffer::Messages::Base)
80
+ return msg
81
+ end
82
+
83
+ unless msg.is_a?(Hash)
84
+ raise InvalidInputError, "Message must be a Hash or Message object, got #{msg.class}"
85
+ end
86
+
87
+ case msg[:role]
88
+ when "user"
89
+ Riffer::Messages::User.new(msg[:content])
90
+ when "assistant"
91
+ Riffer::Messages::Assistant.new(msg[:content], tool_calls: msg[:tool_calls] || [])
92
+ when "system"
93
+ Riffer::Messages::System.new(msg[:content])
94
+ when "tool"
95
+ Riffer::Messages::Tool.new(msg[:content], tool_call_id: msg[:tool_call_id], name: msg[:name])
96
+ else
97
+ raise InvalidInputError, "Unknown message role: #{msg[:role]}"
98
+ end
99
+ end
100
+
101
+ def has_user_message?(messages)
102
+ messages.any? do |msg|
103
+ msg.is_a?(Riffer::Messages::User) || (msg.is_a?(Hash) && msg[:role] == "user")
104
+ end
105
+ end
106
+ end
107
+ end
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openai"
4
+
5
+ module Riffer::Providers
6
+ class OpenAI < Base
7
+ identifier "openai"
8
+
9
+ def initialize(**options)
10
+ depends_on "openai"
11
+
12
+ api_key = options.fetch(:api_key, Riffer.config.openai.api_key)
13
+ raise ArgumentError, "OpenAI API key is required. Set it via Riffer.configure or pass :api_key option" if api_key.nil? || api_key.empty?
14
+
15
+ @client = ::OpenAI::Client.new(api_key: api_key, **options.except(:api_key))
16
+ end
17
+
18
+ private
19
+
20
+ def perform_generate_text(messages, model:)
21
+ params = build_request_params(messages, model)
22
+ response = @client.responses.create(params)
23
+
24
+ output = response.output.find { |o| o.type == :message }
25
+
26
+ if output.nil?
27
+ raise Riffer::Providers::Error, "No output returned from OpenAI API"
28
+ end
29
+
30
+ content = output.content.find { |c| c.type == :output_text }
31
+
32
+ if content.nil?
33
+ raise Riffer::Providers::Error, "No content returned from OpenAI API"
34
+ end
35
+
36
+ if content.type == :refusal
37
+ raise Riffer::Providers::Error, "Request was refused: #{content.refusal}"
38
+ end
39
+
40
+ if content.type != :output_text
41
+ raise Riffer::Providers::Error, "Unexpected content type: #{content.type}"
42
+ end
43
+
44
+ Riffer::Messages::Assistant.new(content.text)
45
+ end
46
+
47
+ def perform_stream_text(messages, model:)
48
+ Enumerator.new do |yielder|
49
+ params = build_request_params(messages, model)
50
+ stream = @client.responses.stream(params)
51
+
52
+ process_stream_events(stream, yielder)
53
+ end
54
+ end
55
+
56
+ def build_request_params(messages, model)
57
+ {
58
+ model: model,
59
+ input: convert_message_to_openai_format(messages)
60
+ }
61
+ end
62
+
63
+ def convert_message_to_openai_format(messages)
64
+ messages.map do |message|
65
+ case message
66
+ when Riffer::Messages::System
67
+ {role: "developer", content: message.content}
68
+ when Riffer::Messages::User
69
+ {role: "user", content: message.content}
70
+ when Riffer::Messages::Assistant
71
+ {role: "assistant", content: message.content}
72
+ when Riffer::Messages::Tool
73
+ raise Riffer::Providers::InvalidInputError, "Tool messages are not supported by OpenAI provider yet"
74
+ when Hash
75
+ message
76
+ else
77
+ raise Riffer::Providers::InvalidInputError, "Unsupported message type: #{message.class}"
78
+ end
79
+ end
80
+ end
81
+
82
+ def process_stream_events(stream, yielder)
83
+ stream.each do |event|
84
+ next unless should_process_event?(event)
85
+
86
+ content = extract_event_content(event)
87
+ yielder << content if content
88
+ end
89
+ end
90
+
91
+ def should_process_event?(event)
92
+ [:"response.output_text.delta", :"response.output_text.done"].include?(event.type)
93
+ end
94
+
95
+ def extract_event_content(event)
96
+ case event.type
97
+ when :"response.output_text.delta"
98
+ Riffer::StreamEvents::TextDelta.new(event.delta)
99
+ when :"response.output_text.done"
100
+ Riffer::StreamEvents::TextDone.new(event.text)
101
+ end
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Providers
4
+ class Test < Base
5
+ identifier "test"
6
+
7
+ attr_reader :calls
8
+
9
+ def initialize(**options)
10
+ @responses = options[:responses] || []
11
+ @current_index = 0
12
+ @calls = []
13
+ @stubbed_response = nil
14
+ end
15
+
16
+ def stub_response(content, tool_calls: [])
17
+ @stubbed_response = {role: "assistant", content: content, tool_calls: tool_calls}
18
+ end
19
+
20
+ private
21
+
22
+ def perform_generate_text(messages, model: nil)
23
+ @calls << {messages: messages.map(&:to_h)}
24
+ response = @stubbed_response || @responses[@current_index] || {role: "assistant", content: "Test response"}
25
+ @current_index += 1
26
+
27
+ if response.is_a?(Hash)
28
+ Riffer::Messages::Assistant.new(response[:content], tool_calls: response[:tool_calls] || [])
29
+ else
30
+ response
31
+ end
32
+ end
33
+
34
+ def perform_stream_text(messages, model: nil)
35
+ @calls << {messages: messages.map(&:to_h)}
36
+ response = @stubbed_response || @responses[@current_index] || {role: "assistant", content: "Test response"}
37
+ @current_index += 1
38
+ Enumerator.new do |yielder|
39
+ content_parts = response[:content].split(". ").map { |part| part + (part.end_with?(".") ? "" : ".") }
40
+ content_parts.each do |part|
41
+ yielder << {role: "assistant", content: part + " "}
42
+ sleep 0.5
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Providers
4
+ class Error < StandardError; end
5
+ class InvalidInputError < Error; end
6
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Storage
4
+ class Base
5
+ def initialize(**options)
6
+ @options = options
7
+ end
8
+
9
+ def save(key, value)
10
+ raise NotImplementedError, "Subclasses must implement #save"
11
+ end
12
+
13
+ def load(key)
14
+ raise NotImplementedError, "Subclasses must implement #load"
15
+ end
16
+
17
+ def delete(key)
18
+ raise NotImplementedError, "Subclasses must implement #delete"
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Storage
4
+ class Error < StandardError; end
5
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::StreamEvents
4
+ class Base
5
+ attr_reader :role
6
+
7
+ def initialize(role: "assistant")
8
+ @role = role
9
+ end
10
+
11
+ def to_h
12
+ raise NotImplementedError, "Subclasses must implement #to_h"
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::StreamEvents
4
+ class TextDelta < Base
5
+ attr_reader :content
6
+
7
+ def initialize(content, role: "assistant")
8
+ super(role: role)
9
+ @content = content
10
+ end
11
+
12
+ def to_h
13
+ {role: @role, content: @content}
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::StreamEvents
4
+ class TextDone < Base
5
+ attr_reader :content
6
+
7
+ def initialize(content, role: "assistant")
8
+ super(role: role)
9
+ @content = content
10
+ end
11
+
12
+ def to_h
13
+ {role: @role, content: @content}
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::StreamEvents
4
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Tools
4
+ class Base
5
+ attr_reader :name, :description
6
+
7
+ def initialize(name:, description:, **options)
8
+ @name = name
9
+ @description = description
10
+ @options = options
11
+ end
12
+
13
+ def call(**params)
14
+ raise NotImplementedError, "Subclasses must implement #call"
15
+ end
16
+
17
+ def schema
18
+ {
19
+ name: @name,
20
+ description: @description,
21
+ parameters: parameters_schema
22
+ }
23
+ end
24
+
25
+ private
26
+
27
+ def parameters_schema
28
+ {}
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer::Tools
4
+ class Error < StandardError; end
5
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Riffer
4
+ VERSION = "0.1.0"
5
+ end
data/lib/riffer.rb ADDED
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "zeitwerk"
4
+
5
+ loader = Zeitwerk::Loader.for_gem
6
+ loader.inflector.inflect(
7
+ "open_ai" => "OpenAI"
8
+ )
9
+ loader.setup
10
+
11
+ module Riffer
12
+ class Error < StandardError; end
13
+
14
+ class << self
15
+ def config
16
+ @config ||= Config.new
17
+ end
18
+
19
+ def configure
20
+ yield config if block_given?
21
+ end
22
+ end
23
+
24
+ Agent = Agents::Base
25
+ Tool = Tools::Base
26
+ Provider = Providers::Base
27
+ end
data/sig/riffer.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Riffer
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,200 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: riffer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jake Bottrall
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: zeitwerk
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '2.6'
19
+ - - ">="
20
+ - !ruby/object:Gem::Version
21
+ version: 2.6.0
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - "~>"
27
+ - !ruby/object:Gem::Version
28
+ version: '2.6'
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ version: 2.6.0
32
+ - !ruby/object:Gem::Dependency
33
+ name: openai
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - "~>"
37
+ - !ruby/object:Gem::Version
38
+ version: 0.42.0
39
+ type: :development
40
+ prerelease: false
41
+ version_requirements: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - "~>"
44
+ - !ruby/object:Gem::Version
45
+ version: 0.42.0
46
+ - !ruby/object:Gem::Dependency
47
+ name: rspec
48
+ requirement: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - "~>"
51
+ - !ruby/object:Gem::Version
52
+ version: '3.0'
53
+ type: :development
54
+ prerelease: false
55
+ version_requirements: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - "~>"
58
+ - !ruby/object:Gem::Version
59
+ version: '3.0'
60
+ - !ruby/object:Gem::Dependency
61
+ name: vcr
62
+ requirement: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - "~>"
65
+ - !ruby/object:Gem::Version
66
+ version: '6.0'
67
+ type: :development
68
+ prerelease: false
69
+ version_requirements: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - "~>"
72
+ - !ruby/object:Gem::Version
73
+ version: '6.0'
74
+ - !ruby/object:Gem::Dependency
75
+ name: webmock
76
+ requirement: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - "~>"
79
+ - !ruby/object:Gem::Version
80
+ version: '3.0'
81
+ type: :development
82
+ prerelease: false
83
+ version_requirements: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - "~>"
86
+ - !ruby/object:Gem::Version
87
+ version: '3.0'
88
+ - !ruby/object:Gem::Dependency
89
+ name: rake
90
+ requirement: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - "~>"
93
+ - !ruby/object:Gem::Version
94
+ version: '13.0'
95
+ type: :development
96
+ prerelease: false
97
+ version_requirements: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - "~>"
100
+ - !ruby/object:Gem::Version
101
+ version: '13.0'
102
+ - !ruby/object:Gem::Dependency
103
+ name: standard
104
+ requirement: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - "~>"
107
+ - !ruby/object:Gem::Version
108
+ version: '1.3'
109
+ type: :development
110
+ prerelease: false
111
+ version_requirements: !ruby/object:Gem::Requirement
112
+ requirements:
113
+ - - "~>"
114
+ - !ruby/object:Gem::Version
115
+ version: '1.3'
116
+ - !ruby/object:Gem::Dependency
117
+ name: rubocop-rspec
118
+ requirement: !ruby/object:Gem::Requirement
119
+ requirements:
120
+ - - "~>"
121
+ - !ruby/object:Gem::Version
122
+ version: '3.8'
123
+ type: :development
124
+ prerelease: false
125
+ version_requirements: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - "~>"
128
+ - !ruby/object:Gem::Version
129
+ version: '3.8'
130
+ description: Riffer is a comprehensive Ruby framework designed to simplify the development
131
+ of AI-powered applications and agents. It provides a complete toolkit for integrating
132
+ artificial intelligence capabilities into your Ruby projects.
133
+ email:
134
+ - jakebottrall@gmail.com
135
+ executables: []
136
+ extensions: []
137
+ extra_rdoc_files: []
138
+ files:
139
+ - ".rspec"
140
+ - ".rubocop_rspec.yml"
141
+ - ".ruby-version"
142
+ - ".standard.yml"
143
+ - CHANGELOG.md
144
+ - CODE_OF_CONDUCT.md
145
+ - Guardfile
146
+ - LICENSE.txt
147
+ - README.md
148
+ - Rakefile
149
+ - lib/riffer.rb
150
+ - lib/riffer/agents.rb
151
+ - lib/riffer/agents/base.rb
152
+ - lib/riffer/config.rb
153
+ - lib/riffer/core.rb
154
+ - lib/riffer/dependency_helper.rb
155
+ - lib/riffer/messages.rb
156
+ - lib/riffer/messages/assistant.rb
157
+ - lib/riffer/messages/base.rb
158
+ - lib/riffer/messages/system.rb
159
+ - lib/riffer/messages/tool.rb
160
+ - lib/riffer/messages/user.rb
161
+ - lib/riffer/providers.rb
162
+ - lib/riffer/providers/base.rb
163
+ - lib/riffer/providers/open_ai.rb
164
+ - lib/riffer/providers/test.rb
165
+ - lib/riffer/storage.rb
166
+ - lib/riffer/storage/base.rb
167
+ - lib/riffer/stream_events.rb
168
+ - lib/riffer/stream_events/base.rb
169
+ - lib/riffer/stream_events/text_delta.rb
170
+ - lib/riffer/stream_events/text_done.rb
171
+ - lib/riffer/tools.rb
172
+ - lib/riffer/tools/base.rb
173
+ - lib/riffer/version.rb
174
+ - sig/riffer.rbs
175
+ homepage: https://riffer.ai
176
+ licenses:
177
+ - MIT
178
+ metadata:
179
+ allowed_push_host: https://rubygems.org
180
+ homepage_uri: https://riffer.ai
181
+ source_code_uri: https://github.com/bottrall/riffer
182
+ changelog_uri: https://github.com/bottrall/riffer/blob/main/CHANGELOG.md
183
+ rdoc_options: []
184
+ require_paths:
185
+ - lib
186
+ required_ruby_version: !ruby/object:Gem::Requirement
187
+ requirements:
188
+ - - ">="
189
+ - !ruby/object:Gem::Version
190
+ version: 3.2.0
191
+ required_rubygems_version: !ruby/object:Gem::Requirement
192
+ requirements:
193
+ - - ">="
194
+ - !ruby/object:Gem::Version
195
+ version: '0'
196
+ requirements: []
197
+ rubygems_version: 3.6.9
198
+ specification_version: 4
199
+ summary: The all-in-one Ruby framework for building AI-powered applications and agents.
200
+ test_files: []