画像解析
AIエージェントは、テキストによる指示と併せて視覚コンテンツを処理することで、画像を分析し理解できます。この能力により、エージェントは物体の認識、シーンの記述、画像に関する質問への回答、さらには複雑な視覚的推論タスクの遂行が可能になります。
前提条件
- Unsplash の開発者アカウント、アプリケーション、APIキー
- OpenAI の APIキー
この例では openai
モデルを使用します。OPENAI_API_KEY
と UNSPLASH_ACCESS_KEY
の両方を .env
ファイルに追加してください。
.env
OPENAI_API_KEY=<your-api-key>
UNSPLASH_ACCESS_KEY=<your-unsplash-access-key>
エージェントの作成
画像を分析して物体を検出し、シーンを説明し、視覚コンテンツに関する質問に答えるシンプルなエージェントを作成します。
src/mastra/agents/example-image-analysis-agent.ts
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
export const imageAnalysisAgent = new Agent({
name: "image-analysis",
description: "Analyzes images to identify objects and describe scenes",
instructions: `
You can view an image and identify objects, describe scenes, and answer questions about the content.
You can also determine species of animals and describe locations in the image.
`,
model: openai("gpt-4o")
});
設定オプションの詳細は Agent をご覧ください。
エージェントの登録
エージェントを使用するには、メインの Mastra インスタンスに登録します。
src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra";
import { imageAnalysisAgent } from "./agents/example-image-analysis-agent";
export const mastra = new Mastra({
// ...
agents: { imageAnalysisAgent }
});
関数の作成
この関数は、エージェントによる分析に渡すため、Unsplash からランダムな画像を取得します。
src/mastra/utils/get-random-image.ts
export const getRandomImage = async (): Promise<string> => {
const queries = ["wildlife", "feathers", "flying", "birds"];
const query = queries[Math.floor(Math.random() * queries.length)];
const page = Math.floor(Math.random() * 20);
const order_by = Math.random() < 0.5 ? "relevant" : "latest";
const response = await fetch(`https://api.unsplash.com/search/photos?query=${query}&page=${page}&order_by=${order_by}`, {
headers: {
Authorization: `Client-ID ${process.env.UNSPLASH_ACCESS_KEY}`,
"Accept-Version": "v1"
},
cache: "no-store"
});
const { results } = await response.json();
return results[Math.floor(Math.random() * results.length)].urls.regular;
};
使用例
getAgent()
でエージェント参照を取得し、プロンプトとともに generate()
を呼び出します。画像の type
、imageUrl
、mimeType
に加え、エージェントの応答方針を明確に示す指示を含む content
配列を渡します。
src/test-image-analysis.ts
import "dotenv/config";
import { mastra } from "./mastra";
import { getRandomImage } from "./mastra/utils/get-random-image";
const imageUrl = await getRandomImage();
const agent = mastra.getAgent("imageAnalysisAgent");
const response = await agent.generate([
{
role: "user",
content: [
{
type: "image",
image: imageUrl,
mimeType: "image/jpeg"
},
{
type: "text",
text: `Analyze this image and identify the main objects or subjects. If there are animals, provide their common name and scientific name. Also describe the location or setting in one or two short sentences.`
}
]
}
]);
console.log(response.text);
View Example on GitHub (outdated)