
import
openai
import
pandas
as
pd
import
json
from
typing
import
List, Dict
classMetadataAutoTagger:
def__init__(self, api_key: str, business_context: str):
self.client = openai.OpenAI(api_key=api_key)
self.business_context = business_context
# 公司業務背景說明
defgenerate_prompt(self, table_name: str, columns: List[str]) -> str:
"""構造大模型提示詞"""
return
f"""
# 任務說明
根據提供的元資料和業務背景,生成資料資產的業務標註資訊,要求:
1. 業務名稱:體現資料在業務中的核心作用
2. 業務型別:交易型/分析型/主資料/日誌型...
3. 業務實體:對應業務物件(客戶/訂單/產品...)
4. 分類分級:按公司資料分類分級標準
5. 欄位說明:用業務語言解釋欄位含義
# 業務背景
{self.business_context}
# 待標註元資料
表名:
{table_name}
欄位列表:
{', '.join(columns)}
請用JSON格式返回結果,結構如下:
{{
"table_name": "
{table_name}
",
"business_name": "",
"business_type": "",
"business_entity": "",
"data_classification": "",
"columns": {{
"column1": "業務說明",
"column2": "業務說明"
}}
}}
"""
deftag_metadata(self, metadata_df: pd.DataFrame) -> pd.DataFrame:
"""批次處理元資料"""
results = []
for
_, row
in
metadata_df.iterrows():
response = self._call_llm(row[
'table_name'
], row[
'columns'
])
if
response:
results.append(response)
return
pd.DataFrame(results)
def_call_llm(self, table_name: str, columns: List[str]) -> Dict:
"""呼叫大模型API"""
try
:
prompt = self.generate_prompt(table_name, columns)
response = self.client.chat.completions.create(
model=
"gpt-4"
,
messages=[{
"role"
:
"user"
,
"content"
: prompt}],
temperature=
0.2
,
response_format={
"type"
:
"json_object"
}
)
return
json.loads(response.choices[
0
].message.content)
except
Exception
as
e:
print(
f"Error processing {table_name}: {str(e)}"
)
returnNone
# 示例用法
if
__name__ ==
"__main__"
:
# 初始化配置
config = {
"api_key"
:
"your_openai_key"
,
"business_context"
:
"某電商公司,主要業務包含商品交易、使用者畫像、訂單履約等..."
}
# 示例元資料(實際從資料庫或檔案讀取)
sample_data = {
"table_name"
: [
"user_info"
,
"order_detail"
],
"columns"
: [
[
"user_id"
,
"registration_date"
,
"last_login"
],
[
"order_id"
,
"product_sku"
,
"payment_amount"
]
]
}
metadata_df = pd.DataFrame(sample_data)
# 執行自動標註
tagger = MetadataAutoTagger(**config)
result_df = tagger.tag_metadata(metadata_df)
# 儲存結果
result_df.to_csv(
"tagged_metadata.csv"
, index=
False
)
print(
"標註結果示例:"
)
print(result_df.head())
典型輸出結果如下:
{
"table_name"
:
"user_info"
,
"business_name"
:
"使用者基本資訊表"
,
"business_type"
:
"主資料"
,
"business_entity"
:
"使用者"
,
"data_classification"
:
"PII/LEVEL-2"
,
"columns"
: {
"user_id"
:
"使用者唯一識別符號,用於跨系統使用者識別"
,
"registration_date"
:
"使用者註冊電商平臺的具體日期"
,
"last_login"
:
"記錄使用者最近一次登入平臺的時間"
}
}
-
自然語言互動:大模型出色的自然語言互動能力可準確理解使用者意圖,大幅提升數 據查詢分析的便利性,提升使用者體驗
-
智慧洞察分析:大模型可分析文字、圖表等多維資料,智慧歸因、預測、總結,降 低員工利用資料、分析資料的門檻
-
整合大模型服務鏈路:整合 LangChain、向量檢索、finetune 等大模型應用所 需技術元件,提升企業除錯、使用大模型的效率


