txcode-sdk 0.6.0__py3-none-any.whl → 0.7.0__py3-none-any.whl
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.
- txcode_sdk/provider/base.py +129 -8
- txcode_sdk/provider/deepseek_provider.py +112 -4
- txcode_sdk/provider/openai_provider.py +94 -225
- {txcode_sdk-0.6.0.dist-info → txcode_sdk-0.7.0.dist-info}/METADATA +1 -1
- {txcode_sdk-0.6.0.dist-info → txcode_sdk-0.7.0.dist-info}/RECORD +9 -9
- {txcode_sdk-0.6.0.dist-info → txcode_sdk-0.7.0.dist-info}/WHEEL +0 -0
- {txcode_sdk-0.6.0.dist-info → txcode_sdk-0.7.0.dist-info}/entry_points.txt +0 -0
- {txcode_sdk-0.6.0.dist-info → txcode_sdk-0.7.0.dist-info}/licenses/LICENSE +0 -0
- {txcode_sdk-0.6.0.dist-info → txcode_sdk-0.7.0.dist-info}/top_level.txt +0 -0
txcode_sdk/provider/base.py
CHANGED
|
@@ -1,12 +1,38 @@
|
|
|
1
|
-
"""BaseProvider 抽象基类(ReAct 循环的 Provider
|
|
1
|
+
"""BaseProvider 抽象基类(ReAct 循环的 Provider 接口 + 公共实现)。
|
|
2
2
|
|
|
3
|
+
公共能力(get_model/set_model/get_base_url/日志/消息格式化/响应解析)在此实现,
|
|
4
|
+
OpenAIProvider 与 DeepSeekProvider 等具体 Provider 继承本类,仅保留各自的请求差异。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import base64
|
|
8
|
+
import json
|
|
9
|
+
import mimetypes
|
|
3
10
|
from abc import ABC, abstractmethod
|
|
4
|
-
from
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, AsyncGenerator, Dict, List, Optional, Union
|
|
14
|
+
|
|
15
|
+
from ..types import ChatMessage, ImageContent, ProviderResponse, TokenUsage
|
|
16
|
+
|
|
5
17
|
|
|
6
|
-
|
|
18
|
+
def _resolve_image_url(url: str) -> str:
|
|
19
|
+
if url.startswith("data:"):
|
|
20
|
+
return url
|
|
21
|
+
path = Path(url)
|
|
22
|
+
if path.is_file():
|
|
23
|
+
mime_type, _ = mimetypes.guess_type(str(path))
|
|
24
|
+
mime_type = mime_type or "image/png"
|
|
25
|
+
with open(path, "rb") as f:
|
|
26
|
+
b64 = base64.b64encode(f.read()).decode("utf-8")
|
|
27
|
+
return f"data:{mime_type};base64,{b64}"
|
|
28
|
+
return url
|
|
7
29
|
|
|
8
30
|
|
|
9
31
|
class BaseProvider(ABC):
|
|
32
|
+
def __init__(self, base_url: str = "", model: str = ""):
|
|
33
|
+
self._base_url = base_url
|
|
34
|
+
self._model = model
|
|
35
|
+
|
|
10
36
|
@abstractmethod
|
|
11
37
|
async def chat(
|
|
12
38
|
self,
|
|
@@ -26,13 +52,108 @@ class BaseProvider(ABC):
|
|
|
26
52
|
) -> AsyncGenerator[str, None]:
|
|
27
53
|
...
|
|
28
54
|
|
|
29
|
-
@abstractmethod
|
|
30
55
|
def get_model(self) -> str:
|
|
31
|
-
|
|
56
|
+
return getattr(self, "_model", "")
|
|
32
57
|
|
|
33
58
|
def get_base_url(self) -> str:
|
|
34
|
-
return ""
|
|
59
|
+
return getattr(self, "_base_url", "")
|
|
35
60
|
|
|
36
61
|
def set_model(self, model: str):
|
|
37
|
-
"""
|
|
38
|
-
|
|
62
|
+
"""运行期切换模型(base_url/api_key 不变,子类公共实现)。"""
|
|
63
|
+
self._model = model
|
|
64
|
+
|
|
65
|
+
def _write_log(self, log_context: dict, event: str, extra: dict):
|
|
66
|
+
work_dir = log_context.get("work_dir", ".")
|
|
67
|
+
log_dir = Path(work_dir) / ".txcode" / "log"
|
|
68
|
+
log_dir.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
entry = {
|
|
70
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
71
|
+
"session_id": log_context.get("session_id", ""),
|
|
72
|
+
"agent_type": log_context.get("agent_type", ""),
|
|
73
|
+
"iteration": log_context.get("iteration", 0),
|
|
74
|
+
"event": event,
|
|
75
|
+
**extra,
|
|
76
|
+
}
|
|
77
|
+
with open(log_dir / "txcode_access.log", "a", encoding="utf-8") as f:
|
|
78
|
+
f.write(json.dumps(entry, ensure_ascii=False, indent=2) + "\n")
|
|
79
|
+
|
|
80
|
+
async def _resolve_messages(self, messages: List[ChatMessage]) -> List[dict]:
|
|
81
|
+
resolved: List[dict] = []
|
|
82
|
+
for msg in messages:
|
|
83
|
+
formatted = self._format_message(msg)
|
|
84
|
+
formatted["content"] = await self._resolve_content_images(msg.content)
|
|
85
|
+
resolved.append(formatted)
|
|
86
|
+
return resolved
|
|
87
|
+
|
|
88
|
+
def _format_message(self, msg: ChatMessage) -> dict:
|
|
89
|
+
formatted: dict = {"role": msg.role}
|
|
90
|
+
content = msg.content
|
|
91
|
+
if isinstance(content, list):
|
|
92
|
+
formatted["content"] = [c.to_dict() if hasattr(c, "to_dict") else c for c in content]
|
|
93
|
+
else:
|
|
94
|
+
formatted["content"] = content
|
|
95
|
+
|
|
96
|
+
if msg.name:
|
|
97
|
+
formatted["name"] = msg.name
|
|
98
|
+
if msg.tool_call_id:
|
|
99
|
+
formatted["tool_call_id"] = msg.tool_call_id
|
|
100
|
+
if msg.tool_calls:
|
|
101
|
+
formatted["tool_calls"] = msg.tool_calls
|
|
102
|
+
if msg.reasoning_content:
|
|
103
|
+
formatted["reasoning_content"] = msg.reasoning_content
|
|
104
|
+
return formatted
|
|
105
|
+
|
|
106
|
+
async def _resolve_content_images(self, content: Union[str, list]) -> Union[str, list]:
|
|
107
|
+
if isinstance(content, str):
|
|
108
|
+
return content
|
|
109
|
+
resolved: list = []
|
|
110
|
+
for c in content:
|
|
111
|
+
if isinstance(c, ImageContent):
|
|
112
|
+
resolved.append(ImageContent(url=_resolve_image_url(c.image_url["url"])).to_dict())
|
|
113
|
+
elif hasattr(c, "to_dict"):
|
|
114
|
+
resolved.append(c.to_dict())
|
|
115
|
+
else:
|
|
116
|
+
resolved.append(c)
|
|
117
|
+
return resolved
|
|
118
|
+
|
|
119
|
+
def _parse_response(self, response: dict) -> ProviderResponse:
|
|
120
|
+
choices = response.get("choices") or []
|
|
121
|
+
if not choices:
|
|
122
|
+
raise RuntimeError("Invalid response: no choices")
|
|
123
|
+
choice = choices[0]
|
|
124
|
+
msg = choice.get("message") or {}
|
|
125
|
+
|
|
126
|
+
usage = None
|
|
127
|
+
usage_data = response.get("usage")
|
|
128
|
+
if usage_data:
|
|
129
|
+
usage = TokenUsage(
|
|
130
|
+
prompt_tokens=usage_data.get("prompt_tokens", 0),
|
|
131
|
+
completion_tokens=usage_data.get("completion_tokens", 0),
|
|
132
|
+
total_tokens=usage_data.get("total_tokens", 0),
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
result = ProviderResponse(
|
|
136
|
+
content=msg.get("content") or "",
|
|
137
|
+
finish_reason=choice.get("finish_reason") or "stop",
|
|
138
|
+
usage=usage,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
reasoning = msg.get("reasoning_content") or response.get("reasoning")
|
|
142
|
+
if reasoning:
|
|
143
|
+
result.reasoning = reasoning
|
|
144
|
+
|
|
145
|
+
tool_calls = msg.get("tool_calls")
|
|
146
|
+
if tool_calls:
|
|
147
|
+
result.tool_calls = [
|
|
148
|
+
{
|
|
149
|
+
"id": tc.get("id", ""),
|
|
150
|
+
"type": tc.get("type", "function"),
|
|
151
|
+
"function": {
|
|
152
|
+
"name": (tc.get("function") or {}).get("name", ""),
|
|
153
|
+
"arguments": (tc.get("function") or {}).get("arguments", ""),
|
|
154
|
+
},
|
|
155
|
+
}
|
|
156
|
+
for tc in tool_calls
|
|
157
|
+
]
|
|
158
|
+
|
|
159
|
+
return result
|
|
@@ -1,13 +1,121 @@
|
|
|
1
|
-
"""DeepSeek Provider
|
|
1
|
+
"""DeepSeek Provider:对齐 TS 端 deepseek.provider.ts 行为,直接继承 BaseProvider。
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
- chat:开启思考模式(thinking.enabled + reasoning_effort: max),默认 max_tokens 65536
|
|
4
|
+
- chat_stream:关闭思考模式(thinking.disabled),默认 max_tokens 2000
|
|
5
|
+
- assistant 消息无 reasoning_content 时补 "null" 占位,规避 DeepSeek API 校验错误
|
|
6
|
+
- reasoning 提取优先级:msg.reasoning_content → msg.reasoning → response.reasoning → msg.content
|
|
7
|
+
"""
|
|
4
8
|
|
|
9
|
+
from typing import Any, AsyncGenerator, Dict, List, Optional
|
|
5
10
|
|
|
6
|
-
|
|
11
|
+
from ..types import ChatMessage, ProviderResponse
|
|
12
|
+
from .base import BaseProvider
|
|
13
|
+
from .txcode_ai import TxCodeAI
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class DeepSeekProvider(BaseProvider):
|
|
7
17
|
def __init__(
|
|
8
18
|
self,
|
|
9
19
|
api_key: str,
|
|
10
20
|
base_url: str = "https://api.deepseek.com/v1",
|
|
11
21
|
model: str = "deepseek-chat",
|
|
12
22
|
):
|
|
13
|
-
super().__init__(
|
|
23
|
+
super().__init__(base_url=base_url, model=model)
|
|
24
|
+
self._client = TxCodeAI(
|
|
25
|
+
api_key=api_key,
|
|
26
|
+
base_url=base_url,
|
|
27
|
+
default_headers={
|
|
28
|
+
"HTTP-Referer": "https://www.homecommunity.cn",
|
|
29
|
+
"X-Title": "txcode",
|
|
30
|
+
},
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
async def chat(
|
|
34
|
+
self,
|
|
35
|
+
messages: List[ChatMessage],
|
|
36
|
+
tools: Optional[List[dict]] = None,
|
|
37
|
+
abort_signal: Any = None,
|
|
38
|
+
log_context: Optional[dict] = None,
|
|
39
|
+
) -> ProviderResponse:
|
|
40
|
+
resolved = await self._resolve_messages(messages)
|
|
41
|
+
kwargs: Dict[str, Any] = {
|
|
42
|
+
"model": self._model,
|
|
43
|
+
"messages": resolved,
|
|
44
|
+
"max_tokens": 65536,
|
|
45
|
+
"thinking": {"type": "enabled"},
|
|
46
|
+
"reasoning_effort": "max",
|
|
47
|
+
}
|
|
48
|
+
if tools:
|
|
49
|
+
kwargs["tools"] = tools
|
|
50
|
+
kwargs["tool_choice"] = "auto"
|
|
51
|
+
|
|
52
|
+
if log_context:
|
|
53
|
+
self._write_log(log_context, "request", {
|
|
54
|
+
"model": self._model,
|
|
55
|
+
"messages": resolved,
|
|
56
|
+
"tools": tools or [],
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
response = await self._client.chat_completions(**kwargs)
|
|
60
|
+
parsed = self._parse_response(response)
|
|
61
|
+
|
|
62
|
+
if log_context:
|
|
63
|
+
self._write_log(log_context, "response", {
|
|
64
|
+
"model": self._model,
|
|
65
|
+
"finish_reason": parsed.finish_reason,
|
|
66
|
+
"content": parsed.content or "",
|
|
67
|
+
"tool_calls": parsed.tool_calls or [],
|
|
68
|
+
"usage": {
|
|
69
|
+
"prompt_tokens": parsed.usage.prompt_tokens,
|
|
70
|
+
"completion_tokens": parsed.usage.completion_tokens,
|
|
71
|
+
"total_tokens": parsed.usage.total_tokens,
|
|
72
|
+
} if parsed.usage else None,
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
return parsed
|
|
76
|
+
|
|
77
|
+
async def chat_stream(
|
|
78
|
+
self,
|
|
79
|
+
messages: List[ChatMessage],
|
|
80
|
+
tools: Optional[List[dict]] = None,
|
|
81
|
+
abort_signal: Any = None,
|
|
82
|
+
) -> AsyncGenerator[str, None]:
|
|
83
|
+
resolved = await self._resolve_messages(messages)
|
|
84
|
+
kwargs: Dict[str, Any] = {
|
|
85
|
+
"model": self._model,
|
|
86
|
+
"messages": resolved,
|
|
87
|
+
"max_tokens": 2000,
|
|
88
|
+
"stream": True,
|
|
89
|
+
"thinking": {"type": "disabled"},
|
|
90
|
+
}
|
|
91
|
+
if tools:
|
|
92
|
+
kwargs["tools"] = tools
|
|
93
|
+
|
|
94
|
+
async for chunk in self._client.chat_completions_stream(**kwargs):
|
|
95
|
+
choices = chunk.get("choices") or []
|
|
96
|
+
if not choices:
|
|
97
|
+
continue
|
|
98
|
+
delta = choices[0].get("delta") or {}
|
|
99
|
+
content = delta.get("content")
|
|
100
|
+
if content:
|
|
101
|
+
yield content
|
|
102
|
+
|
|
103
|
+
def _format_message(self, msg: ChatMessage) -> dict:
|
|
104
|
+
formatted = super()._format_message(msg)
|
|
105
|
+
if msg.role == "assistant" and not formatted.get("reasoning_content"):
|
|
106
|
+
formatted["reasoning_content"] = "null"
|
|
107
|
+
return formatted
|
|
108
|
+
|
|
109
|
+
def _parse_response(self, response: dict) -> ProviderResponse:
|
|
110
|
+
result = super()._parse_response(response)
|
|
111
|
+
choice = (response.get("choices") or [{}])[0]
|
|
112
|
+
msg = choice.get("message") or {}
|
|
113
|
+
reasoning = (
|
|
114
|
+
msg.get("reasoning_content")
|
|
115
|
+
or msg.get("reasoning")
|
|
116
|
+
or response.get("reasoning")
|
|
117
|
+
or (msg.get("content") or "")
|
|
118
|
+
)
|
|
119
|
+
if reasoning:
|
|
120
|
+
result.reasoning = reasoning
|
|
121
|
+
return result
|
|
@@ -1,225 +1,94 @@
|
|
|
1
|
-
"""OpenAI Provider:基于自研 TxCodeAI(urllib)实现,零 openai SDK 依赖。"""
|
|
2
|
-
|
|
3
|
-
import
|
|
4
|
-
|
|
5
|
-
import
|
|
6
|
-
from
|
|
7
|
-
from
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
"
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
if log_context:
|
|
96
|
-
self._write_log(log_context, "request", {
|
|
97
|
-
"model": self._model,
|
|
98
|
-
"messages": resolved,
|
|
99
|
-
"tools": tools or [],
|
|
100
|
-
})
|
|
101
|
-
|
|
102
|
-
response = await self._client.chat_completions(**kwargs)
|
|
103
|
-
parsed = self._parse_response(response)
|
|
104
|
-
|
|
105
|
-
if log_context:
|
|
106
|
-
self._write_log(log_context, "response", {
|
|
107
|
-
"model": self._model,
|
|
108
|
-
"finish_reason": parsed.finish_reason,
|
|
109
|
-
"content": parsed.content or "",
|
|
110
|
-
"tool_calls": parsed.tool_calls or [],
|
|
111
|
-
"usage": {
|
|
112
|
-
"prompt_tokens": parsed.usage.prompt_tokens,
|
|
113
|
-
"completion_tokens": parsed.usage.completion_tokens,
|
|
114
|
-
"total_tokens": parsed.usage.total_tokens,
|
|
115
|
-
} if parsed.usage else None,
|
|
116
|
-
})
|
|
117
|
-
|
|
118
|
-
return parsed
|
|
119
|
-
|
|
120
|
-
async def chat_stream(
|
|
121
|
-
self,
|
|
122
|
-
messages: List[ChatMessage],
|
|
123
|
-
tools: Optional[List[dict]] = None,
|
|
124
|
-
abort_signal: Any = None,
|
|
125
|
-
) -> AsyncGenerator[str, None]:
|
|
126
|
-
resolved = await self._resolve_messages(messages)
|
|
127
|
-
kwargs: Dict[str, Any] = {
|
|
128
|
-
"model": self._model,
|
|
129
|
-
"messages": resolved,
|
|
130
|
-
"temperature": 0.7,
|
|
131
|
-
"max_tokens": 2000,
|
|
132
|
-
"stream": True,
|
|
133
|
-
}
|
|
134
|
-
if tools:
|
|
135
|
-
kwargs["tools"] = tools
|
|
136
|
-
|
|
137
|
-
async for chunk in self._client.chat_completions_stream(**kwargs):
|
|
138
|
-
choices = chunk.get("choices") or []
|
|
139
|
-
if not choices:
|
|
140
|
-
continue
|
|
141
|
-
delta = choices[0].get("delta") or {}
|
|
142
|
-
content = delta.get("content")
|
|
143
|
-
if content:
|
|
144
|
-
yield content
|
|
145
|
-
|
|
146
|
-
async def _resolve_messages(self, messages: List[ChatMessage]) -> List[dict]:
|
|
147
|
-
resolved: List[dict] = []
|
|
148
|
-
for msg in messages:
|
|
149
|
-
formatted = self._format_message(msg)
|
|
150
|
-
formatted["content"] = await self._resolve_content_images(msg.content)
|
|
151
|
-
resolved.append(formatted)
|
|
152
|
-
return resolved
|
|
153
|
-
|
|
154
|
-
def _format_message(self, msg: ChatMessage) -> dict:
|
|
155
|
-
formatted: dict = {"role": msg.role}
|
|
156
|
-
content = msg.content
|
|
157
|
-
if isinstance(content, list):
|
|
158
|
-
formatted["content"] = [c.to_dict() if hasattr(c, "to_dict") else c for c in content]
|
|
159
|
-
else:
|
|
160
|
-
formatted["content"] = content
|
|
161
|
-
|
|
162
|
-
if msg.name:
|
|
163
|
-
formatted["name"] = msg.name
|
|
164
|
-
if msg.tool_call_id:
|
|
165
|
-
formatted["tool_call_id"] = msg.tool_call_id
|
|
166
|
-
if msg.tool_calls:
|
|
167
|
-
formatted["tool_calls"] = msg.tool_calls
|
|
168
|
-
if msg.reasoning_content:
|
|
169
|
-
formatted["reasoning_content"] = msg.reasoning_content
|
|
170
|
-
return formatted
|
|
171
|
-
|
|
172
|
-
async def _resolve_content_images(self, content: Union[str, list]) -> Union[str, list]:
|
|
173
|
-
if isinstance(content, str):
|
|
174
|
-
return content
|
|
175
|
-
resolved: list = []
|
|
176
|
-
for c in content:
|
|
177
|
-
if isinstance(c, ImageContent):
|
|
178
|
-
resolved.append(ImageContent(url=_resolve_image_url(c.image_url["url"])).to_dict())
|
|
179
|
-
elif hasattr(c, "to_dict"):
|
|
180
|
-
resolved.append(c.to_dict())
|
|
181
|
-
else:
|
|
182
|
-
resolved.append(c)
|
|
183
|
-
return resolved
|
|
184
|
-
|
|
185
|
-
def _parse_response(self, response: dict) -> ProviderResponse:
|
|
186
|
-
choices = response.get("choices") or []
|
|
187
|
-
if not choices:
|
|
188
|
-
raise RuntimeError("Invalid response: no choices")
|
|
189
|
-
choice = choices[0]
|
|
190
|
-
msg = choice.get("message") or {}
|
|
191
|
-
|
|
192
|
-
usage = None
|
|
193
|
-
usage_data = response.get("usage")
|
|
194
|
-
if usage_data:
|
|
195
|
-
usage = TokenUsage(
|
|
196
|
-
prompt_tokens=usage_data.get("prompt_tokens", 0),
|
|
197
|
-
completion_tokens=usage_data.get("completion_tokens", 0),
|
|
198
|
-
total_tokens=usage_data.get("total_tokens", 0),
|
|
199
|
-
)
|
|
200
|
-
|
|
201
|
-
result = ProviderResponse(
|
|
202
|
-
content=msg.get("content") or "",
|
|
203
|
-
finish_reason=choice.get("finish_reason") or "stop",
|
|
204
|
-
usage=usage,
|
|
205
|
-
)
|
|
206
|
-
|
|
207
|
-
reasoning = msg.get("reasoning_content") or response.get("reasoning")
|
|
208
|
-
if reasoning:
|
|
209
|
-
result.reasoning = reasoning
|
|
210
|
-
|
|
211
|
-
tool_calls = msg.get("tool_calls")
|
|
212
|
-
if tool_calls:
|
|
213
|
-
result.tool_calls = [
|
|
214
|
-
{
|
|
215
|
-
"id": tc.get("id", ""),
|
|
216
|
-
"type": tc.get("type", "function"),
|
|
217
|
-
"function": {
|
|
218
|
-
"name": (tc.get("function") or {}).get("name", ""),
|
|
219
|
-
"arguments": (tc.get("function") or {}).get("arguments", ""),
|
|
220
|
-
},
|
|
221
|
-
}
|
|
222
|
-
for tc in tool_calls
|
|
223
|
-
]
|
|
224
|
-
|
|
225
|
-
return result
|
|
1
|
+
"""OpenAI Provider:基于自研 TxCodeAI(urllib)实现,零 openai SDK 依赖。"""
|
|
2
|
+
|
|
3
|
+
from typing import Any, AsyncGenerator, Dict, List, Optional
|
|
4
|
+
|
|
5
|
+
from ..types import ChatMessage, ProviderResponse
|
|
6
|
+
from .base import BaseProvider
|
|
7
|
+
from .txcode_ai import TxCodeAI
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class OpenAIProvider(BaseProvider):
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
api_key: str,
|
|
14
|
+
base_url: str = "https://api.openai.com/v1",
|
|
15
|
+
model: str = "gpt-4",
|
|
16
|
+
):
|
|
17
|
+
super().__init__(base_url=base_url, model=model)
|
|
18
|
+
self._client = TxCodeAI(
|
|
19
|
+
api_key=api_key,
|
|
20
|
+
base_url=base_url,
|
|
21
|
+
default_headers={
|
|
22
|
+
"HTTP-Referer": "https://www.homecommunity.cn",
|
|
23
|
+
"X-Title": "txcode",
|
|
24
|
+
},
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
async def chat(
|
|
28
|
+
self,
|
|
29
|
+
messages: List[ChatMessage],
|
|
30
|
+
tools: Optional[List[dict]] = None,
|
|
31
|
+
abort_signal: Any = None,
|
|
32
|
+
log_context: Optional[dict] = None,
|
|
33
|
+
) -> ProviderResponse:
|
|
34
|
+
resolved = await self._resolve_messages(messages)
|
|
35
|
+
kwargs: Dict[str, Any] = {
|
|
36
|
+
"model": self._model,
|
|
37
|
+
"messages": resolved,
|
|
38
|
+
"temperature": 0.7,
|
|
39
|
+
"max_tokens": 65536,
|
|
40
|
+
}
|
|
41
|
+
if tools:
|
|
42
|
+
kwargs["tools"] = tools
|
|
43
|
+
kwargs["tool_choice"] = "auto"
|
|
44
|
+
|
|
45
|
+
if log_context:
|
|
46
|
+
self._write_log(log_context, "request", {
|
|
47
|
+
"model": self._model,
|
|
48
|
+
"messages": resolved,
|
|
49
|
+
"tools": tools or [],
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
response = await self._client.chat_completions(**kwargs)
|
|
53
|
+
parsed = self._parse_response(response)
|
|
54
|
+
|
|
55
|
+
if log_context:
|
|
56
|
+
self._write_log(log_context, "response", {
|
|
57
|
+
"model": self._model,
|
|
58
|
+
"finish_reason": parsed.finish_reason,
|
|
59
|
+
"content": parsed.content or "",
|
|
60
|
+
"tool_calls": parsed.tool_calls or [],
|
|
61
|
+
"usage": {
|
|
62
|
+
"prompt_tokens": parsed.usage.prompt_tokens,
|
|
63
|
+
"completion_tokens": parsed.usage.completion_tokens,
|
|
64
|
+
"total_tokens": parsed.usage.total_tokens,
|
|
65
|
+
} if parsed.usage else None,
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
return parsed
|
|
69
|
+
|
|
70
|
+
async def chat_stream(
|
|
71
|
+
self,
|
|
72
|
+
messages: List[ChatMessage],
|
|
73
|
+
tools: Optional[List[dict]] = None,
|
|
74
|
+
abort_signal: Any = None,
|
|
75
|
+
) -> AsyncGenerator[str, None]:
|
|
76
|
+
resolved = await self._resolve_messages(messages)
|
|
77
|
+
kwargs: Dict[str, Any] = {
|
|
78
|
+
"model": self._model,
|
|
79
|
+
"messages": resolved,
|
|
80
|
+
"temperature": 0.7,
|
|
81
|
+
"max_tokens": 65536,
|
|
82
|
+
"stream": True,
|
|
83
|
+
}
|
|
84
|
+
if tools:
|
|
85
|
+
kwargs["tools"] = tools
|
|
86
|
+
|
|
87
|
+
async for chunk in self._client.chat_completions_stream(**kwargs):
|
|
88
|
+
choices = chunk.get("choices") or []
|
|
89
|
+
if not choices:
|
|
90
|
+
continue
|
|
91
|
+
delta = choices[0].get("delta") or {}
|
|
92
|
+
content = delta.get("content")
|
|
93
|
+
if content:
|
|
94
|
+
yield content
|
|
@@ -91,9 +91,9 @@ txcode_sdk/hooks/handlers/__init__.py,sha256=5Bo0LQeTzvcgacnEdgdotCmGKaaNz-Bl6dL
|
|
|
91
91
|
txcode_sdk/hooks/handlers/base.py,sha256=4-H95O4xcpGpEmA8OjG-KXx1LIIarKkB9b0JiCC-rVs,515
|
|
92
92
|
txcode_sdk/hooks/handlers/memory.py,sha256=0B1O4l_7QnpWM_pKGEJqFZQrKK9dZ27Q5RBHciBCAAI,923
|
|
93
93
|
txcode_sdk/provider/__init__.py,sha256=lyvilAyXBMDv-_JB5XSu1GULuhAbxb59Hscq15G5p14,242
|
|
94
|
-
txcode_sdk/provider/base.py,sha256=
|
|
95
|
-
txcode_sdk/provider/deepseek_provider.py,sha256=
|
|
96
|
-
txcode_sdk/provider/openai_provider.py,sha256=
|
|
94
|
+
txcode_sdk/provider/base.py,sha256=laAcmvKqnOeNpt4o5aBSkmzeceZaLr9Hl2yUdvn4Uzk,5632
|
|
95
|
+
txcode_sdk/provider/deepseek_provider.py,sha256=WmRv-S91OY4SApoT-tW-X0bdzPPVVXNCGdlWLaiT3oQ,4285
|
|
96
|
+
txcode_sdk/provider/openai_provider.py,sha256=Jecv1xpSv3GIhQRrFnqnrnxa-McrSWOJ7586rwight4,3055
|
|
97
97
|
txcode_sdk/provider/router.py,sha256=r6zxnR3QEXkL8UO2IXF0UnC1y30hXKxqfbeH1N0VxKM,516
|
|
98
98
|
txcode_sdk/provider/txcode_ai.py,sha256=7l0iwdGywGr0r__HHwqhRjbKD5KGW5ezsxv6g2_hv7I,7640
|
|
99
99
|
txcode_sdk/server/__init__.py,sha256=jO8Zg74O7sfnZ-jBTvlVuThZdntY4FZi4SIx3AgM0LU,146
|
|
@@ -135,9 +135,9 @@ txcode_sdk/tools/web_shell_exec.py,sha256=QTnSlDLWPvldpResrYP1RAX2SYkHIkmLDuTvsO
|
|
|
135
135
|
txcode_sdk/tools/web_shell_exec.txt,sha256=6KVGwgQDp9HnbybcsIpxqPmtr5H6X0iPRARdzTahvYo,655
|
|
136
136
|
txcode_sdk/tools/write_file.py,sha256=hDB9ZKUsP9N2x4e_84pzAN1l0iiNEkXHOf_Cy1RbKyw,1404
|
|
137
137
|
txcode_sdk/tools/write_file.txt,sha256=b-PJMcpUf31U_eGCCgIPO7hjilPtcHJYNVR3DSbghd0,562
|
|
138
|
-
txcode_sdk-0.
|
|
139
|
-
txcode_sdk-0.
|
|
140
|
-
txcode_sdk-0.
|
|
141
|
-
txcode_sdk-0.
|
|
142
|
-
txcode_sdk-0.
|
|
143
|
-
txcode_sdk-0.
|
|
138
|
+
txcode_sdk-0.7.0.dist-info/licenses/LICENSE,sha256=MgVwuuUcdnF9JsDYM5blhGjaQrIM1SYpka3glIF0fko,1070
|
|
139
|
+
txcode_sdk-0.7.0.dist-info/METADATA,sha256=jgbPpXtfecLisPPFKEkt5G72CbkxwR-Bz2pzIS3IxJI,11536
|
|
140
|
+
txcode_sdk-0.7.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
141
|
+
txcode_sdk-0.7.0.dist-info/entry_points.txt,sha256=DOwXTKeX9yV_FSKIecinhnIbHcxtMcJFR-3Xu4duR9Q,63
|
|
142
|
+
txcode_sdk-0.7.0.dist-info/top_level.txt,sha256=rXVjeFngkf2CR9InAdTEc68OJ2RlJZINs99Ffw1WYqY,19
|
|
143
|
+
txcode_sdk-0.7.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|