DEV Community

Cover image for AI Helps Learning
Pam
Pam

Posted on

1

AI Helps Learning

This is a submission for the Agent.ai Challenge: Assembly of Agents (See Details)

What I Built

AI as an Educational Tool

  • I am all about learning and creating roadmaps on how to best learn a topic. I used ruby/rails to implement an ai agent and the ruby-openai gem to access openAI's API token. I then created models to represent agents and their interactions as well as creating a controller and service to handle requests and invoke AI agents.
  • I used Hotwire, turbo for the frontend.
class AiAgentsController < ApplicationController
  def new
  end

  def invoke_agent
    user_query = params[:query]
    begin
      @ai_response = AiService.invoke_agent(user_query)
      Query.create(user_query: user_query, ai_response: @ai_response)

      respond_to do |format|
        format.turbo_stream
        format.html { redirect_to root_path, notice: "Query processed successfully" }
      end
    rescue StandardError => e
      error_message = e.message
      Rails.logger.error("AI Agent Error: #{error_message}")

      respond_to do |format|
        format.turbo_stream { 
          render turbo_stream: turbo_stream.update("response_frame", 
            partial: "error", 
            locals: { message: error_message })
        }
        format.html { redirect_to root_path, alert: error_message }
      end
    end
  end

  def index
    @queries = Query.all
  end
end
Enter fullscreen mode Exit fullscreen mode
require 'openai'

class AiService
  class RateLimitError < StandardError; end
  MAX_RETRIES = 3
  BASE_WAIT_TIME = 10  # Increased base wait time

  def self.invoke_agent(query)
    retries = 0
    begin
      client = OpenAI::Client.new(access_token: ENV['OPENAI_API_KEY'])

      response = client.chat(
        parameters: {
          model: "gpt-4o-mini",
          messages: [
            { role: "system", content: "You are a helpful assistant" },
            { role: "user", content: query }
          ],
          max_tokens: 150,
          temperature: 0.7
        }
      )

      response.dig("choices", 0, "message", "content").to_s.strip
    rescue Faraday::TooManyRequestsError => e
      retries += 1
      if retries <= MAX_RETRIES
        wait_time = BASE_WAIT_TIME * retries  # Linear backoff: 10, 20, 30 seconds
        Rails.logger.warn("Rate limit hit (#{retries}/#{MAX_RETRIES}). Waiting #{wait_time} seconds...")
        sleep(wait_time)
        retry
      else
        Rails.logger.error("Rate limit exceeded. Response: #{e.response&.body}")
        raise RateLimitError, "Please wait a few minutes before trying again"
      end
    rescue StandardError => e
      Rails.logger.error("OpenAI Error: #{e.class} - #{e.message}")
      raise "API Error: #{e.message}"
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Demo

https://github.com/PamBWillenz/Ai-agent
I used ruby/rails to implement an ai agent.

Home
Image description
Query
Image description
Query Answers
Image description

Agent.ai Experience

  • Not as intuitive as I thought. I used the platform openai.com. I built my ai agent in ruby/rails and the API key was harder to set up then I thought it would be.
  • I had to save the key in .env but initiating it was more complex.
  • The instructions were not clear for the language and framework I was using.

Was the builder tool intuitive and easy to use?
Were the instructions and documentation clear?

  • No, not exactly. The API key that was generated was in a different format and there were no examples for the framework/language I was using. After many attempts I finally used a curl command to get my framework to connect properly to the AI agent. I used a gem (library in rails) to make the AI api connection.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay