chat_service.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. VOLCENGINE_API_TOKEN = '5e275c38-44fd-415f-abcf-4b59f6377f72'
  13. VOLCENGINE_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3"
  14. VOLCENGINE_MODEL_DEEPSEEK_V3 = "ep-20250213194558-rrmr2"
  15. VOLCENGINE_MODEL_DOUBAO_PRO_1_5 = 'ep-20250307150409-4blz9'
  16. class ChatServiceType(Enum):
  17. OPENAI_COMPATIBLE = auto
  18. COZE_CHAT = auto()
  19. class CozeChat:
  20. def __init__(self, token, base_url: str):
  21. self.coze = Coze(auth=TokenAuth(token), base_url=base_url)
  22. def create(self, bot_id: str, user_id: str, messages: List, custom_variables: Dict):
  23. response = self.coze.chat.create_and_poll(
  24. bot_id=bot_id, user_id=user_id, additional_messages=messages,
  25. custom_variables=custom_variables)
  26. logging.debug("coze response: {}".format(response.messages))
  27. for message in response.messages:
  28. if message.type == MessageType.ANSWER:
  29. return message.content
  30. return None
  31. if __name__ == '__main__':
  32. # Init the Coze client through the access_token.
  33. coze = Coze(auth=TokenAuth(token=COZE_API_TOKEN), base_url=COZE_CN_BASE_URL)
  34. # Create a bot instance in Coze, copy the last number from the web link as the bot's ID.
  35. bot_id = "7479005417885417487"
  36. # The user id identifies the identity of a user. Developers can use a custom business ID
  37. # or a random string.
  38. user_id = "dev_user"
  39. chat = coze.chat.create_and_poll(
  40. bot_id=bot_id,
  41. user_id=user_id,
  42. additional_messages=[Message.build_user_question_text("北京今天天气怎么样")],
  43. custom_variables={
  44. 'agent_name': '芳华',
  45. 'agent_age': '25',
  46. 'agent_region': '北京',
  47. 'name': '李明',
  48. 'preferred_nickname': '李叔',
  49. 'age': '70',
  50. 'last_interaction_interval': '12',
  51. 'current_time_period': '上午',
  52. 'if_first_interaction': 'False',
  53. 'if_active_greeting': 'False'
  54. }
  55. )
  56. for message in chat.messages:
  57. print(message, flush=True)
  58. if chat.chat.status == ChatStatus.COMPLETED:
  59. print("token usage:", chat.chat.usage.token_count)