### Install Raix Ruby Gem Source: https://github.com/olympiaai/raix/blob/main/README.md This snippet provides instructions for installing the Raix Ruby gem. It covers both `bundle add` for Bundler-managed projects and `gem install` for standalone installations, ensuring the necessary dependencies are met for using Raix. ```shell $ bundle add raix If bundler is not being used to manage dependencies, install the gem by executing: $ gem install raix ``` -------------------------------- ### Install and Release Raix Ruby Gem to RubyGems Source: https://github.com/olympiaai/raix/blob/main/README.md This snippet demonstrates how to install the Raix gem onto a local machine and how to release a new version. Releasing involves updating the version number in `version.rb`, creating a git tag, pushing commits, and pushing the `.gem` file to rubygems.org. ```Bash bundle exec rake install bundle exec rake release ``` -------------------------------- ### Set Up and Test Raix Ruby Gem Development Environment Source: https://github.com/olympiaai/raix/blob/main/README.md This snippet provides commands to initialize the Raix Ruby gem development environment. It covers installing project dependencies, running unit tests, and launching an interactive console for experimentation. Note that `OR_ACCESS_TOKEN` and `OAI_ACCESS_TOKEN` environment variables are required for running specs. ```Bash bin/setup rake spec bin/console ``` -------------------------------- ### Basic Usage of Raix ResponseFormat in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md This Ruby example demonstrates the basic usage of `Raix::ResponseFormat` to define a simple JSON schema for AI responses. It shows how to create a format object with basic types and apply it to a chat completion call, ensuring structured output like 'PersonInfo' with name and age. ```ruby # Simple schema with basic types format = Raix::ResponseFormat.new("PersonInfo", { name: { type: "string" }, age: { type: "integer" } }) # Use in chat completion my_ai.chat_completion(response_format: format) ``` -------------------------------- ### Ruby Chat Completion with Raix Source: https://github.com/olympiaai/raix/blob/main/README.md This snippet demonstrates how to use the mandatory `ChatCompletion` module in Raix. By including this module, Ruby classes gain access to `transcript` and `chat_completion` methods, enabling interaction with LLMs. The example shows adding a user message to the transcript and then calling `chat_completion` to get an AI response. ```Ruby class MeaningOfLife include Raix::ChatCompletion end ai = MeaningOfLife.new ai.transcript << { user: "What is the meaning of life?" } ai.chat_completion ``` -------------------------------- ### Integrate Raix ResponseFormat with Chat Completion in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md This Ruby example demonstrates how to integrate `Raix::ResponseFormat` directly into a chat completion class. It shows defining a schema for AI analysis of a person and using it within the `chat_completion` method, ensuring the AI's response adheres to the specified structured format. ```ruby class StructuredResponse include Raix::ChatCompletion def analyze_person(name) format = Raix::ResponseFormat.new("PersonAnalysis", { full_name: { type: "string" }, age_estimate: { type: "integer" }, personality_traits: ["string"] }) transcript << { user: "Analyze the person named #{name}" } chat_completion(params: { response_format: format }) end end response = StructuredResponse.new.analyze_person("Alice") # Returns a hash matching the defined schema ``` -------------------------------- ### Example of Generated JSON Schema by Raix ResponseFormat Source: https://github.com/olympiaai/raix/blob/main/README.md This JSON snippet shows the typical structure of a schema generated by the `Raix::ResponseFormat` class. It highlights how Ruby definitions are translated into a standard JSON schema format, including type, properties, required fields, and `additionalProperties: false` for strict validation. ```json { "type": "json_schema", "json_schema": { "name": "SchemaName", "schema": { "type": "object", "properties": { "property1": { "type": "string" }, "property2": { "type": "integer" } }, "required": ["property1", "property2"], "additionalProperties": false }, "strict": true } } ``` -------------------------------- ### Override Raix Configuration at Class Level in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md This Ruby example shows how to override global Raix configuration settings at a class level. It demonstrates using the `configure` block within a class that includes `Raix::ChatCompletion` to set specific client instances or other options, providing granular control over Raix behavior for individual components. ```ruby class MyClass include Raix::ChatCompletion configure do |config| config.openrouter_client = OpenRouter::Client.new # with my special options end end ``` -------------------------------- ### Configure Raix OpenRouter and OpenAI Clients in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md This Ruby code demonstrates how to configure Raix clients for OpenRouter and OpenAI within an application's initializer. It shows setting up API client instances with access tokens and optional Faraday middleware for retries and logging, essential for connecting Raix to external AI services. ```ruby # config/initializers/raix.rb OpenRouter.configure do |config| config.faraday do |f| f.request :retry, retry_options f.response :logger, Logger.new($stdout), { headers: true, bodies: true, errors: true } do |logger| logger.filter(/(Bearer) (\S+)/, '\1[REDACTED]') end end end Raix.configure do |config| config.openrouter_client = OpenRouter::Client.new(access_token: ENV.fetch("OR_ACCESS_TOKEN", nil)) config.openai_client = OpenAI::Client.new(access_token: ENV.fetch("OAI_ACCESS_TOKEN", nil)) do |f| f.request :retry, retry_options f.response :logger, Logger.new($stdout), { headers: true, bodies: true, errors: true } do |logger| logger.filter(/(Bearer) (\S+)/, '\1[REDACTED]') end end end ``` -------------------------------- ### Raix AI Modules API Reference Source: https://github.com/olympiaai/raix/blob/main/README.md This section provides an API overview of key modules in the Raix library for AI application development. It covers `PromptDeclarations` for defining prompt sequences, `ChatCompletion` for core AI interactions, `FunctionDispatch` for dynamic tool invocation, and `ReplyStream` for managing streamed AI responses. These modules enable flexible and powerful AI conversation flows. ```APIDOC Raix Modules: - Module: PromptDeclarations Description: Provides the ability to declare a "Prompt Chain" (series of prompts to be called in a sequence), and features a declarative, Rails-like DSL. Prompts can be defined inline or delegate to callable prompt objects. Usage: - `prompt call: CallablePromptClass` - `prompt text: -> { user_message.content }, stream: -> { ReplyStream.new(self) }, until: -> { bot_message.complete? }` - Module: ChatCompletion Description: Core module for interacting with AI models (e.g., GPT-4). Callable prompt objects implement this module. Method: `chat_completion(loop: true, openai: "gpt-4o")` - Module: FunctionDispatch Description: Enables dynamic function calling based on AI model's output. Functions are declared with a name, description, and parameters. Method: `function :name, "description", param: { type: "string" } do |arguments| ... end` - Class: ReplyStream Description: Handles the streaming of AI responses to the end user. Passed as a parameter to prompt declarations. ``` -------------------------------- ### Implement Callable AI Prompts with FunctionDispatch in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md This Ruby class, `FetchUrlCheck`, exemplifies a callable prompt that integrates with `ChatCompletion` and `FunctionDispatch`. It's designed to pre-process user messages, specifically checking for URLs using a regex. If a URL is found, it constructs a transcript to call a `fetch` function, demonstrating dynamic tool invocation and result handling within an AI conversation flow. ```Ruby class FetchUrlCheck include ChatCompletion include FunctionDispatch REGEX = %r{\b(?:http(s)?://)?(?:www\.)?[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+(/[^\s]*)?\b} attr_accessor :context, :conversation delegate :user_message, to: :context delegate :content, to: :user_message def initialize(context) self.context = context self.conversation = context.conversation self.model = "anthropic/claude-3-haiku" end def call return unless content&.match?(REGEX) transcript << { system: "Call the `fetch` function if the user mentions a website, otherwise say nil" } transcript << { user: content } chat_completion # TODO: consider looping to fetch more than one URL per user message end function :fetch, "Gets the plain text contents of a web page", url: { type: "string" } do |arguments| Tools::FetchUrl.fetch(arguments[:url]).tap do |result| parent = conversation.function_call!("fetch_url", arguments, parent: user_message) conversation.function_result!("fetch_url", result, parent:) end end end ``` -------------------------------- ### Handle Yes/No/Maybe Questions with Raix Predicate Module in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md The `Raix::Predicate` module simplifies handling AI chat completion for yes/no/maybe questions. It allows defining declarative blocks for each response type (yes, no, maybe) to process the AI's explanation. This module is a concrete pattern for discrete AI components and requires at least one response handler to be defined, otherwise it raises a RuntimeError. ```Ruby class Question include Raix::Predicate yes? do |explanation| puts "Affirmative: #{explanation}" end no? do |explanation| puts "Negative: #{explanation}" end maybe? do |explanation| puts "Uncertain: #{explanation}" end end question = Question.new question.ask("Is Ruby a programming language?") # => Affirmative: Yes, Ruby is a dynamic, object-oriented programming language... ``` ```Ruby class SimpleQuestion include Raix::Predicate # Only handle positive responses yes? do |explanation| puts "✅ #{explanation}" end end question = SimpleQuestion.new question.ask("Is 2 + 2 = 4?") # => ✅ Yes, 2 + 2 equals 4, this is a fundamental mathematical fact. ``` ```Ruby class InvalidQuestion include Raix::Predicate end question = InvalidQuestion.new question.ask("Any question") # => RuntimeError: Please define a yes and/or no block ``` ```APIDOC Raix::Predicate Module Features: - Handlers: yes?, no?, maybe? - Declarative class-level blocks to define callbacks for different response types. - Explanation Argument: Handlers receive the full AI response, including an explanation, as an argument. - Response Format: AI responses always start with "Yes, ", "No, ", or "Maybe, " followed by an explanation. - Handler Requirement: At least one handler (yes, no, or maybe) must be defined. - Question Type: Questions should be answerable with yes, no, or maybe for determinate results. - Error Handling: Raises a RuntimeError if `ask` is called without any defined response handlers. ``` -------------------------------- ### Integrate Raix with Model Context Protocol (MCP) in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md The `Raix::MCP` module provides experimental integration with remote Model Context Protocol (MCP) servers. It allows Raix applications to connect to these servers, automatically fetch available tools, register them as OpenAI-compatible function schemas, and proxy requests. This module depends on `Raix::ChatCompletion` and `Raix::FunctionDispatch` for seamless integration with existing workflows and conversation history. ```Ruby class McpConsumer include Raix::ChatCompletion include Raix::FunctionDispatch include Raix::MCP mcp "https://your-mcp-server.example.com/sse" end ``` ```APIDOC Raix::MCP Module Features: - Server Declaration: `mcp` DSL to declare remote MCP server URLs. - Tool Fetching: Automatically fetches available tools from the remote MCP server using `tools/list` endpoint. - Function Schema Registration: Registers remote tools as OpenAI-compatible function schemas. - Proxy Methods: Defines proxy methods to forward requests to the remote server via `tools/call` endpoint. - Workflow Integration: Seamlessly integrates with existing `FunctionDispatch` workflow. - Transcript Recording: Handles transcript recording to maintain consistent conversation history. - Status: Experimental feature. ``` -------------------------------- ### Define AI Prompt Chains with Raix PromptDeclarations in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md This Ruby snippet demonstrates how to use the `PromptDeclarations` module within a `PromptSubscriber` class to define a sequence of AI prompts. It shows the declaration of callable prompts like `FetchUrlCheck` and `MemoryScan`, followed by a text-based prompt with streaming. The class initializes with a `conversation` object and manages `user_message` and `bot_message` states for the `chat_completion` loop. ```Ruby class PromptSubscriber include Raix::ChatCompletion include Raix::PromptDeclarations attr_accessor :conversation, :bot_message, :user_message # many other declarations omitted... prompt call: FetchUrlCheck prompt call: MemoryScan prompt text: -> { user_message.content }, stream: -> { ReplyStream.new(self) }, until: -> { bot_message.complete? } def initialize(conversation) self.conversation = conversation end def message_created(user_message) self.user_message = user_message self.bot_message = conversation.bot_message!(responding_to: user_message) chat_completion(loop: true, openai: "gpt-4o") end # ... end ``` -------------------------------- ### Raix ResponseFormat Class API Documentation Source: https://github.com/olympiaai/raix/blob/main/README.md This section provides API documentation for the `Raix::ResponseFormat` class, which enables declaring JSON schemas for AI chat completion responses. It details how to define structured outputs, including nested objects and arrays, ensuring AI responses conform to predefined formats. ```APIDOC Class: Raix::ResponseFormat Description: Provides a way to declare a JSON schema for the response format of an AI chat completion, ensuring structured outputs. Features: - Converts Ruby hashes and arrays into JSON schema format. - Supports nested structures and arrays. - Enforces strict validation with `additionalProperties: false`. - Automatically marks all top-level properties as required. - Handles both simple type definitions and complex nested schemas. Constructor: new(schema_name, schema_definition) Parameters: schema_name (String): A unique name for the generated JSON schema. schema_definition (Hash or Array): A Ruby hash or array representing the desired JSON structure and types. Returns: Raix::ResponseFormat instance. Example Usage: format = Raix::ResponseFormat.new("PersonInfo", { name: { type: "string" }, age: { type: "integer" } }) ``` -------------------------------- ### Implement AI Tool/Function Dispatching with Raix Source: https://github.com/olympiaai/raix/blob/main/README.md The `FunctionDispatch` module allows declarative function implementation for AI models. Raix automatically executes requested tool functions, adds results to the transcript, and sends it back to the AI, ensuring seamless integration. The `max_tool_calls` parameter can limit invocations. ```Ruby class WhatIsTheWeather include Raix::ChatCompletion include Raix::FunctionDispatch function :check_weather, "Check the weather for a location", location: { type: "string", required: true } do |arguments| "The weather in #{arguments[:location]} is hot and sunny" end end RSpec.describe WhatIsTheWeather do subject { described_class.new } it "provides a text response after automatically calling weather function" do subject.transcript << { user: "What is the weather in Zipolite, Oaxaca?" } response = subject.chat_completion(openai: "gpt-4o") expect(response).to include("hot and sunny") end end ``` -------------------------------- ### Raix Transcript Standard OpenAI Message Format Source: https://github.com/olympiaai/raix/blob/main/README.md In addition to the abbreviated format, Raix also understands the standard OpenAI message hash format. This format explicitly defines the `role` and `content` keys, offering full compatibility with OpenAI's API specifications. Using this format ensures broader interoperability and consistency with other OpenAI-based tools. ```Ruby transcript << { role: "user", content: "What is the meaning of life?" } ``` -------------------------------- ### Configure Raix PromptDeclarations Options in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md The `PromptDeclarations` module in Raix allows developers to define and customize AI prompt behavior using a declarative DSL. It supports various options like system directives, conditional execution, success callbacks, custom API parameters, looping conditions, raw response retrieval, and direct OpenAI integration. This module depends on `Raix::ChatCompletion` and `Raix::PromptDeclarations`. ```Ruby class CustomPromptExample include Raix::ChatCompletion include Raix::PromptDeclarations # Basic prompt with text prompt text: "Process this input" # Prompt with system directive prompt system: "You are a helpful assistant", text: "Analyze this text" # Prompt with conditions prompt text: "Process this input", if: -> { some_condition }, unless: -> { some_other_condition } # Prompt with success callback prompt text: "Process this input", success: ->(response) { handle_response(response) } # Prompt with custom parameters prompt text: "Process with custom settings", params: { temperature: 0.7, max_tokens: 1000 } # Prompt with until condition for looping prompt text: "Keep processing until complete", until: -> { processing_complete? } # Prompt with raw response prompt text: "Get raw response", raw: true # Prompt using OpenAI directly prompt text: "Use OpenAI", openai: "gpt-4o" end ``` ```Ruby class ContextAwarePrompt include Raix::ChatCompletion include Raix::PromptDeclarations def process_with_context # Access current prompt current_prompt.params[:temperature] # Access previous response last_response chat_completion end end ``` ```APIDOC PromptDeclarations Options: - system: string - Sets a system directive for the prompt. - if: Proc - Controls prompt execution; prompt runs if condition is true. - unless: Proc - Controls prompt execution; prompt runs unless condition is true. - success: Proc - Callback executed upon successful prompt response, receives response as argument. - params: Hash - Custom API parameters (e.g., temperature, max_tokens) applied to the prompt. - until: Proc - Condition for looping; prompt continues until condition is true. - raw: boolean - If true, retrieves the raw API response. - openai: string - Specifies an OpenAI model to use directly (e.g., "gpt-4o"). - stream: boolean - Controls response streaming behavior. - call: callable - Delegates to callable prompt objects. - current_prompt: Raix::Prompt - Accesses the current prompt context. - last_response: Raix::Response - Accesses the previous AI response. ``` -------------------------------- ### Handle Multiple AI Tool Calls Sequentially in Raix Source: https://github.com/olympiaai/raix/blob/main/README.md Raix automatically handles multiple tool calls made by AI models (e.g., GPT-4) in a single response by executing them sequentially. The `chat_completion` method always returns the final text response, while function arguments can be captured within the function block. ```Ruby class MultipleToolExample include Raix::ChatCompletion include Raix::FunctionDispatch attr_reader :invocations function :first_tool do |arguments| @invocations << :first "Result from first tool" end function :second_tool do |arguments| @invocations << :second "Result from second tool" end def initialize @invocations = [] end end example = MultipleToolExample.new example.transcript << { user: "Please use both tools" } example.chat_completion(openai: "gpt-4o") ``` -------------------------------- ### Implement Predicted Outputs with Raix and OpenAI Source: https://github.com/olympiaai/raix/blob/main/README.md Raix supports OpenAI's Predicted Outputs feature, which can help optimize latency. This is enabled by passing a `prediction` parameter within the `params` hash to the `chat_completion` method. This allows applications to leverage OpenAI's capabilities for faster response generation where applicable. ```Ruby ai.chat_completion(openai: "gpt-4o", params: { prediction: }) ``` -------------------------------- ### Raix::FunctionDispatch#function DSL Reference Source: https://github.com/olympiaai/raix/blob/main/README.md Defines a function that can be called by the AI. This method is part of the `Raix::FunctionDispatch` module, allowing declarative function implementation. It specifies the function's name, description, and expected parameters. ```APIDOC Method: function(name, description, parameters = {}, &block) Parameters: - name: Symbol - The name of the function (e.g., :check_weather). - description: String - A human-readable description of the function's purpose. - parameters: Hash - (Optional) A hash defining the function's arguments. Each key is a parameter name (Symbol), and its value is a hash specifying 'type' (String, e.g., "string", "integer") and 'required' (Boolean, default false). - &block: Proc - The Ruby block to execute when the function is called. It receives a hash of 'arguments' as its parameter. Return Value: The return value of the block is added to the conversation transcript. ``` -------------------------------- ### Configure Prompt Caching with Raix and Anthropic Source: https://github.com/olympiaai/raix/blob/main/README.md Raix facilitates Anthropic-style prompt caching when using Claude models by allowing a `cache_at` parameter in the `chat_completion` call. If a message's content exceeds the `cache_at` character count, it's sent as a multipart message with an 'ephemeral' cache control breakpoint. Note that there's a limit of four breakpoints and a five-minute cache expiration, so it's recommended for large text bodies like RAG data or character cards. ```Ruby my_class.chat_completion(params: { cache_at: 1000 }) ``` ```APIDOC { "messages": [ { "role": "system", "content": [ { "type": "text", "text": "HUGE TEXT BODY LONGER THAN 1000 CHARACTERS", "cache_control": { "type": "ephemeral" } } ] } ] } ``` -------------------------------- ### Enable JSON Mode for Structured AI Responses in Raix Source: https://github.com/olympiaai/raix/blob/main/README.md Raix simplifies obtaining structured JSON data from AI models. For OpenAI models, it automatically sets `response_format`. For other models, it expects JSON within XML tags. This ensures the entire response body is parsed as JSON. ```Ruby >> my_class.chat_completion(json: true) => { "key": "value" } ``` ```Ruby >> my_class.chat_completion(json: true, openai: "gpt-4o") => { "key": "value" } ``` -------------------------------- ### Cache Raix Function Call Results with ActiveSupport Source: https://github.com/olympiaai/raix/blob/main/README.md Implement caching for Raix function call results using ActiveSupport's Cache to improve performance for expensive or frequently called operations. This mechanism uses the function name and arguments as cache keys, automatically fetching or executing as needed. ```Ruby class CachedFunctionExample include Raix::ChatCompletion include Raix::FunctionDispatch function :expensive_operation do |arguments| "Result of expensive operation with #{arguments}" end # Override dispatch_tool_function to enable caching for all functions def dispatch_tool_function(function_name, arguments) # Pass the cache to the superclass implementation super(function_name, arguments, cache: Rails.cache) end end ``` -------------------------------- ### Control AI Tool Exposure with Raix Tool Filtering Source: https://github.com/olympiaai/raix/blob/main/README.md Raix allows granular control over which tool functions are exposed to the AI using the `available_tools` parameter. You can disable all tools, pass specific tools, or allow all declared tools. This prevents unintended function invocations and enhances security. ```Ruby class WeatherAndTime include Raix::ChatCompletion include Raix::FunctionDispatch function :check_weather, "Check the weather for a location", location: { type: "string" } do |arguments| "The weather in #{arguments[:location]} is sunny" end function :get_time, "Get the current time" do |_arguments| "The time is 12:00 PM" end end weather = WeatherAndTime.new # Don't pass any tools to the LLM weather.chat_completion(available_tools: false) # Only pass specific tools to the LLM weather.chat_completion(available_tools: [:check_weather]) # Pass all declared tools (default behavior) weather.chat_completion ``` -------------------------------- ### Define Complex JSON Schemas with Raix ResponseFormat in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md This Ruby snippet illustrates how to define complex, nested JSON schemas using `Raix::ResponseFormat`. It demonstrates handling arrays of objects and arrays of strings within a hierarchical structure, useful for generating detailed AI responses like 'CompanyInfo' with employees and locations. ```ruby # Nested structure with arrays format = Raix::ResponseFormat.new("CompanyInfo", { company: { name: { type: "string" }, employees: [ { name: { type: "string" }, role: { type: "string" }, skills: ["string"] } ], locations: ["string"] } }) ``` -------------------------------- ### Raix Transcript Abbreviated Message Format Source: https://github.com/olympiaai/raix/blob/main/README.md The Raix transcript supports an abbreviated message format for system, assistant, and user messages. This simplified format maps the role directly to its content, providing a concise way to add messages to the conversation history. It's a convenient shorthand for common message types. ```Ruby transcript << { user: "What is the meaning of life?" } ``` -------------------------------- ### Filter Remote Tools in Raix Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md This Ruby snippet demonstrates how to include or exclude specific remote tools when using Raix's `mcp` method. It allows fine-grained control over which tools are available for chat completion and function dispatch, enhancing security and relevance. ```ruby class FilteredMcpConsumer include Raix::ChatCompletion include Raix::FunctionDispatch include Raix::MCP # Only include specific tools mcp "https://server.example.com/sse", only: [:tool_one, :tool_two] # Or exclude specific tools mcp "https://server.example.com/sse", except: [:tool_to_exclude] end ``` -------------------------------- ### Customize Raix Function Dispatch in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md Override the 'dispatch_tool_function' method in your class to add custom logic around function calls, such as logging, caching, or error handling. This allows for centralized control over how Raix executes its defined tools. ```Ruby class CustomDispatchExample include Raix::ChatCompletion include Raix::FunctionDispatch function :example_tool do |arguments| "Result from example tool" end def dispatch_tool_function(function_name, arguments) puts "Calling #{function_name} with #{arguments}" result = super puts "Result: #{result}" result end end ``` -------------------------------- ### Limit Maximum Raix Tool Calls in Ruby Source: https://github.com/olympiaai/raix/blob/main/README.md Control the maximum number of consecutive tool calls an AI can make before it must provide a text response. This limit can be set per-response or configured globally for all Raix chat completions. ```Ruby # Limit to 5 tool calls (default is 25) response = my_ai.chat_completion(max_tool_calls: 5) # Configure globally Raix.configure do |config| config.max_tool_calls = 10 end ``` -------------------------------- ### Manually Stop Raix Tool Calls and Force AI Response Source: https://github.com/olympiaai/raix/blob/main/README.md Use 'stop_tool_calls_and_respond!' within a function to explicitly force the AI to cease further tool calls and generate a text response. This is particularly useful for automated processes where a definitive end to tool execution is required. ```Ruby class OrderProcessor include Raix::ChatCompletion include Raix::FunctionDispatch SYSTEM_DIRECTIVE = "You are an order processor, tasked with order validation, inventory check, payment processing, and shipping." attr_accessor :order def initialize(order) self.order = order transcript << { system: SYSTEM_DIRECTIVE } transcript << { user: order.to_json } end def perform # will automatically continue after tool calls until finished_processing is called chat_completion end # implementation of functions that can be called by the AI # entirely at its discretion, depending on the needs of the order. # The return value of each `perform` method will be added to the # transcript of the conversation as a function result. function :validate_order do OrderValidationWorker.perform(@order) end function :check_inventory do InventoryCheckWorker.perform(@order) end function :process_payment do PaymentProcessingWorker.perform(@order) end function :schedule_shipping do ShippingSchedulerWorker.perform(@order) end function :send_confirmation do OrderConfirmationWorker.perform(@order) end function :finished_processing do order.update!(transcript:, processed_at: Time.current) stop_tool_calls_and_respond! "Order processing completed successfully" end end ``` -------------------------------- ### Control Raix Chat Completion Response Saving Source: https://github.com/olympiaai/raix/blob/main/README.md By default, Raix automatically adds the AI's response to the transcript. This behavior can be controlled using the `save_response` parameter, which defaults to `true`. Setting `save_response` to `false` is useful when managing transcript updates manually, especially during multiple sequential or parallel chat completion calls within a single object's lifecycle. ```Ruby ai.chat_completion(save_response: false) ``` -------------------------------- ### Override Raix Transcript with Messages Parameter Source: https://github.com/olympiaai/raix/blob/main/README.md It's possible to override the current object's transcript by passing a `messages` array directly to the `chat_completion` method. This feature is particularly useful for scenarios where multiple threads or contexts need to share a single conversation without immediately writing responses back to the main transcript. It allows for deferred transcript updates and parallel conversation management. ```Ruby chat_completion(openai: "gpt-4.1-nano", messages: [{ user: "What is the meaning of life?" }]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.