agent.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import requests
  2. import json
  3. import time
  4. authorization = 'Bearer bce-v3/ALTAK-MyGbNEA18oT3boS2nOga1/d8b5057f7842f59b2c64971d8d077fe724d0aed5'
  5. def call_chat_api(app_id: str, conversation_id: str, user_input: str) -> str:
  6. url = "https://qianfan.baidubce.com/v2/app/conversation/runs"
  7. payload = json.dumps({
  8. "app_id": app_id,
  9. "conversation_id": conversation_id,
  10. "query": user_input,
  11. "stream": False
  12. }, ensure_ascii=False)
  13. headers = {
  14. 'Authorization': authorization,
  15. 'Content-Type': 'application/json'
  16. }
  17. start_time = time.time()
  18. response = requests.post(url, headers=headers, data=payload.encode('utf-8'), timeout=60)
  19. end_time = time.time()
  20. elapsed_time = end_time - start_time
  21. print(f"Elapsed time: {elapsed_time:.2f} seconds")
  22. answer = json.loads(response.text)["answer"]
  23. return answer.strip("\n```json")
  24. def get_conversation_id(app_id: str) -> str:
  25. url = "https://qianfan.baidubce.com/v2/app/conversation"
  26. payload = json.dumps({
  27. "app_id": app_id
  28. }, ensure_ascii=False)
  29. headers = {
  30. 'Authorization': authorization,
  31. 'Content-Type': 'application/json'
  32. }
  33. response = requests.post(url, headers=headers, data=payload.encode('utf-8'), timeout=60)
  34. return json.loads(response.text)["conversation_id"]
  35. if __name__ == "__main__":
  36. conversation_id = get_conversation_id("256fd853-60b0-4357-b11b-8114b4e90ae0")
  37. print(conversation_id)
  38. result = call_chat_api("256fd853-60b0-4357-b11b-8114b4e90ae0", conversation_id,
  39. "反复咳嗽、咳痰伴低热2月余,加重伴夜间盗汗1周。")
  40. print(result)