👉 jxon-schema 0.2.0 (PyPI)
注:ライブラリ自体が重要というわけではなく、あくまでも概念の共有を目的とした記事です。
生成AIを使ってJSONデータを自動的に更新・編集する際、特に重要だと思うのが配列操作の自動化です。自動化を実装するために重要なのは、「add」「remove」「replace」操作をスキーマとして明確に定義することです。
なぜ配列の「add/remove/replace」を構造化スキーマに組み込むのか?
配列操作の自動化を実現するためには、AIが出力するデータが「構造化」されていることが条件です。
例えば、次のようなJSONがあったとします:
{
"tags": ["web", "app", "mobile"]
}
これをそのままAIに渡しても、漠然とした出力しか得られません。
しかし、jxon-schema
を使用することで、この配列を次のように構造化されたスキーマとして明示できます:
{
"type": "object",
"additionalProperties": false,
"properties": {
"tags": {
"type": "object",
"properties": {
"add": {
"type": "array",
"items": {"type": "string"}
},
"remove": {
"type": "array",
"items": {"type": "string"}
},
"replace": {
"type": "string",
"enum": ["web", "app", "mobile"]
}
},
"required": ["add", "remove", "replace"]
}
},
"required": ["tags"]
}
こちらを使えば、AIからの出力が次のように明確な形で得られます:
{
"tags": {
"add": ["backend"],
"remove": ["mobile"],
"replace": "web"
}
}
このように、配列に対する変更の意図とその詳細を分かりやすく処理可能にしてくれます。
GPT4oを使った例
from jxon import convert_to_schema
from openai import OpenAI
import json
# サンプルJSONデータ
task_json = {
"title": "Implement feature X",
"description": "Implement the new feature X for the application",
"due_date": "2023-12-31",
"priority": "high",
"tags": ["feature", "development", "important"],
"assignee": {
"name": "Jane Smith",
"email": "jane.smith@example.com"
},
"status": "in progress"
}
# スキーマを生成
schema = convert_to_schema(task_json)
# OpenAI用にスキーマをクリーンアップ
def clean_schema_for_openai(schema_obj):
if isinstance(schema_obj, dict):
schema_obj.pop('current_value', None)
schema_obj.pop('description', None)
if 'properties' in schema_obj and 'required' in schema_obj:
for field in list(schema_obj['required']):
if field not in schema_obj['properties']:
schema_obj['properties'][field] = {"type": "string"}
for key, value in list(schema_obj.items()):
if isinstance(value, (dict, list)):
clean_schema_for_openai(value)
elif isinstance(schema_obj, list):
for item in schema_obj:
if isinstance(item, (dict, list)):
clean_schema_for_openai(item)
return schema_obj
# クリーンアップ後のスキーマ
cleaned_schema = clean_schema_for_openai(schema)
# OpenAI APIを呼び出し
client = OpenAI(api_key="your-api-key")
response = client.chat.completions.create(
model="gpt-4o-2024-08-06",
messages=[
{"role": "system", "content": "You are a helpful assistant that outputs structured JSON data."},
{"role": "user", "content": "Create a task for implementing a new feature in a mobile app."}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "structured_response",
"schema": cleaned_schema,
"strict": True
}
}
)
インストール方法
PyPIからインストールできます:
pip install jxon-schema
実際の使い方(簡単な例)
from jxon_schema import generate_schema
data = {"tags": ["web", "app", "mobile"]}
schema = generate_schema(data, array_operations=True)
print(schema)
まとめ:『jxon-schema』でAIによるJSON更新を完全自動化
jxon-schema
を使うことで、JSONの配列操作を構造化スキーマとして定義し、AIを使った更新・編集・やり直しのプロセスを完全に自動化できます。
ぜひお試しください。