💎 ChatSDK Ruby

API: AI

ChatSDK::AI provides utilities for integrating LLMs with chat -- message conversion, tool definitions, tool execution, and streaming.

ChatSDK::AI provides utilities for integrating LLMs with the chat SDK. It handles converting chat messages to AI-friendly formats, generating tool definitions for function calling, executing tool calls, and streaming AI responses into threads.

Module Methods

AI.to_ai_messages(messages, include_names: false, &transform)

Converts an array of ChatSDK::Message objects into the [{role:, content:}] format used by LLM APIs.

messages = thread.messages(limit: 50)
ai_messages = ChatSDK::AI.to_ai_messages(messages, include_names: true)
# => [{role: "user", content: "[Alice]: hello"}, {role: "assistant", content: "Hi!"}]
ParameterTypeRequiredDefaultDescription
messagesArray<Message>Yes--Chat messages to convert
include_namesBooleanNofalsePrefix user messages with [author_name]:
&transformBlockNo--Optional block |hash, message| to transform each converted hash

Messages are sorted by timestamp (falling back to id), and blank messages are filtered out. Bot authors produce "assistant" role; all others produce "user" role.

When messages have attachments, the content field becomes a multipart array with text and attachment parts (images get type: "image", other files get type: "file").

The optional block receives each converted hash and the original message, and should return the (possibly modified) hash, or nil to skip the message.

AI.create_tools(preset: :messenger, require_approval: true)

Generates a hash of tool definitions suitable for LLM function calling.

tools = ChatSDK::AI.create_tools(preset: :messenger)
# Pass to your LLM client as tool/function definitions
ParameterTypeRequiredDefaultDescription
presetSymbolNo:messengerTool preset (see presets below)
require_approvalBooleanNotrueWhether write tools require user approval

Returns Hash{Symbol => Hash} where each value contains :description, :parameters, :read_only, and :requires_approval.

AI.create_executor(chat:)

Creates a ToolExecutor that can execute tool calls against a Chat instance.

executor = ChatSDK::AI.create_executor(chat: chat)
result = executor.execute(:post_message, {
  adapter_name: "slack",
  channel_id: "C123",
  text: "Hello from AI!"
})
ParameterTypeRequiredDescription
chatChatYesThe Chat instance to execute tools against

Returns a ChatSDK::AI::ToolExecutor instance.

AI::Converter

Handles the conversion logic used by AI.to_ai_messages.

Constants

ConstantValueDescription
ROLE_USER"user"Role for human users
ROLE_ASSISTANT"assistant"Role for bot authors

Attachment Handling

Attachments are converted to multipart content:

  • Image attachments (MIME type starting with image/): {type: "image", url: ..., media_type: ...}
  • File attachments: {type: "file", url: ..., filename: ..., media_type: ...}
  • Other: {type: "text", text: attachment.to_s}

AI::ToolBuilder

Builds tool definition hashes from presets.

Presets

PresetTools Included
:readerfetch_messages, fetch_thread
:messengerfetch_messages, fetch_thread, post_message, send_direct_message, add_reaction, start_typing
:moderatorfetch_messages, fetch_thread, post_message, send_direct_message, add_reaction, edit_message, delete_message, remove_reaction, start_typing

Tool Definitions

ToolDescriptionRead-only
fetch_messagesFetch recent messages from a channel or threadYes
fetch_threadFetch all messages in a specific threadYes
post_messagePost a message to a channel or threadNo
send_direct_messageSend a direct message to a userNo
edit_messageEdit an existing messageNo
delete_messageDelete a messageNo
add_reactionAdd an emoji reaction to a messageNo
remove_reactionRemove an emoji reaction from a messageNo
start_typingShow typing indicator in a channelNo

When require_approval: true (the default), write tools (non-read-only) have requires_approval: true set.

AI::ToolExecutor

Executes tool calls against a Chat instance.

Constructor

ChatSDK::AI::ToolExecutor.new(chat: chat)

Instance Methods

execute(tool_name, arguments)

Executes a tool call and returns a result hash.

result = executor.execute(:fetch_messages, {
  adapter_name: "slack",
  channel_id: "C123",
  limit: 10
})
# => [{id: "msg1", text: "hello", author: "Alice", timestamp: ...}, ...]
ParameterTypeRequiredDescription
tool_nameSymbol or StringYesName of the tool to execute
argumentsHashYesTool arguments (keys can be strings or symbols)

Raises ChatSDK::Error if the tool name is unknown.

Return values by tool:

ToolReturns
fetch_messagesArray<{id:, text:, author:, timestamp:}>
fetch_threadArray<{id:, text:, author:, timestamp:}>
post_message{id:, text:}
send_direct_message{id:, channel_id:}
edit_message{success: true}
delete_message{success: true}
add_reaction{success: true}
remove_reaction{success: true}
start_typing{success: true}

AI::StreamHandler

Streams AI output into a chat thread.

StreamHandler.stream_to_thread(thread, enumerable, placeholder: "Thinking...")

Convenience method that pipes an enumerable of string chunks through Thread#post_stream.

chunks = my_ai_client.chat_stream(messages: ai_messages)
ChatSDK::AI::StreamHandler.stream_to_thread(thread, chunks, placeholder: "Thinking...")
ParameterTypeRequiredDefaultDescription
threadThreadYes--Target thread
enumerableEnumerableYes--Yields string chunks
placeholderStringNo"Thinking..."Initial placeholder message

This is the method called by Thread#post_ai_stream.

On this page