dify_vision_demo.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import base64
  2. import requests
  3. import time
  4. # dify 密钥
  5. api_key = "app-wzRAbuWYxm9WiyY6fpQzA7Cu"
  6. user = "howsoGQ@qq.com"
  7. upload_url = "http://robot.yun36.com:8066/v1/files/upload"
  8. chat_url = "http://robot.yun36.com:8066/v1/chat-messages"
  9. def upload_image_to_dify(image_path='demo_pic.png'):
  10. files = {
  11. "file": ("demo_pic.png", open("demo_pic.png", "rb"), "image/[png|jpeg|jpg|webp|gif]")
  12. }
  13. data = {
  14. "user": user
  15. }
  16. headers = {
  17. "Authorization": f"Bearer {api_key}"
  18. }
  19. resp = requests.post(upload_url, headers=headers, files=files, data=data)
  20. return resp.json().get("id")
  21. def chat_with_dify(question='请用 30 字以内分析你看到的', image_path=''):
  22. s1_time = time.time()
  23. headers = {
  24. "Authorization": f"Bearer {api_key}",
  25. "Content-Type": "application/json"
  26. }
  27. if image_path != '':
  28. image_id = upload_image_to_dify(image_path)
  29. s2_time = time.time()
  30. print(f"图片上传完成耗时: {s2_time - s1_time:.2f}秒")
  31. files_val = [
  32. {
  33. "type": "image",
  34. "transfer_method": "local_file",
  35. "upload_file_id": image_id
  36. # "url": "https://cloud.dify.ai/logo/logo-site.png"
  37. }
  38. ]
  39. else:
  40. files_val = []
  41. payload = {
  42. "inputs": {}, # 可以留空,或者传其他上下文
  43. "query": question,
  44. "response_mode": "blocking",
  45. "conversation_id": "", # 如果是新会话可以留空
  46. "user": user,
  47. "files": files_val
  48. }
  49. # 发送请求
  50. s3_time = time.time()
  51. resp = requests.post(chat_url, headers=headers, json=payload)
  52. s4_time = time.time()
  53. print(resp.json().get("answer",'请求出错'))
  54. print(f"请求完成耗时: {s4_time - s3_time:.2f}秒")
  55. print(f"总耗时: {s4_time - s1_time:.2f}秒")
  56. if __name__ == '__main__':
  57. # chat_with_dify(question='请用 30 字以内分析你看到的',image_path='demo_pic.png')
  58. chat_with_dify(question='苏超最近的比赛', image_path='')