2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PLaMo APIで多言語翻訳してみた!

Last updated at Posted at 2025-12-10

PLaMoとは

PLaMo(Preferred Language Model) は、日本を代表するAI企業である株式会社Preferred Networks(PFN)が開発・提供しているLLMです。特に高い日本語性能や翻訳能力に定評があります。

image.png

PLaMo APIを使おうと思った背景

先日、コードゴルフコンペに参加し、15位チーム銀メダルを獲得しました。
こちらのコンペでは、ARC-AGIデータセット400問の解をどれだけ短く書けるかを競いました。コンペ期間中に、とある参加者から各問題のヒントテキストファイルが公開されましたが、そのヒントテキストファイルは中国語で書かれていました。

LLMにコードゴルフを実行させる際、ヒントテキストを付与することでより良い結果が得られると考えました。また、解答の多様性を高めるため、多言語のヒントテキストで試したくなり、PLaMo APIに白羽の矢が立ちました。

実際に使ってみてわかったこと

使い方は非常に簡単でした。PLaMoの公式サイトにアクセスし、APIキーを発行し、インストラクションに従うことで、簡単にHello worldできました。

また、GENIAC-PRIZE応援キャンペーンで1000円分の無料クレジットを頂けました。
※対象期間内かは下記からご確認をお願いします
image.png

合計1200問以上のヒントテキストを翻訳しましたが、API使用量は21円だけだったので、余裕で無料クレジット内に収まりました。

最初は単純な翻訳プロンプトを使っていましたが、翻訳文と一緒に「備考コメント」や「補足説明」が付いてしまうことがありました。これはChatGPTなどでもよくある挙動だと思います。ただ、モデルがとても賢いので、備考の文章が不要な旨をプロンプトに追加することで、そういった余計な文章は無くなりました。

コンペで実際に使用したコードの例も参考程度に共有します。"model": "plamo-2.0-prime"は使用時点での最新バージョンに置き換えることをオススメします。

コンペで実際に使用したコードの例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import time
import requests
from pathlib import Path
import os

def translate_with_plamo_to_english(chinese_text, api_key):
    """PLaMo APIを使用して中国語を英語に直訳"""

    url = "https://platform.preferredai.jp/api/completion/v1/chat/completions"

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    data = {
        "messages": [
            {
                "role": "system",
                "content": "You are a professional translator. Translate the Chinese text to English directly and concisely. Do NOT add any explanations, technical term notes, or supplementary information. Just provide a clean, direct translation."
            },
            {
                "role": "user",
                "content": f"Translate this Chinese text to English:\n\n{chinese_text}"
            }
        ],
        "model": "plamo-2.0-prime"
    }

    try:
        response = requests.post(url, headers=headers, json=data, timeout=30)
        response.raise_for_status()

        result = response.json()
        translated_text = result["choices"][0]["message"]["content"].strip()

        # 不要な前置きを除去
        if translated_text.lower().startswith("here") or translated_text.lower().startswith("the translation"):
            lines = translated_text.split('\n')
            for i, line in enumerate(lines):
                if line.strip() and not any(word in line.lower() for word in ["here", "translation", "english"]):
                    translated_text = '\n'.join(lines[i:])
                    break

        return translated_text

    except requests.exceptions.RequestException as e:
        print(f"  ERROR: API call failed - {e}")
        return None
    except json.JSONDecodeError as e:
        print(f"  ERROR: JSON parsing failed - {e}")
        return None
    except KeyError as e:
        print(f"  ERROR: Invalid response format - {e}")
        return None

def main():
    """メイン処理"""

    # API キーを環境変数から取得
    api_key = os.getenv("PLAMO_API_KEY")
    if not api_key:
        print("ERROR: PLAMO_API_KEY environment variable not set")
        return

    print("PLAMO API中国語→英語翻訳開始...")
    print("=" * 50)

    # 入力・出力ディレクトリ
    input_dir = Path("hints_by_task")
    output_dir = Path("hints_by_task_english")

    if not input_dir.exists():
        print(f"ERROR: {input_dir} directory not found")
        return

    output_dir.mkdir(exist_ok=True)

    # 全400タスクを処理
    success_count = 0
    failed_tasks = []

    for task_num in range(1, 401):
        task_filename = f"task{task_num:03d}.txt"
        input_file = input_dir / task_filename
        output_file = output_dir / task_filename

        if not input_file.exists():
            print(f"  WARNING: {task_filename}: Input file not found")
            failed_tasks.append(task_num)
            continue

        # 既に翻訳済みの場合はスキップ
        if output_file.exists():
            print(f"  OK: {task_filename}: Already translated (skip)")
            success_count += 1
            continue

        try:
            # 中国語テキストを読み込み
            with open(input_file, 'r', encoding='utf-8') as f:
                chinese_text = f.read().strip()

            print(f"  PROCESSING: {task_filename}: Translating...")

            # PLAMO APIで英語に翻訳
            english_text = translate_with_plamo_to_english(chinese_text, api_key)

            if english_text:
                # 翻訳結果を保存
                with open(output_file, 'w', encoding='utf-8') as f:
                    f.write(english_text)

                print(f"  OK: {task_filename}: Translation completed")
                success_count += 1
            else:
                print(f"  ERROR: {task_filename}: Translation failed")
                failed_tasks.append(task_num)

            # APIレート制限を考慮して少し待機
            time.sleep(0.5)

        except Exception as e:
            print(f"  ERROR: {task_filename}: Unexpected error - {e}")
            failed_tasks.append(task_num)

        # 進捗表示(50タスクごと)
        if task_num % 50 == 0:
            print(f"\nProgress: {task_num}/400 tasks processed (success: {success_count})")
            print("-" * 50)

    # 結果サマリー
    print(f"\nTranslation completed!")
    print(f"Output directory: {output_dir}")
    print(f"Success: {success_count}/400 tasks")

    if failed_tasks:
        print(f"Failed tasks: {failed_tasks}")
        print(f"Failed count: {len(failed_tasks)}")
    else:
        print("All tasks translated successfully!")

if __name__ == "__main__":
    main()

まとめ

日本語以外の翻訳性能も高く、コストパフォーマンスが良いモデルだと思いました。
ジェネラルなLLM APIを翻訳用途で使っている場合は、コストや性能の観点で、PLaMo APIに置き換えるメリットがありそうです。日本語関連のタスクをLLMに解かせる場合は、ぜひPLaMo APIの採用をご検討頂ければと思います。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?