Create utils/api.py
Browse files- utils/api.py +58 -0
utils/api.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from typing import Dict, Any, Optional
|
| 3 |
+
from groq import Groq
|
| 4 |
+
|
| 5 |
+
def generate_fancy_text(
|
| 6 |
+
text: str,
|
| 7 |
+
api_key: str,
|
| 8 |
+
model: str = "llama3-70b-8192",
|
| 9 |
+
) -> Optional[Dict[str, Any]]:
|
| 10 |
+
"""
|
| 11 |
+
Groq APIを使用して入力テキストを様々な装飾スタイルに変換する
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
text: 変換するテキスト
|
| 15 |
+
api_key: Groq APIキー
|
| 16 |
+
model: 使用するGroq APIのモデル名
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
装飾スタイルの辞書。エラーが発生した場合はNone
|
| 20 |
+
"""
|
| 21 |
+
# システムプロンプトを定義
|
| 22 |
+
system_prompt = """あなたはテキスト装飾の専門家です。
|
| 23 |
+
与えられたテキストを15種類以上の異なるスタイル(カッコいい、かわいい、フォーマル、カジュアル、未来的、レトロ、ミニマル、装飾的など)に変換してください。
|
| 24 |
+
出力は必ず以下のJSON形式で返してください:
|
| 25 |
+
{
|
| 26 |
+
"styles": [
|
| 27 |
+
{"name": "スタイル名1", "text": "装飾されたテキスト1"},
|
| 28 |
+
{"name": "スタイル名2", "text": "装飾されたテキスト2"},
|
| 29 |
+
...
|
| 30 |
+
]
|
| 31 |
+
}
|
| 32 |
+
装飾には、特殊文字、絵文字、記号などを使用し、オリジナルのテキストの意味を保持してください。
|
| 33 |
+
日本語と英語の両方に対応してください。"""
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
# Groq APIクライアントを初期化
|
| 37 |
+
client = Groq(api_key=api_key)
|
| 38 |
+
|
| 39 |
+
# API呼び出し
|
| 40 |
+
response = client.chat.completions.create(
|
| 41 |
+
model=model,
|
| 42 |
+
messages=[
|
| 43 |
+
{"role": "system", "content": system_prompt},
|
| 44 |
+
{"role": "user", "content": f"次のテキストを装飾してください: {text}"}
|
| 45 |
+
],
|
| 46 |
+
temperature=0.7,
|
| 47 |
+
response_format={"type": "json_object"}
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# レスポンスからコンテンツを取得
|
| 51 |
+
content = response.choices[0].message.content
|
| 52 |
+
|
| 53 |
+
# JSONをパース
|
| 54 |
+
result = json.loads(content)
|
| 55 |
+
return result
|
| 56 |
+
except Exception as e:
|
| 57 |
+
print(f"API通信エラー: {e}")
|
| 58 |
+
return None
|