Zenn Tech Blog

iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💬

Combating the Surge of Spam on Zenn with LLMs

に公開
2024/10/28
2件
Inside Zennの記事です

Introduction

Hi, I'm Yoshikawa (dyoshikawa) from the Zenn team.

Since around June 2024, Zenn experienced a sudden surge in spam posts. To address this, I built an automated spam detection system using LLMs (Large Language Models).

Due to the nature of the objective, I cannot disclose too many details. However, I would like to share the overview of this project to provide technical insights and because I want to be as open as possible with the community about our team's efforts.

The Challenge

Around June 2024, spam posts on Zenn increased rapidly. As a result, the number of violation reports from users rose, which made us, the Zenn operation team, aware of the situation.

We wanted to avoid a scenario where spam posts became a constant sight for our readers, and we were also mindful of the significant burden on users who were taking the time to report violations each time. Therefore, we decided to proceed with countermeasures.

The Solution

We concluded that we needed a mechanism to detect spam posts automatically to some extent. That is why we decided to leverage LLMs.

I have no background in machine learning or natural language processing, but with an LLM, I can create a detection system with a certain level of quality just by crafting prompts in natural language. This is one of the truly revolutionary aspects of LLMs 👍

However, since this initiative is not about developing the core value of Zenn, I wanted to minimize the effort as much as possible. I also wanted to get as close to zero as possible for cases where legitimate articles that shouldn't be flagged are incorrectly identified as spam and taken down. Thus, we decided to utilize our existing violation reporting function.

An LLM crawls published content and generates a violation report if it determines the content is spam. Then, operation team members check both the report and the actual content from the management console to confirm whether it is truly a spam post (in accordance with our terms of service). By involving human judgment, we can reduce the risk of false positives from the LLM.

In this way, we were able to incorporate spam countermeasures without significantly changing our existing routine operations.

Management Console Capture
Violation reports created by the LLM (AI)

Model Selection

Since Zenn is primarily built on Google Cloud, we decided to use the Vertex AI platform. We believe that if you can consolidate resource building into a single cloud service, it makes managing IaC and IAM permissions easier.

When you think of Google LLMs, Gemini comes to mind, but this time we selected Anthropic Claude.

https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude?hl=en

There wasn't a strong underlying intention behind the selection. It was simply that our company has experience with Amazon Bedrock + Claude for other generative AI projects outside the Zenn team, and we thought that by selecting Claude here as well, we might be able to share operational and prompting expertise within the company (so we might change it in the future).

Using Vertex AI from a Rails Application

Zenn's backend runs on Ruby on Rails. We judged that it wasn't necessary to build a separate server in a different programming language for this purpose, so we adopted a configuration to use Vertex AI from Rails.

Required IAM Permissions

https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude?hl=en

You need to attach the aiplatform.endpoints.predict permission.

Region

https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude?hl=en#anthropic_claude_region_availability

According to the documentation, regional availability is as follows:

Model Region
Claude 3 Sonnet us-central1 (Iowa)
Claude 3 Sonnet asia-southeast1 (Singapore)
Claude 3 Haiku us-central1 (Iowa)
Claude 3 Haiku europe-west4 (Netherlands)

It is not yet available in the Tokyo region (asia-northeast1), so you must select regions like us-central1.

Calling the Vertex AI Claude API from Ruby

https://console.cloud.google.com/vertex-ai/publishers/anthropic/model-garden/claude-3-haiku

There are Anthropic SDKs available for Python and TypeScript.

According to this, the SDK does not appear to be available when using Ruby. You will need to construct the API requests without using an SDK.

Fortunately, an example of how to make requests using curl is provided above. It looks like this:

PROJECT_ID=your-gcp-project-id
MODEL=claude-3-haiku@20240307

# Pick one region:
LOCATION=us-central1
# LOCATION=europe-west4

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json; charset=utf-8" \
  -d @request.json \
"https://$LOCATION-aiplatform.googleapis.com/v1/projects/$PROJECT_ID/locations/$LOCATION/publishers/anthropic/models/$MODEL:streamRawPredict"

Basically, you will assemble the code to make HTTP(S) requests in Ruby while referring to this. Additionally, you need to consider how to obtain the access token from $(gcloud auth print-access-token) within your application.

There are several ways to do this. This article introduces how to use ADC (Application Default Credentials) in a local environment.

https://cloud.google.com/docs/authentication/provide-credentials-adc?hl=en

https://cloud.google.com/docs/authentication/application-default-credentials?hl=en

For local environments, you must run gcloud auth application-default login in advance to acquire and save credentials.

gcloud auth application-default login

In that state, you can obtain an access token by writing the following Ruby code using the googleauth Gem:

require "googleauth" # googleauth gem required

credentials = Google::Auth.get_application_default
access_token = credentials.fetch_access_token!["access_token"]

Based on this, here is the overall picture of a minimal sample code for calling Vertex AI Claude (Haiku) from Ruby:

PROJECT_ID = "your-project-id"
LOCATION = "us-central1".freeze
MODEL = "claude-3-haiku@20240307".freeze
TEMPERATURE = 0.0
MAX_TOKENS = 512

# Example of obtaining an access token using ADC (Application Default Credentials)
# Assumes `gcloud auth application-default login` has been executed in advance
credentials = Google::Auth.get_application_default
access_token = credentials.fetch_access_token!["access_token"]

uri = URI("https://#{LOCATION}-aiplatform.googleapis.com/v1/projects/#{PROJECT_ID}/locations/#{LOCATION}/publishers/anthropic/models/#{MODEL}:rawPredict")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri)
request["Authorization"] = "Bearer #{access_token}"
request["Content-Type"] = "application/json; charset=utf-8"

request.body = {
  anthropic_version: "vertex-2023-10-16",
  messages: [
    {
      role: "user",
      content: [
        {
          type: "text",
          text: "Hello"
        }
      ],
    }
  ],
  temperature: TEMPERATURE,
  max_tokens: MAX_TOKENS,
  stream: false,
}.to_json
response = http.request(request)

if response.code.to_i >= 400
  raise "HTTP Request failed with status code: #{response.code} body: #{response.body}"
end

parsed_overall = JSON.parse(response.body)
result = "{#{parsed_overall['content'][0]['text']}"
puts result

Handling 429 Errors (Request for Quota Increase)

When using it to a certain extent, I occasionally received status code 429 (Too Many Requests) from the Vertex AI API along with the following response body:

{
  "error": {
    "code": 429,
    "message": "Resource exhausted. Please try again later.",
    "status": "RESOURCE_EXHAUSTED"
  }
}

https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude?hl=en

According to "Anthropic Claude Quotas and Supported Context Lengths," the default limits are as follows:

Model Region Default Quota Limit Supported Context Length
Claude 3 Sonnet us-central1 (Iowa) 60 QPM, 50,000 TPM 200,000 tokens
Claude 3 Sonnet asia-southeast1 (Singapore) 60 QPM, 50,000 TPM 200,000 tokens
Claude 3 Haiku us-central1 (Iowa) 60 QPM, 50,000 TPM 200,000 tokens
Claude 3 Haiku europe-west4 (Netherlands) 60 QPM, 50,000 TPM 200,000 tokens

The meanings of QPM and TPM are as follows:

Abbreviation Meaning
QPM Queries Per Minute
TPM Tokens Per Minute (including both input and output)

If you want to exceed these limits, you need to submit a request for an increase in Claude usage (a so-called quota increase request) from the Google Cloud Console via "IAM & Admin" > "Quotas & System Limits."

https://cloud.google.com/docs/quotas/quota-adjuster?hl=en

Accuracy Verification and Phased Rollout

I prepared around 10 to 100 items by mixing listings of actual published content on Zenn (articles, Books, Scraps, comments) with fictional posts I created myself, categorized as:

  • Content expected to be judged as non-spam
  • Content expected to be judged as spam

Then, I performed a simple accuracy verification by having the LLM judge whether they were spam or not.

This time, I created a Rails (rake) command to do the above, making it easy to retry accuracy verification every time I change models, prompts, or test data.

To minimize the impact of unforeseen side effects, I introduced it gradually by:

  1. Starting the release for articles within a limited period
  2. Gradually adding other content types (Books, Scraps, comments) as targets
  3. Expanding the time range

Closing

I have introduced the automated spam detection system using LLMs on Zenn.

Currently, we detect spam content at a pace of several dozen to 80 items per day. I believe this initiative has significantly reduced the need for users to report spam violations. Furthermore, automated detection by LLMs has improved the efficiency and effectiveness of our operation team's routine tasks. I have also gained technical insights from the process of incorporating LLMs into an actual production application, which will likely be useful in future development.

Looking ahead, as spam posting methods are expected to evolve daily, I intend to work on continuous improvement of the system through prompt optimization and periodic reviews of model selection. Also, based on the insights gained this time, I will explore the possibilities of applying LLMs to other aspects of Zenn, such as supporting content quality improvement and improving the user experience.

Zenn is a platform that grows together with its users, and I believe this spam countermeasure mechanism was realized only because of the reports and feedback from all of you. We would appreciate it if you could continue to share your voices to help us make Zenn a better platform.

I hope this article is helpful to other platforms and developers facing similar challenges.

References

Zenn Tech Blog
Zenn Tech Blog

Discussion

Ken MatsuiKen Matsui

できる限り少ない労力で済ませたかったとのことですが、Bloom filterやNaive Bayesはご検討されましたでしょうか。もしされた場合は、その上でLLMを選択された理由を伺えたら幸いです。

4
dyoshikawadyoshikawa

コメントありがとうございます。返信が遅くなりました 🙏

Bloom filterやNaive Bayes

検討していません(そもそも知りませんでした 🙏)。そういった既存の手法に対する知識が全くない状態で本問題に取り組みました。そんな自分でもLLMを活用することで一定程度実用的な仕組みが作ることができたという内容になっております。

3