0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【OpenAI API】画像情報から、テキスト情報を JSON形式で出力(TypeScript, Node.js)

Posted at

今回やること

以下の Qiitaマイページの画像から、ユーザー名、contributions、フォロー数、フォロワー数、自己紹介文を JSON形式で取得します。

サンプルコード

実行方法

私が作ったサンプルでは、以下コマンドで実行できます

npx ts-node readFile.ts

実行結果

以下の様な JSON 形式で出力されます

{
    "name": "jumpei nagai",
    "contributions": 298,
    "postCount": 50,
    "followers": 7,
    "following": 0,
    "introduction": "WebのFE・BEの両面書けます\nWindowsデスクトップアプリやスマホアプリ、Officeのアドインなんかも作れます\nプログラミング言語は10種類ぐらいなら使えます\n(英語 は全然ダメですが笑)\n・危険物乙種全類有資格者"
}

解説

〇画像を読み込ませるには、content に対して、image_urlを読み込ませます。
 サンプルコードとしては、以下の様になっています。

readFile.ts
 const fileData = fs.readFileSync('qiita_mypage.png', { encoding: 'base64' });

 const content: ChatCompletionContentPart[] = [
   { type: "image_url", image_url: { url: `data:image/png;base64,${fileData}` } }
 ];

〇戻り値を JSON形式にするには、response_formatに以下の様にフォーマットを定義します

readFile.ts
    response_format: {
      type: "json_schema",
      json_schema: {
        strict: true,
        name: 'mypage_info',
        schema: {
          type: 'object',
          properties: {
            name: { type: 'string', description: 'ユーザー名' }, // 戻り値の JSONプロパティの値と形式
            ...
          },
          required: ['name', ...], // 必須とする項目
          additionalProperties: false
        }
      }
    },
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?