fast_gpt_client.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import yaml
  2. import requests
  3. from pathlib import Path
  4. from tools.utils import get_config
  5. class FastGPTClient:
  6. def __init__(self):
  7. self.config = get_config()
  8. self.headers = {
  9. "Content-Type": "application/json",
  10. "Authorization": f"Bearer {self.config.get('fastgpt.key')}"
  11. }
  12. def chat(self, prompt: str, temperature: float = 0.7) -> str:
  13. """与FastGPT进行对话"""
  14. payload = {
  15. "chatId": "my_chatId111",
  16. "stream": False,
  17. "detail": False,
  18. "messages": [
  19. {
  20. "role": "user",
  21. "content": prompt
  22. }
  23. ]
  24. }
  25. try:
  26. response = requests.post(
  27. self.config.get('fastgpt.url'),
  28. headers=self.headers,
  29. json=payload,
  30. timeout=500
  31. )
  32. response.raise_for_status()
  33. data = response.json()
  34. return data['choices'][0]['message']['content']
  35. except Exception as e:
  36. print(f"API调用失败: {str(e)}")
  37. raise e
  38. if __name__ == "__main__":
  39. try:
  40. client = FastGPTClient()
  41. response = client.chat("总结一下知识库总定额编号相关的内容")
  42. print("FastGPT回复:", response)
  43. except Exception as e:
  44. print(f"发生异常: {str(e)}")