前言
在產線或維修記錄分析時,常常會遇到大量結構化的JSON資料,這些資料對於工程師來說很清楚,但對非專業人員卻不易理解。透過OpenAI的模型,我們可以將這些紀錄自動轉換為精簡易懂的自然語言描述,方便溝通、彙整與後續使用。
本篇將以簡化教學示例,說明如何用Python批次處理、避免中途斷線資料流失、並精算API花費。
一、簡化版需求描述
- 自動將每一筆維修紀錄(JSON格式)轉成自然語言說明
- 資料量大(數千筆),API處理需花很久。
若中途中斷(ctrl+C或API額度用完),避免處理進度全丟失 - 每筆都即時寫入檔案,並記錄token消耗與費用
二、自然語言轉換Prompt設計(簡化範例)
prompt = """
請將下列JSON格式的維修紀錄,轉換成精簡易懂的中文自然語言描述,
若某些欄位為空,則省略該資訊,不要胡亂補充。
範例:
{
"Family_家族": "['ASTORIA']",
"sn_治具序号": "015ATR30",
"faultType_故障分类": "UUT IP FAIL",
"defectSymptom_故障現象": "無法正常開機",
"rootCause_故障原因": "Agora 無法正常讀取",
"correctiveAction_解決方案": "更換agor轉板*1",
"startTime_開始時間": "2025/03/13 09:09:02",
"endTime_完成時間": "2025/03/13 10:04:06"
}
輸出:
2025年3月13日09:09,ASTORIA家族的治具(序號015ATR30)發生UUT IP FAIL,
現象為無法正常開機,原因是Agora無法正常讀取,處理方式為更換Agora轉板,於10:04修復完成。
請處理下列資料:
"""
三、Python程式範例(重點精簡版)
import os, json, time
from openai import OpenAI
client = OpenAI(api_key="請至openAI網站購買")
# 讀取資料庫
with open("fixtureRepair.json", "r", encoding="utf-8") as f:
json_data = json.load(f) # List[dict]
# 輸出暫存路徑
out_dir = "Neutral Lang"
os.makedirs(out_dir, exist_ok=True)
out_tmp = os.path.join(out_dir, "fixtureRepair_nl_tmp.json")
out_final = os.path.join(out_dir, "fixtureRepair_nl.json")
prompt = """(如上,略)"""
json_data_nl = []
total_cost = 0
for i, dic in enumerate(json_data):
response = client.chat.completions.create(
model="gpt-4.1-nano",
messages=[{"role": "user",
"content": prompt + json.dumps(dic, ensure_ascii=False)}]
)
reply = response.choices[0].message.content
dic_nl = dic.copy()
dic_nl["自然語言描述"] = reply
json_data_nl.append(dic_nl)
# 計算token與花費
in_tok = response.usage.prompt_tokens
out_tok = response.usage.completion_tokens
cost = (in_tok/1e6)*0.1 + (out_tok/1e6)*0.4
total_cost += cost
# 每筆即時存檔,避免中斷遺失
with open(out_tmp, "w", encoding="utf-8") as f:
json.dump(json_data_nl, f, ensure_ascii=False, indent=2)
print(f"第{i+1}筆完成,花費:{total_cost:.6f} USD")
# 全部完成後正名
os.rename(out_tmp, out_final)
print("全部完成,總花費:", total_cost)
輸出的資料(多了自然語言描述):
![Python如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/07/20250716084059_0_c5b368.png)
chatGPT vs Claude vs Gemini:
import openai
from anthropic import Anthropic
import google.generativeai as genai
import json
# 設定 API 金鑰
client_openai = openai.OpenAI(api_key="你的OPENAI_API_KEY")
client_claude = Anthropic(api_key="你的ANTHROPIC_API_KEY")
genai.configure(api_key="你的GOOGLE_API_KEY")
def compare_prompt(prompt, dic):
# OpenAI
completion = client_openai.chat.completions.create(
model="gpt-4.1-nano",
messages=[{"role": "user", "content": prompt + json.dumps(dic, ensure_ascii=False)}]
)
chatgpt_response = completion.choices[0].message.content
# Claude
claude_response = client_claude.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=512,
messages=[{"role": "user", "content": prompt + json.dumps(dic, ensure_ascii=False)}]
)
claude_response_text = claude_response.content[0].text
# Gemini
gemini_model = genai.GenerativeModel('gemini-1.5-flash')
#"gemini-2.5-pro"
#須付費,或者 time.sleep() 避免超過免費API的quota
gemini_response = gemini_model.generate_content(prompt + json.dumps(dic, ensure_ascii=False))
gemini_text = gemini_response.text
return {
"ChatGPT": chatgpt_response,
"Claude": claude_response_text,
"Gemini": gemini_text
}
#取得Gemini API Key: https://aistudio.google.com/apikey
#免費API key限制: https://ai.google.dev/gemini-api/docs/rate-limits?hl=zh-tw
各家 response 取出 text 的對照表
![Python如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/07/20250717095851_0_549da9.png)
四、重點技巧
- 逐筆處理、逐筆即時寫入:避免API中斷或手動停止時資料全失。
- 精算token與API花費:方便成本預估與控制。
- 範例prompt設計:確保LLM輸出統一、精簡、無編造內容。
五、結語
這種寫法不僅能自動化資訊摘要,也大幅降低人力轉寫風險與成本。
只要掌握逐筆即時寫入與token花費控管,批次處理大資料時就能兼顧安全與效率!
費用計算請參考:
https://platform.openai.com/docs/pricing
gpt-4.1-nano 最便宜
![Python如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/07/20250716085741_0_6a7979.png)
四種基本 Prompt 技巧說明
1. Zero-shot Prompting
- 定義:直接丟指令給模型,不給任何範例。
- 用途:最簡單、最快速,適合簡單明確的任務。
- 例子:「請總結這段文章。」
2. Few-shot Prompting
- 定義:給模型一到數個範例,讓模型模仿格式或風格。
- 用途:當你希望輸出品質穩定、格式統一時特別有效。
- 例子:
範例:
問題:2+2是多少?
答案:4
問題:5+7是多少?
答案:
(模型會自動補出12)
3. Chain-of-Thought (CoT)
- 定義:要求模型展開推理步驟,而不是只給答案。
- 用途:數學、推理、決策類問題更容易得到正確答案。
- 例子:
「請分步驟說明你怎麼得到答案。」
4. Emotional Prompt
- 定義:在指令中加入情感色彩、語氣,引導模型表現更自然或貼心。
- 用途:客服、陪伴、行銷文案、需要溫度的內容。
- 例子:
「請用鼓勵的語氣告訴我這段話。」
小結
- Zero-shot =「直接請你做…」
- Few-shot =「請參考這些範例,幫我做…」
- CoT =「請一步步推理…」
- Emotional =「請用溫柔/鼓勵/專業語氣…」
本篇就是這裡第二種技巧few-shot prompt的經典應用,
讓模型「照著範例學」!
推薦hahow線上學習python: https://igrape.net/30afN
import google.generativeai as genai
所有支援 (包括修正錯誤) 將於 2025 年 9 月底終止。
參考: https://ai.google.dev/gemini-api/docs/libraries?hl=zh-tw
![Python如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/07/20250808155127_0_3d33a9.png)
新語法:
from google import genai
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.0-flash", contents="Write a story about a magic backpack."
)
print(response.text)
推薦hahow線上學習python: https://igrape.net/30afN
近期留言