Class: Rack::AI::Providers::OpenAI

Inherits:
Base
  • Object
show all
Defined in:
lib/rack/ai/providers/openai.rb

Constant Summary collapse

API_BASE_URL =
"https://api.openai.com/v1"

Instance Attribute Summary

Attributes inherited from Base

#config

Instance Method Summary collapse

Methods inherited from Base

#build_request_data, #healthy?, #validate!

Constructor Details

#initialize(config) ⇒ OpenAI

Returns a new instance of OpenAI.



13
14
15
16
# File 'lib/rack/ai/providers/openai.rb', line 13

def initialize(config)
  super
  @client = build_client
end

Instance Method Details

#analyze_patterns(data) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/rack/ai/providers/openai.rb', line 73

def analyze_patterns(data)
  prompt = build_pattern_analysis_prompt(data)
  
  response = @client.post("chat/completions") do |req|
    req.body = {
      model: "gpt-3.5-turbo",
      messages: [
        {
          role: "system",
          content: "You are a traffic pattern analyst. Analyze the provided request patterns and identify anomalies, trends, and recommendations. Respond with JSON."
        },
        {
          role: "user",
          content: prompt
        }
      ],
      temperature: 0.2,
      max_tokens: 500
    }.to_json
  end

  handle_api_error(response) unless response.success?
  
  result = JSON.parse(response.body)
  content = JSON.parse(result.dig("choices", 0, "message", "content") || "{}")
  
  {
    anomalies: content["anomalies"] || [],
    trends: content["trends"] || [],
    recommendations: content["recommendations"] || [],
    confidence: content["confidence"] || 0.0,
    provider: :openai
  }
end

#classify_request(data) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rack/ai/providers/openai.rb', line 18

def classify_request(data)
  prompt = build_classification_prompt(data)
  
  response = @client.post("chat/completions") do |req|
    req.body = {
      model: "gpt-3.5-turbo",
      messages: [
        {
          role: "system",
          content: "You are a web request classifier. Analyze the request and classify it as one of: human, bot, spam, suspicious. Respond with JSON containing 'classification' and 'confidence' (0-1)."
        },
        {
          role: "user",
          content: prompt
        }
      ],
      temperature: 0.1,
      max_tokens: 100
    }.to_json
  end

  handle_api_error(response) unless response.success?
  
  result = JSON.parse(response.body)
  content = JSON.parse(result.dig("choices", 0, "message", "content") || "{}")
  
  {
    classification: content["classification"]&.to_sym || :unknown,
    confidence: content["confidence"] || 0.0,
    reasoning: content["reasoning"],
    provider: :openai
  }
end

#detect_anomalies(request_data) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/rack/ai/providers/openai.rb', line 108

def detect_anomalies(request_data)
  prompt = build_anomaly_detection_prompt(request_data)
  
  response = @client.post("chat/completions") do |req|
    req.body = {
      model: "gpt-3.5-turbo",
      messages: [
        {
          role: "system",
          content: "You are a security analyst. Detect potential security threats, anomalies, or suspicious patterns in web requests. Respond with JSON containing 'threat_level' (low/medium/high), 'anomalies', and 'confidence'."
        },
        {
          role: "user",
          content: prompt
        }
      ],
      temperature: 0.1,
      max_tokens: 200
    }.to_json
  end

  handle_api_error(response) unless response.success?
  
  result = JSON.parse(response.body)
  content = JSON.parse(result.dig("choices", 0, "message", "content") || "{}")
  
  {
    threat_level: content["threat_level"]&.to_sym || :low,
    anomalies: content["anomalies"] || [],
    confidence: content["confidence"] || 0.0,
    provider: :openai
  }
end

#enhance_content(content, enhancement_type) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/rack/ai/providers/openai.rb', line 142

def enhance_content(content, enhancement_type)
  prompt = build_enhancement_prompt(content, enhancement_type)
  
  response = @client.post("chat/completions") do |req|
    req.body = {
      model: "gpt-3.5-turbo",
      messages: [
        {
          role: "system",
          content: "You are a content enhancement assistant. Improve the provided content based on the specified enhancement type."
        },
        {
          role: "user",
          content: prompt
        }
      ],
      temperature: 0.3,
      max_tokens: 1000
    }.to_json
  end

  handle_api_error(response) unless response.success?
  
  result = JSON.parse(response.body)
  enhanced_content = result.dig("choices", 0, "message", "content")
  
  {
    original_content: content,
    enhanced_content: enhanced_content,
    enhancement_type: enhancement_type,
    provider: :openai
  }
end

#moderate_content(content, options = {}) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/rack/ai/providers/openai.rb', line 52

def moderate_content(content, options = {})
  response = @client.post("moderations") do |req|
    req.body = {
      input: content,
      model: "text-moderation-latest"
    }.to_json
  end

  handle_api_error(response) unless response.success?
  
  result = JSON.parse(response.body)
  moderation_result = result["results"]&.first || {}
  
  {
    flagged: moderation_result["flagged"] || false,
    categories: moderation_result["categories"] || {},
    category_scores: moderation_result["category_scores"] || {},
    provider: :openai
  }
end

#pingObject



176
177
178
179
# File 'lib/rack/ai/providers/openai.rb', line 176

def ping
  response = @client.get("models")
  response.success?
end