Translation Agent
The Translation Agent demonstrates how to create specialized agents for specific tasks like language translation.
Setup
Generate a translation agent:
bash
rails generate active_agent:agent translation translate
Implementation
ruby
class TranslationAgent < ApplicationAgent
generate_with :openai, instructions: "Translate the given text from one language to another."
def translate
prompt
end
end
Usage Examples
Basic Translation
The translation agent accepts a message and target locale:
ruby
translate_prompt = TranslationAgent.with(message: "Hi, I'm Justin", locale: "japanese").translate
assert_equal "translate: Hi, I'm Justin; to japanese\n", translate_prompt.message.content
assert_equal "Translate the given text from one language to another.", translate_prompt.instructions
Translation Generation
Generate a translation using the configured AI provider:
ruby
response = TranslationAgent.with(
message: "Hi, I'm Justin",
locale: "japanese"
).translate.generate_now
assert_equal "こんにちは、私はジャスティンです。", response.message.content
Response Example
activeagent/test/agents/translation_agent_test.rb:23
ruby
# Response object
#<ActiveAgent::GenerationProvider::Response:0x39a8
@message=#<ActiveAgent::ActionPrompt::Message:0x39bc
@action_id=nil,
@action_name=nil,
@action_requested=false,
@charset="UTF-8",
@content="こんにちは、私はジャスティンです。",
@role=:assistant>
@prompt=#<ActiveAgent::ActionPrompt::Prompt:0x39d0 ...>
@content_type="text/plain"
@raw_response={...}>
# Message content
response.message.content # => "こんにちは、私はジャスティンです。"
Key Features
- Action-based Translation: Use the
translate
action to process translations - Locale Support: Pass target language as a parameter
- Prompt Templates: Customize translation prompts through view templates
- Instruction Override: Define custom translation instructions per agent
View Templates
The translation agent uses view templates to format prompts:
erb
translate: <%= params[:message] %>; to <%= params[:locale] %>