APIサンプルコード
最終更新
curl -X POST 'https://api.dify.ai/v1/chat-messages' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{
"inputs": {},
"query": "こんにちは、営業時間を教えてください",
"response_mode": "blocking",
"user": "user-123"
}'import requests
def chat_with_dify(query, user_id, conversation_id=None, api_key="YOUR_API_KEY"):
base_url = "https://api.dify.ai/v1/chat-messages"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
payload = {
"inputs": {}, # プロンプト変数がある場合はここに設定
"query": query,
"response_mode": "blocking",
"user": user_id,
}
if conversation_id:
payload["conversation_id"] = conversation_id
try:
response = requests.post(base_url, headers=headers, json=payload, timeout=60)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return None
# 使用例
result = chat_with_dify(
query="営業時間を教えてください",
user_id="user-123"
)
if result:
print("Answer:", result.get("answer"))
print("Conversation ID:", result.get("conversation_id"))const axios = require('axios');
async function chatWithDify(query, userId, conversationId = null, apiKey = 'YOUR_API_KEY') {
const url = 'https://api.dify.ai/v1/chat-messages';
const payload = {
inputs: {},
query: query,
response_mode: 'blocking',
user: userId
};
if (conversationId) {
payload.conversation_id = conversationId;
}
try {
const response = await axios.post(url, payload, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
timeout: 60000 // 60秒タイムアウト
});
return response.data;
} catch (error) {
console.error('API Error:', error.response ? error.response.data : error.message);
throw error;
}
}
// 使用例
(async () => {
try {
const result = await chatWithDify('営業時間を教えてください', 'user-123');
console.log('Answer:', result.answer);
} catch (e) {
// エラーハンドリング
}
})(); import requests
import json
def chat_streaming(query, user_id, api_key="YOUR_API_KEY"):
url = "https://api.dify.ai/v1/chat-messages"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
payload = {
"inputs": {},
"query": query,
"response_mode": "streaming",
"user": user_id,
}
print("Bot: ", end="", flush=True)
with requests.post(url, headers=headers, json=payload, stream=True, timeout=60) as response:
response.raise_for_status()
for line in response.iter_lines(decode_unicode=True):
if line and line.startswith("data:"):
# "data: " のプレフィックスを除去してJSONパース
json_str = line[5:].strip()
try:
data = json.loads(json_str)
event = data.get("event")
# メッセージ終了またはエラー時
if event in ["message_end", "error"]:
break
# テキスト生成イベントの場合
if event == "message":
answer = data.get("answer", "")
print(answer, end="", flush=True)
except json.JSONDecodeError:
continue
print() # 改行
# 使用例
chat_streaming("Difyについて教えて", "user-123"){
"event": "message",
"message_id": "9dbbb6c1-c88f-43b3-8c4c-2f222830e236",
"conversation_id": "e56b4028-0955-460d-88b9-11221375e236",
"mode": "chat",
"answer": "DifyはオープンソースのLLMアプリ開発プラットフォームです...",
"metadata": { ... },
"created_at": 1705627476
}{
"code": "invalid_api_key",
"message": "Invalid API key",
"status": 401
}