chat_service.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. #
  5. import os
  6. from typing import List, Dict
  7. from enum import Enum, auto
  8. import logging
  9. from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType, MessageType
  10. COZE_API_TOKEN = os.getenv("COZE_API_TOKEN")
  11. COZE_CN_BASE_URL = 'https://api.coze.cn'
  12. class ChatServiceType(Enum):
  13. OPENAI_COMPATIBLE = auto
  14. COZE_CHAT = auto()
  15. class CozeChat:
  16. def __init__(self, token, base_url: str):
  17. self.coze = Coze(auth=TokenAuth(token), base_url=base_url)
  18. def create(self, bot_id: str, user_id: str, messages: List, custom_variables: Dict):
  19. response = self.coze.chat.create_and_poll(
  20. bot_id=bot_id, user_id=user_id, additional_messages=messages,
  21. custom_variables=custom_variables)
  22. logging.debug("coze response: {}".format(response.messages))
  23. for message in response.messages:
  24. if message.type == MessageType.ANSWER:
  25. return message.content
  26. return None
  27. if __name__ == '__main__':
  28. # Init the Coze client through the access_token.
  29. coze = Coze(auth=TokenAuth(token=COZE_API_TOKEN), base_url=COZE_CN_BASE_URL)
  30. # Create a bot instance in Coze, copy the last number from the web link as the bot's ID.
  31. bot_id = "7479005417885417487"
  32. # The user id identifies the identity of a user. Developers can use a custom business ID
  33. # or a random string.
  34. user_id = "dev_user"
  35. chat = coze.chat.create_and_poll(
  36. bot_id=bot_id,
  37. user_id=user_id,
  38. additional_messages=[Message.build_user_question_text("北京今天天气怎么样")],
  39. custom_variables={
  40. 'agent_name': '芳华',
  41. 'agent_age': '25',
  42. 'agent_region': '北京',
  43. 'name': '李明',
  44. 'preferred_nickname': '李叔',
  45. 'age': '70',
  46. 'last_interaction_interval': '12',
  47. 'current_time_period': '上午',
  48. 'if_first_interaction': 'False',
  49. 'if_active_greeting': 'False'
  50. }
  51. )
  52. for message in chat.messages:
  53. print(message, flush=True)
  54. if chat.chat.status == ChatStatus.COMPLETED:
  55. print("token usage:", chat.chat.usage.token_count)