DEV Community

Germán Alberto Gimenez Silva
Germán Alberto Gimenez Silva

Posted on • Originally published at rubystacknews.com on

Build a Complete AI Chatbot with DeepSeek and Ruby – Full Code and Guide!

March 11, 2025

Introduction

Artificial Intelligence (AI) chatbots are transforming the way we interact with technology, and with tools like DeepSeek, building an intelligent chatbot has never been easier. In this article, we’ll walk through constructing a full-fledged AI chatbot using Ruby and the DeepSeek API. You’ll get a working chatbot, complete with conversation history and a configuration manager, along with code examples to guide you step by step.


🚀 Want to Integrate AI Chat into Your Project?🚀

Looking to add an intelligent AI-powered chatbot to your application? Whether it’s for customer support, automation, or interactive experiences, I can help you build and integrate a powerful AI chat system.

📩 Let’s connect! Reach out here: Get in Touch


Why DeepSeek for AI Chatbots?

DeepSeek provides a powerful AI-driven language model that can generate human-like responses, making it a great choice for chatbot development. With an easy-to-use API, you can integrate DeepSeek into any application to enable conversational AI capabilities.

Setting Up the Chatbot

1. Install Dependencies

To get started, install the necessary Ruby gems:

 gem install faraday json yaml 
Enter fullscreen mode Exit fullscreen mode

These libraries help with HTTP requests, data formatting, and configuration management.

2. Create a Configuration Manager

We need a way to store and manage chatbot settings. The following ConfigManager class reads and updates a YAML configuration file:

require 'yaml'

class ConfigManager
  CONFIG_FILE = 'deepseek_config.yml'

  def self.load
    config = { model: "deepseek-chat" }
    config.merge!(YAML.load_file(CONFIG_FILE)) if File.exist?(CONFIG_FILE)
    File.write(CONFIG_FILE, config.to_yaml) unless File.exist?(CONFIG_FILE)
    config
  end

  def self.update(new_config)
    updated = load.merge(new_config)
    File.write(CONFIG_FILE, updated.to_yaml)
    updated
  end
end 
Enter fullscreen mode Exit fullscreen mode

3. Implement the DeepSeek API Client

The DeepSeekClient class handles API requests, conversation history, and responses:

require 'faraday'
require 'json'

class DeepSeekClient
  API_URL = 'https://api.deepseek.com/v1/chat/completions'

  def initialize(api_key)
    @api_key = api_key
    @conversation_history = []
  end

  def send_prompt(prompt, temperature: 0.7, max_tokens: 500)
    @conversation_history << { role: 'user', content: prompt }
    body = { model: ConfigManager.load[:model], messages: @conversation_history }.to_json
    response = Faraday.post(API_URL, body, headers)

    if response.success?
      ai_response = JSON.parse(response.body)['choices'][0]['message']['content']
      @conversation_history << { role: 'assistant', content: ai_response }
      ai_response
    else
      handle_error(response)
    end
  end

  private

  def headers
    { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{@api_key}" }
  end

  def handle_error(response)
    case response.status
    when 429 then "Error: Rate limit exceeded."
    when 401 then "Error: Invalid API key."
    else "Error: #{response.status} - #{response.body}"
    end
  end
end 
Enter fullscreen mode Exit fullscreen mode

4. Build an Interactive Command Line Interface (CLI)

To interact with the chatbot, we’ll create a simple CLI interface:

class DeepSeekCLI
  def initialize(api_key)
    @client = DeepSeekClient.new(api_key)
    @config = ConfigManager.load
  end

  def start
    loop do
      print "\nYou: "
      input = gets.chomp
      break if input.downcase == 'exit'
      response = @client.send_prompt(input, temperature: @config[:temperature], max_tokens: @config[:max_tokens])
      puts "\nDeepSeek: #{response}"
    end
  end
end

DEEPSEEK_API_KEY = 'your_api_key_here'
cli = DeepSeekCLI.new(DEEPSEEK_API_KEY)
cli.start 
Enter fullscreen mode Exit fullscreen mode

Running the Chatbot

  1. Save the chatbot script as chatbot.rb.
  2. Create a YAML config file (deepseek_config.yml) with initial values:
:model: deepseek-chat
:temperature: 0.7
:max_tokens: 500 
Enter fullscreen mode Exit fullscreen mode
  1. Run the chatbot:
ruby chatbot.rb 
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this guide, we built a fully functional AI chatbot using Ruby and DeepSeek. We covered everything from configuration management to API integration and user interaction via a CLI. This chatbot can be further enhanced with features like memory persistence, custom prompts, and integration into web applications.

Try building your own chatbot today and enhance your AI development skills!

Complete functional Code:

require 'faraday'
require 'json'
require 'yaml'

# Configuration Manager
class ConfigManager
  CONFIG_FILE = 'deepseek_config.yml'

  def self.load
    config = {
        model: "deepseek-chat"
    }

    if File.exist?(CONFIG_FILE)
      config.merge!(YAML.load_file(CONFIG_FILE))
    else
      File.write(CONFIG_FILE, config.to_yaml)
    end
    config
  end

  def self.update(new_config)
    current = load
    updated = current.merge(new_config)
    File.write(CONFIG_FILE, updated.to_yaml)
    updated
  end
end

# AI Client with Conversation History
class DeepSeekClient
  API_URL = 'https://api.deepseek.com/v1/chat/completions'

  def initialize(api_key)
    @api_key = api_key
    @conversation_history = []
  end

  def send_prompt(prompt, temperature: 0.7, max_tokens: 500)
    @conversation_history << { role: 'user', content: prompt }

    body = {
      model: ConfigManager.load[:model],
      messages: @conversation_history
    }.to_json

    response = Faraday.post(API_URL, body, headers)

    if response.success?
      ai_response = JSON.parse(response.body)['choices'][0]['message']['content']
      @conversation_history << { role: 'assistant', content: ai_response }
      ai_response
    else
      handle_error(response)
    end
  end

  private

  def headers
    {
      'Content-Type' => 'application/json',
      'Authorization' => "Bearer #{@api_key}"
    }
  end

  def handle_error(response)
    case response.status
    when 429 then "Error: Rate limit exceeded. Wait before retrying."
    when 401 then "Error: Invalid API key."
    else "Error: #{response.status} - #{response.body}"
    end
  end
end

# Interactive CLI Interface
class DeepSeekCLI
  def initialize(api_key)
    @client = DeepSeekClient.new(api_key)
    @config = ConfigManager.load
  end

  def start
    loop do
      print "\nYou: "
      input = gets.chomp
      break if input.downcase == 'exit'

      handle_special_commands(input)
      process_input(input)
    end
  end

  private

  def process_input(input)
    response = @client.send_prompt(input, temperature: @config[:temperature], max_tokens: @config[:max_tokens])
    puts "\nDeepSeek: #{response}"
  end

  def handle_special_commands(input)
    case input
    when '/config'
      update_configuration
    when '/reset'
      @client.reset_conversation
      puts "Conversation history cleared."
    when '/help'
      show_help
    end
  end

  def update_configuration
    puts "Update settings (leave blank to keep current):"
    new_temp = ask("Temperature (0.0-1.0): ", @config[:temperature])
    new_tokens = ask("Max tokens: ", @config[:max_tokens])

    ConfigManager.update(
      temperature: new_temp.to_f,
      max_tokens: new_tokens.to_i
    )
    @config = ConfigManager.load
    puts "Configuration updated!"
  end

  def ask(prompt, default)
    print "#{prompt}[#{default}]: "
    input = gets.chomp
    input.empty? ? default : input
  end

  def show_help
    puts <<~HELP
      Commands:
      /config - Adjust settings
      /reset - Clear conversation history
      /help - Show this menu
      exit - Quit the program
    HELP
  end
end

# Run the CLI
DEEPSEEK_API_KEY = '<TOKEN>'

cli = DeepSeekCLI.new(DEEPSEEK_API_KEY)
cli.start
Enter fullscreen mode Exit fullscreen mode

Need Expert Ruby on Rails Developers to Elevate Your Project?

Fill out our form! >>


Need Expert Ruby on Rails Developers to Elevate Your Project?

Top comments (0)