sycommon-python-lib 0.1.56b17__tar.gz → 0.1.57__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/PKG-INFO +1 -1
  2. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/pyproject.toml +1 -1
  3. sycommon_python_lib-0.1.57/src/sycommon/llm/get_llm.py +37 -0
  4. sycommon_python_lib-0.1.57/src/sycommon/llm/struct_token.py +192 -0
  5. sycommon_python_lib-0.1.57/src/sycommon/llm/sy_langfuse.py +103 -0
  6. sycommon_python_lib-0.1.57/src/sycommon/llm/usage_token.py +117 -0
  7. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/rabbitmq/rabbitmq_client.py +6 -5
  8. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/rabbitmq/rabbitmq_service_client_manager.py +6 -1
  9. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/services.py +118 -96
  10. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/nacos_client_base.py +3 -1
  11. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/tools/merge_headers.py +20 -0
  12. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon_python_lib.egg-info/PKG-INFO +1 -1
  13. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon_python_lib.egg-info/SOURCES.txt +3 -0
  14. sycommon_python_lib-0.1.56b17/src/sycommon/llm/get_llm.py +0 -308
  15. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/README.md +0 -0
  16. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/setup.cfg +0 -0
  17. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/command/cli.py +0 -0
  18. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/__init__.py +0 -0
  19. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/config/Config.py +0 -0
  20. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/config/DatabaseConfig.py +0 -0
  21. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/config/EmbeddingConfig.py +0 -0
  22. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/config/LLMConfig.py +0 -0
  23. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/config/LangfuseConfig.py +0 -0
  24. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/config/MQConfig.py +0 -0
  25. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/config/RerankerConfig.py +0 -0
  26. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/config/SentryConfig.py +0 -0
  27. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/config/__init__.py +0 -0
  28. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/database/async_base_db_service.py +0 -0
  29. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/database/async_database_service.py +0 -0
  30. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/database/base_db_service.py +0 -0
  31. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/database/database_service.py +0 -0
  32. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/health/__init__.py +0 -0
  33. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/health/health_check.py +0 -0
  34. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/health/metrics.py +0 -0
  35. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/health/ping.py +0 -0
  36. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/llm/__init__.py +0 -0
  37. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/llm/embedding.py +0 -0
  38. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/llm/llm_logger.py +0 -0
  39. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/llm/llm_tokens.py +0 -0
  40. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/logging/__init__.py +0 -0
  41. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/logging/async_sql_logger.py +0 -0
  42. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/logging/kafka_log.py +0 -0
  43. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/logging/logger_levels.py +0 -0
  44. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/logging/logger_wrapper.py +0 -0
  45. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/logging/sql_logger.py +0 -0
  46. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/middleware/__init__.py +0 -0
  47. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/middleware/context.py +0 -0
  48. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/middleware/cors.py +0 -0
  49. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/middleware/docs.py +0 -0
  50. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/middleware/exception.py +0 -0
  51. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/middleware/middleware.py +0 -0
  52. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/middleware/monitor_memory.py +0 -0
  53. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/middleware/mq.py +0 -0
  54. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/middleware/timeout.py +0 -0
  55. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/middleware/traceid.py +0 -0
  56. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/models/__init__.py +0 -0
  57. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/models/base_http.py +0 -0
  58. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/models/log.py +0 -0
  59. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/models/mqlistener_config.py +0 -0
  60. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/models/mqmsg_model.py +0 -0
  61. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/models/mqsend_config.py +0 -0
  62. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/models/sso_user.py +0 -0
  63. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/notice/__init__.py +0 -0
  64. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/notice/uvicorn_monitor.py +0 -0
  65. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/rabbitmq/rabbitmq_pool.py +0 -0
  66. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/rabbitmq/rabbitmq_service.py +0 -0
  67. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/rabbitmq/rabbitmq_service_connection_monitor.py +0 -0
  68. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/rabbitmq/rabbitmq_service_consumer_manager.py +0 -0
  69. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/rabbitmq/rabbitmq_service_core.py +0 -0
  70. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/rabbitmq/rabbitmq_service_producer_manager.py +0 -0
  71. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/sentry/__init__.py +0 -0
  72. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/sentry/sy_sentry.py +0 -0
  73. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/sse/__init__.py +0 -0
  74. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/sse/event.py +0 -0
  75. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/sse/sse.py +0 -0
  76. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/__init__.py +0 -0
  77. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/example.py +0 -0
  78. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/example2.py +0 -0
  79. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/feign.py +0 -0
  80. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/feign_client.py +0 -0
  81. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/nacos_config_manager.py +0 -0
  82. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/nacos_heartbeat_manager.py +0 -0
  83. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/nacos_service.py +0 -0
  84. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/nacos_service_discovery.py +0 -0
  85. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/nacos_service_registration.py +0 -0
  86. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/synacos/param.py +0 -0
  87. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/tools/__init__.py +0 -0
  88. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/tools/docs.py +0 -0
  89. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/tools/env.py +0 -0
  90. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/tools/snowflake.py +0 -0
  91. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon/tools/timing.py +0 -0
  92. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon_python_lib.egg-info/dependency_links.txt +0 -0
  93. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon_python_lib.egg-info/entry_points.txt +0 -0
  94. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon_python_lib.egg-info/requires.txt +0 -0
  95. {sycommon_python_lib-0.1.56b17 → sycommon_python_lib-0.1.57}/src/sycommon_python_lib.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sycommon-python-lib
3
- Version: 0.1.56b17
3
+ Version: 0.1.57
4
4
  Summary: Add your description here
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sycommon-python-lib"
3
- version = "0.1.56-beta17"
3
+ version = "0.1.57"
4
4
  description = "Add your description here"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -0,0 +1,37 @@
1
+ from sycommon.llm.llm_logger import LLMLogger
2
+ from langchain.chat_models import init_chat_model
3
+ from sycommon.config.LLMConfig import LLMConfig
4
+ from sycommon.llm.sy_langfuse import LangfuseInitializer
5
+ from sycommon.llm.usage_token import LLMWithAutoTokenUsage
6
+
7
+
8
+ def get_llm(
9
+ model: str = None,
10
+ streaming: bool = False
11
+ ) -> LLMWithAutoTokenUsage:
12
+ if not model:
13
+ model = "Qwen2.5-72B"
14
+
15
+ llmConfig = LLMConfig.from_config(model)
16
+ if not llmConfig:
17
+ raise Exception(f"无效的模型配置:{model}")
18
+
19
+ # 初始化Langfuse
20
+ langfuse_callbacks, langfuse = LangfuseInitializer.get()
21
+
22
+ callbacks = [LLMLogger()] + langfuse_callbacks
23
+
24
+ llm = init_chat_model(
25
+ model_provider=llmConfig.provider,
26
+ model=llmConfig.model,
27
+ base_url=llmConfig.baseUrl,
28
+ api_key="-",
29
+ temperature=0.1,
30
+ streaming=streaming,
31
+ callbacks=callbacks
32
+ )
33
+
34
+ if llm is None:
35
+ raise Exception(f"初始化原始LLM实例失败:{model}")
36
+
37
+ return LLMWithAutoTokenUsage(llm, langfuse)
@@ -0,0 +1,192 @@
1
+ from typing import Dict, List, Optional, Any
2
+ from langfuse import Langfuse, LangfuseSpan, propagate_attributes
3
+ from sycommon.llm.llm_logger import LLMLogger
4
+ from langchain_core.runnables import Runnable, RunnableConfig
5
+ from langchain_core.messages import BaseMessage, HumanMessage
6
+ from sycommon.llm.llm_tokens import TokensCallbackHandler
7
+ from sycommon.logging.kafka_log import SYLogger
8
+ from sycommon.tools.env import get_env_var
9
+ from sycommon.tools.merge_headers import get_header_value
10
+
11
+
12
+ class StructuredRunnableWithToken(Runnable):
13
+ """带Token统计的Runnable类"""
14
+
15
+ def __init__(self, retry_chain: Runnable, langfuse: Optional[Langfuse]):
16
+ super().__init__()
17
+ self.retry_chain = retry_chain
18
+ self.langfuse = langfuse
19
+
20
+ def _adapt_input(self, input: Any) -> List[BaseMessage]:
21
+ """适配输入格式"""
22
+ if isinstance(input, list) and all(isinstance(x, BaseMessage) for x in input):
23
+ return input
24
+ elif isinstance(input, BaseMessage):
25
+ return [input]
26
+ elif isinstance(input, str):
27
+ return [HumanMessage(content=input)]
28
+ elif isinstance(input, dict) and "input" in input:
29
+ return [HumanMessage(content=str(input["input"]))]
30
+ else:
31
+ raise ValueError(f"不支持的输入格式:{type(input)}")
32
+
33
+ def _get_callback_config(
34
+ self,
35
+ config: Optional[RunnableConfig] = None,
36
+ trace_id: Optional[str] = None,
37
+ user_id: Optional[str] = None
38
+ ) -> tuple[RunnableConfig, TokensCallbackHandler]:
39
+ """构建包含Token统计和metadata的回调配置"""
40
+ token_handler = TokensCallbackHandler()
41
+
42
+ if config is None:
43
+ processed_config = {"callbacks": [], "metadata": {}}
44
+ else:
45
+ processed_config = config.copy()
46
+ if "callbacks" not in processed_config:
47
+ processed_config["callbacks"] = []
48
+ if "metadata" not in processed_config:
49
+ processed_config["metadata"] = {}
50
+
51
+ # 添加 Langfuse metadata
52
+ if trace_id:
53
+ processed_config["metadata"]["langfuse_session_id"] = trace_id
54
+ if user_id:
55
+ processed_config["metadata"]["langfuse_user_id"] = user_id
56
+
57
+ callbacks = processed_config["callbacks"]
58
+ if not any(isinstance(cb, LLMLogger) for cb in callbacks):
59
+ callbacks.append(LLMLogger())
60
+ callbacks.append(token_handler)
61
+
62
+ callback_types = {}
63
+ unique_callbacks = []
64
+ for cb in callbacks:
65
+ cb_type = type(cb)
66
+ if cb_type not in callback_types:
67
+ callback_types[cb_type] = cb
68
+ unique_callbacks.append(cb)
69
+
70
+ processed_config["callbacks"] = unique_callbacks
71
+
72
+ return processed_config, token_handler
73
+
74
+ def invoke(self, input: Any, config: Optional[RunnableConfig] = None, **kwargs) -> Dict[str, Any]:
75
+ # 获取 trace_id 和 user_id
76
+ trace_id = SYLogger.get_trace_id()
77
+ userid = get_header_value(SYLogger.get_headers(), "x-userid-header")
78
+ syVersion = get_header_value(SYLogger.get_headers(), "s-y-version")
79
+ user_id = userid or syVersion or get_env_var('VERSION')
80
+
81
+ # 判断是否启用 Langfuse
82
+ if self.langfuse:
83
+ try:
84
+ with self.langfuse.start_as_current_observation(as_type="span", name="invoke") as span:
85
+ with propagate_attributes(session_id=trace_id, user_id=user_id):
86
+ span.update_trace(user_id=user_id, session_id=trace_id)
87
+ return self._execute_chain(input, config, trace_id, user_id, span)
88
+ except Exception as e:
89
+ # Langfuse 跟踪失败不应阻断业务,降级执行
90
+ SYLogger.error(f"Langfuse 同步跟踪失败: {str(e)}", exc_info=True)
91
+ return self._execute_chain(input, config, trace_id, user_id, None)
92
+ else:
93
+ # 未启用 Langfuse,直接执行业务逻辑
94
+ return self._execute_chain(input, config, trace_id, user_id, None)
95
+
96
+ async def ainvoke(self, input: Any, config: Optional[RunnableConfig] = None, **kwargs) -> Dict[str, Any]:
97
+ # 获取 trace_id 和 user_id
98
+ trace_id = SYLogger.get_trace_id()
99
+ userid = get_header_value(SYLogger.get_headers(), "x-userid-header")
100
+ syVersion = get_header_value(SYLogger.get_headers(), "s-y-version")
101
+ user_id = userid or syVersion or get_env_var('VERSION')
102
+
103
+ # 判断是否启用 Langfuse
104
+ if self.langfuse:
105
+ try:
106
+ with self.langfuse.start_as_current_observation(as_type="span", name="ainvoke") as span:
107
+ with propagate_attributes(session_id=trace_id, user_id=user_id):
108
+ span.update_trace(user_id=user_id, session_id=trace_id)
109
+ return await self._aexecute_chain(input, config, trace_id, user_id, span)
110
+ except Exception as e:
111
+ # Langfuse 跟踪失败不应阻断业务,降级执行
112
+ SYLogger.error(f"Langfuse 异步跟踪失败: {str(e)}", exc_info=True)
113
+ return await self._aexecute_chain(input, config, trace_id, user_id, None)
114
+ else:
115
+ # 未启用 Langfuse,直接执行业务逻辑
116
+ return await self._aexecute_chain(input, config, trace_id, user_id, None)
117
+
118
+ def _execute_chain(
119
+ self,
120
+ input: Any,
121
+ config: Optional[RunnableConfig],
122
+ trace_id: str,
123
+ user_id: str,
124
+ span: LangfuseSpan
125
+ ) -> Dict[str, Any]:
126
+ """执行实际的调用逻辑 (同步)"""
127
+ try:
128
+ processed_config, token_handler = self._get_callback_config(
129
+ config,
130
+ trace_id=trace_id,
131
+ user_id=user_id
132
+ )
133
+
134
+ adapted_input = self._adapt_input(input)
135
+ input_data = {"messages": adapted_input}
136
+
137
+ if span:
138
+ span.update_trace(input=input_data)
139
+
140
+ structured_result = self.retry_chain.invoke(
141
+ input_data,
142
+ config=processed_config
143
+ )
144
+
145
+ if span:
146
+ span.update_trace(output=structured_result)
147
+
148
+ token_usage = token_handler.usage_metadata
149
+ structured_result._token_usage_ = token_usage
150
+
151
+ return structured_result
152
+ except Exception as e:
153
+ SYLogger.error(f"同步LLM调用失败: {str(e)}", exc_info=True)
154
+ return None
155
+
156
+ async def _aexecute_chain(
157
+ self,
158
+ input: Any,
159
+ config: Optional[RunnableConfig],
160
+ trace_id: str,
161
+ user_id: str,
162
+ span: LangfuseSpan
163
+ ) -> Dict[str, Any]:
164
+ """执行实际的调用逻辑 (异步)"""
165
+ try:
166
+ processed_config, token_handler = self._get_callback_config(
167
+ config,
168
+ trace_id=trace_id,
169
+ user_id=user_id
170
+ )
171
+
172
+ adapted_input = self._adapt_input(input)
173
+ input_data = {"messages": adapted_input}
174
+
175
+ if span:
176
+ span.update_trace(input=input_data)
177
+
178
+ structured_result = await self.retry_chain.ainvoke(
179
+ input_data,
180
+ config=processed_config
181
+ )
182
+
183
+ if span:
184
+ span.update_trace(output=structured_result)
185
+
186
+ token_usage = token_handler.usage_metadata
187
+ structured_result._token_usage_ = token_usage
188
+
189
+ return structured_result
190
+ except Exception as e:
191
+ SYLogger.error(f"异步LLM调用失败: {str(e)}", exc_info=True)
192
+ return None
@@ -0,0 +1,103 @@
1
+ import os
2
+ from typing import Tuple, List, Optional, Any, Dict
3
+ from langfuse import Langfuse, get_client
4
+ from sycommon.config.Config import Config, SingletonMeta
5
+ from sycommon.logging.kafka_log import SYLogger
6
+ from langfuse.langchain import CallbackHandler
7
+ from sycommon.tools.env import get_env_var
8
+ from sycommon.tools.merge_headers import get_header_value
9
+
10
+
11
+ class LangfuseInitializer(metaclass=SingletonMeta):
12
+ """
13
+ Langfuse 初始化管理器
14
+ """
15
+
16
+ def __init__(self):
17
+ self._langfuse_client: Optional[Langfuse] = None
18
+ self._base_callbacks: List[Any] = []
19
+
20
+ # 执行初始化
21
+ self._initialize()
22
+
23
+ def _initialize(self):
24
+ """执行实际的配置读取和组件创建"""
25
+ try:
26
+ config_dict = Config().config
27
+
28
+ server_name = config_dict.get('Name', '')
29
+ langfuse_configs = config_dict.get('LangfuseConfig', [])
30
+ environment = config_dict.get('Nacos', {}).get('namespaceId', '')
31
+
32
+ # 3. 查找匹配的配置项
33
+ target_config = next(
34
+ (item for item in langfuse_configs if item.get(
35
+ 'name') == server_name), None
36
+ )
37
+
38
+ # 4. 如果启用且配置存在,初始化 Langfuse
39
+ if target_config and target_config.get('enable', False):
40
+ # 设置环境变量
41
+ os.environ["LANGFUSE_SECRET_KEY"] = target_config.get(
42
+ 'secretKey', '')
43
+ os.environ["LANGFUSE_PUBLIC_KEY"] = target_config.get(
44
+ 'publicKey', '')
45
+ os.environ["LANGFUSE_BASE_URL"] = target_config.get(
46
+ 'baseUrl', '')
47
+ os.environ["LANGFUSE_TRACING_ENVIRONMENT"] = environment
48
+ os.environ["OTEL_SERVICE_NAME"] = server_name
49
+
50
+ self._langfuse_client = get_client()
51
+
52
+ langfuse_handler = CallbackHandler()
53
+ self._base_callbacks.append(langfuse_handler)
54
+
55
+ SYLogger.info(f"Langfuse 初始化成功 [Service: {server_name}]")
56
+ else:
57
+ SYLogger.info(f"Langfuse 未启用或未找到匹配配置 [Service: {server_name}]")
58
+
59
+ except Exception as e:
60
+ SYLogger.error(f"Langfuse 初始化异常: {str(e)}", exc_info=True)
61
+
62
+ @property
63
+ def callbacks(self) -> List[Any]:
64
+ """获取回调列表"""
65
+ return self._base_callbacks
66
+
67
+ @property
68
+ def metadata(self) -> Dict[str, Any]:
69
+ """动态生成包含 langfuse_session_id 和 langfuse_user_id 的 metadata"""
70
+ trace_id = SYLogger.get_trace_id()
71
+ userid = get_header_value(
72
+ SYLogger.get_headers(), "x-userid-header")
73
+ syVersion = get_header_value(
74
+ SYLogger.get_headers(), "s-y-version")
75
+ user_id = userid or syVersion or get_env_var('VERSION')
76
+ metadata_config = {
77
+ "langfuse_session_id": trace_id,
78
+ "langfuse_user_id": user_id,
79
+ }
80
+
81
+ return metadata_config
82
+
83
+ @property
84
+ def client(self) -> Optional[Langfuse]:
85
+ """获取 Langfuse 原生客户端实例"""
86
+ return self._langfuse_client
87
+
88
+ @property
89
+ def config(self) -> Dict[str, Any]:
90
+ return {
91
+ "callbacks": self.callbacks,
92
+ "metadata": self.metadata,
93
+ }
94
+
95
+ def get_components(self) -> Tuple[List[Any], Optional[Langfuse]]:
96
+ """获取 Langfuse 组件"""
97
+ return list(self._base_callbacks), self._langfuse_client
98
+
99
+ @staticmethod
100
+ def get() -> Tuple[List[Any], Optional[Langfuse]]:
101
+ """一句话获取组件"""
102
+ initializer = LangfuseInitializer()
103
+ return initializer.get_components()
@@ -0,0 +1,117 @@
1
+ from typing import Type, List, Optional, Callable
2
+ from langfuse import Langfuse
3
+ from langchain_core.language_models import BaseChatModel
4
+ from langchain_core.runnables import Runnable, RunnableLambda
5
+ from langchain_core.output_parsers import PydanticOutputParser
6
+ from langchain_core.messages import BaseMessage, HumanMessage
7
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
8
+ from pydantic import BaseModel, ValidationError, Field
9
+ from sycommon.llm.struct_token import StructuredRunnableWithToken
10
+
11
+
12
+ class LLMWithAutoTokenUsage(BaseChatModel):
13
+ """自动为结构化调用返回token_usage的LLM包装类"""
14
+ llm: BaseChatModel = Field(default=None)
15
+ langfuse: Optional[Langfuse] = Field(default=None, exclude=True)
16
+
17
+ def __init__(self, llm: BaseChatModel, langfuse: Langfuse, **kwargs):
18
+ super().__init__(llm=llm, langfuse=langfuse, **kwargs)
19
+
20
+ def with_structured_output(
21
+ self,
22
+ output_model: Type[BaseModel],
23
+ max_retries: int = 3,
24
+ is_extract: bool = False,
25
+ override_prompt: ChatPromptTemplate = None,
26
+ custom_processors: Optional[List[Callable[[str], str]]] = None,
27
+ custom_parser: Optional[Callable[[str], BaseModel]] = None
28
+ ) -> Runnable:
29
+ """返回支持自动统计Token的结构化Runnable"""
30
+ parser = PydanticOutputParser(pydantic_object=output_model)
31
+
32
+ # 提示词模板
33
+ accuracy_instructions = """
34
+ 字段值的抽取准确率(0~1之间),评分规则:
35
+ 1.0(完全准确):直接从原文提取,无需任何加工,且格式与原文完全一致
36
+ 0.9(轻微处理):数据来源明确,但需进行格式标准化或冗余信息剔除(不改变原始数值)
37
+ 0.8(有限推断):数据需通过上下文关联或简单计算得出,仍有明确依据
38
+ 0.8以下(不可靠):数据需大量推测、存在歧义或来源不明,处理方式:直接忽略该数据,设置为None
39
+ """
40
+
41
+ if is_extract:
42
+ prompt = ChatPromptTemplate.from_messages([
43
+ MessagesPlaceholder(variable_name="messages"),
44
+ HumanMessage(content=f"""
45
+ 请提取信息并遵循以下规则:
46
+ 1. 准确率要求:{accuracy_instructions.strip()}
47
+ 2. 输出格式:{parser.get_format_instructions()}
48
+ """)
49
+ ])
50
+ else:
51
+ prompt = override_prompt or ChatPromptTemplate.from_messages([
52
+ MessagesPlaceholder(variable_name="messages"),
53
+ HumanMessage(content=f"""
54
+ 输出格式:{parser.get_format_instructions()}
55
+ """)
56
+ ])
57
+
58
+ # 文本处理函数
59
+ def extract_response_content(response: BaseMessage) -> str:
60
+ try:
61
+ return response.content
62
+ except Exception as e:
63
+ raise ValueError(f"提取响应内容失败:{str(e)}") from e
64
+
65
+ def strip_code_block_markers(content: str) -> str:
66
+ try:
67
+ return content.strip("```json").strip("```").strip()
68
+ except Exception as e:
69
+ raise ValueError(f"移除代码块标记失败:{str(e)}") from e
70
+
71
+ def normalize_in_json(content: str) -> str:
72
+ try:
73
+ return content.replace("None", "null").replace("none", "null").replace("NONE", "null").replace("''", '""')
74
+ except Exception as e:
75
+ raise ValueError(f"JSON格式化失败:{str(e)}") from e
76
+
77
+ def default_parse_to_pydantic(content: str) -> BaseModel:
78
+ try:
79
+ return parser.parse(content)
80
+ except (ValidationError, ValueError) as e:
81
+ raise ValueError(f"解析结构化结果失败:{str(e)}") from e
82
+
83
+ # ========== 构建处理链 ==========
84
+ base_chain = prompt | self.llm | RunnableLambda(
85
+ extract_response_content)
86
+
87
+ # 文本处理链
88
+ process_runnables = custom_processors or [
89
+ RunnableLambda(strip_code_block_markers),
90
+ RunnableLambda(normalize_in_json)
91
+ ]
92
+ process_chain = base_chain
93
+ for runnable in process_runnables:
94
+ process_chain = process_chain | runnable
95
+
96
+ # 解析链
97
+ parse_chain = process_chain | RunnableLambda(
98
+ custom_parser or default_parse_to_pydantic)
99
+
100
+ # 重试链
101
+ retry_chain = parse_chain.with_retry(
102
+ retry_if_exception_type=(ValidationError, ValueError),
103
+ stop_after_attempt=max_retries,
104
+ wait_exponential_jitter=True,
105
+ exponential_jitter_params={
106
+ "initial": 0.1, "max": 3.0, "exp_base": 2.0, "jitter": 1.0}
107
+ )
108
+
109
+ return StructuredRunnableWithToken(retry_chain, self.langfuse)
110
+
111
+ # ========== 实现BaseChatModel抽象方法 ==========
112
+ def _generate(self, messages, stop=None, run_manager=None, ** kwargs):
113
+ return self.llm._generate(messages, stop=stop, run_manager=run_manager, ** kwargs)
114
+
115
+ @property
116
+ def _llm_type(self) -> str:
117
+ return self.llm._llm_type
@@ -27,6 +27,7 @@ class RabbitMQClient:
27
27
  exchange_name: str = "system.topic.exchange",
28
28
  exchange_type: str = "topic",
29
29
  queue_name: Optional[str] = None,
30
+ app_name: Optional[str] = None,
30
31
  routing_key: str = "#",
31
32
  durable: bool = True,
32
33
  auto_delete: bool = False,
@@ -45,6 +46,7 @@ class RabbitMQClient:
45
46
  logger.warning(f"无效的exchange_type: {exchange_type},默认使用'topic'")
46
47
  self.exchange_type = ExchangeType.TOPIC
47
48
 
49
+ self.app_name = app_name.strip() if app_name else None
48
50
  self.queue_name = queue_name.strip() if queue_name else None
49
51
  self.routing_key = routing_key.strip() if routing_key else "#"
50
52
  self.durable = durable
@@ -104,7 +106,7 @@ class RabbitMQClient:
104
106
  logger.info(f"交换机重建成功: {self.exchange_name}")
105
107
 
106
108
  # 声明队列
107
- if self.queue_name:
109
+ if self.queue_name and self.queue_name.endswith(f".{self.app_name}"):
108
110
  self._queue = await self._channel.declare_queue(
109
111
  name=self.queue_name,
110
112
  durable=self.durable,
@@ -181,7 +183,7 @@ class RabbitMQClient:
181
183
  await self._rebuild_resources()
182
184
 
183
185
  # --- 阶段3: 恢复消费 ---
184
- if was_consuming and self._message_handler and self.queue_name:
186
+ if was_consuming and self._message_handler and self.queue_name and self.queue_name.endswith(f".{self.app_name}"):
185
187
  logger.info("🔄 检测到重连前处于消费状态,尝试自动恢复...")
186
188
  try:
187
189
  self._queue = await self._channel.declare_queue(
@@ -270,7 +272,6 @@ class RabbitMQClient:
270
272
  routing_key=message.routing_key,
271
273
  delivery_tag=message.delivery_tag,
272
274
  traceId=message.headers.get("trace-id"),
273
- headers=message.headers
274
275
  )
275
276
 
276
277
  SYLogger.set_trace_id(msg_obj.traceId)
@@ -317,7 +318,7 @@ class RabbitMQClient:
317
318
  await self.connect()
318
319
 
319
320
  if not self._queue:
320
- if self.queue_name:
321
+ if self.queue_name and self.queue_name.endswith(f".{self.app_name}"):
321
322
  self._queue = await self._channel.declare_queue(
322
323
  name=self.queue_name,
323
324
  durable=self.durable,
@@ -391,7 +392,7 @@ class RabbitMQClient:
391
392
 
392
393
  result = await self._exchange.publish(
393
394
  message=message,
394
- routing_key=self.routing_key or self.queue_name or "#",
395
+ routing_key=self.routing_key,
395
396
  mandatory=True,
396
397
  timeout=5.0
397
398
  )
@@ -100,13 +100,18 @@ class RabbitMQClientManager(RabbitMQCoreService):
100
100
  f"是否创建队列: {create_if_not_exists}"
101
101
  )
102
102
 
103
+ final_queue_name = None
104
+ if create_if_not_exists and processed_queue_name.endswith(f".{app_name}"):
105
+ final_queue_name = processed_queue_name
106
+
103
107
  # 创建客户端实例
104
108
  client = RabbitMQClient(
105
109
  connection_pool=cls._connection_pool,
106
110
  exchange_name=cls._config.get(
107
111
  'exchange_name', "system.topic.exchange"),
108
112
  exchange_type=kwargs.get('exchange_type', "topic"),
109
- queue_name=None if not create_if_not_exists else processed_queue_name,
113
+ queue_name=final_queue_name,
114
+ app_name=app_name,
110
115
  routing_key=kwargs.get(
111
116
  'routing_key',
112
117
  f"{queue_name.split('.')[0]}.#"