1
2
3
4
5
6
7
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
| import asyncio
import json
import httpx
from typing import Optional, Dict, Any, List, AsyncIterator, Union
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Assistant:
"""智能体助手"""
id: str
name: str
config: Dict[str, Any]
created_at: datetime
client: 'LangGraphClient'
async def update_config(self, config: Dict[str, Any]) -> 'Assistant':
"""更新助手配置"""
return await self.client.update_assistant(self.id, config)
async def delete(self) -> None:
"""删除助手"""
await self.client.delete_assistant(self.id)
async def invoke(
self,
input: Dict[str, Any],
*,
thread_id: Optional[str] = None,
config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""调用助手"""
return await self.client.invoke_assistant(
self.id, input, thread_id=thread_id, config=config
)
async def stream(
self,
input: Dict[str, Any],
*,
thread_id: Optional[str] = None,
config: Optional[Dict[str, Any]] = None,
) -> AsyncIterator[Dict[str, Any]]:
"""流式调用助手"""
async for event in self.client.stream_assistant(
self.id, input, thread_id=thread_id, config=config
):
yield event
@dataclass
class Thread:
"""对话线程"""
id: str
metadata: Dict[str, Any]
created_at: datetime
client: 'LangGraphClient'
async def get_messages(self) -> List[Dict[str, Any]]:
"""获取消息历史"""
return await self.client.get_thread_messages(self.id)
async def add_message(self, content: str, role: str = "user") -> Dict[str, Any]:
"""添加消息"""
return await self.client.add_thread_message(self.id, content, role)
async def get_state(self) -> Dict[str, Any]:
"""获取线程状态"""
return await self.client.get_thread_state(self.id)
async def update_state(self, values: Dict[str, Any]) -> Dict[str, Any]:
"""更新线程状态"""
return await self.client.update_thread_state(self.id, values)
class LangGraphClient:
"""LangGraph平台API客户端"""
def __init__(
self,
api_key: Optional[str] = None,
base_url: str = "https://api.langgraph.com",
timeout: float = 60.0,
):
self.api_key = api_key or self._get_api_key()
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self._client = httpx.AsyncClient(
timeout=timeout,
headers={
"Authorization": f"Bearer {self.api_key}",
"User-Agent": "langgraph-sdk-python/0.1.0",
}
)
def _get_api_key(self) -> str:
"""获取API密钥"""
import os
api_key = os.environ.get("LANGGRAPH_API_KEY")
if not api_key:
raise ValueError("未设置LANGGRAPH_API_KEY环境变量")
return api_key
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self._client.aclose()
# 助手管理
async def get_assistants(self) -> List[Assistant]:
"""获取助手列表"""
response = await self._client.get(f"{self.base_url}/assistants")
response.raise_for_status()
data = response.json()
return [
Assistant(
id=item["id"],
name=item["name"],
config=item["config"],
created_at=datetime.fromisoformat(item["created_at"]),
client=self,
)
for item in data["assistants"]
]
async def create_assistant(
self,
name: str,
config: Dict[str, Any],
metadata: Optional[Dict[str, Any]] = None,
) -> Assistant:
"""创建新助手"""
payload = {
"name": name,
"config": config,
"metadata": metadata or {},
}
response = await self._client.post(
f"{self.base_url}/assistants",
json=payload,
)
response.raise_for_status()
data = response.json()
return Assistant(
id=data["id"],
name=data["name"],
config=data["config"],
created_at=datetime.fromisoformat(data["created_at"]),
client=self,
)
async def get_assistant(self, assistant_id: str) -> Assistant:
"""获取指定助手"""
response = await self._client.get(f"{self.base_url}/assistants/{assistant_id}")
response.raise_for_status()
data = response.json()
return Assistant(
id=data["id"],
name=data["name"],
config=data["config"],
created_at=datetime.fromisoformat(data["created_at"]),
client=self,
)
async def update_assistant(
self,
assistant_id: str,
config: Dict[str, Any]
) -> Assistant:
"""更新助手配置"""
response = await self._client.patch(
f"{self.base_url}/assistants/{assistant_id}",
json={"config": config},
)
response.raise_for_status()
data = response.json()
return Assistant(
id=data["id"],
name=data["name"],
config=data["config"],
created_at=datetime.fromisoformat(data["created_at"]),
client=self,
)
async def delete_assistant(self, assistant_id: str) -> None:
"""删除助手"""
response = await self._client.delete(f"{self.base_url}/assistants/{assistant_id}")
response.raise_for_status()
# 线程管理
async def create_thread(
self,
metadata: Optional[Dict[str, Any]] = None
) -> Thread:
"""创建新线程"""
payload = {"metadata": metadata or {}}
response = await self._client.post(f"{self.base_url}/threads", json=payload)
response.raise_for_status()
data = response.json()
return Thread(
id=data["id"],
metadata=data["metadata"],
created_at=datetime.fromisoformat(data["created_at"]),
client=self,
)
async def get_thread(self, thread_id: str) -> Thread:
"""获取指定线程"""
response = await self._client.get(f"{self.base_url}/threads/{thread_id}")
response.raise_for_status()
data = response.json()
return Thread(
id=data["id"],
metadata=data["metadata"],
created_at=datetime.fromisoformat(data["created_at"]),
client=self,
)
# 执行管理
async def invoke_assistant(
self,
assistant_id: str,
input: Dict[str, Any],
*,
thread_id: Optional[str] = None,
config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""同步调用助手"""
payload = {
"input": input,
"config": config or {},
}
if thread_id:
payload["thread_id"] = thread_id
response = await self._client.post(
f"{self.base_url}/assistants/{assistant_id}/invoke",
json=payload,
)
response.raise_for_status()
return response.json()
async def stream_assistant(
self,
assistant_id: str,
input: Dict[str, Any],
*,
thread_id: Optional[str] = None,
config: Optional[Dict[str, Any]] = None,
) -> AsyncIterator[Dict[str, Any]]:
"""流式调用助手"""
payload = {
"input": input,
"config": config or {},
}
if thread_id:
payload["thread_id"] = thread_id
async with self._client.stream(
"POST",
f"{self.base_url}/assistants/{assistant_id}/stream",
json=payload,
) as response:
response.raise_for_status()
async for line in response.aiter_lines():
if line.startswith("data: "):
try:
data = json.loads(line[6:])
yield data
except json.JSONDecodeError:
continue
# 状态管理
async def get_thread_state(self, thread_id: str) -> Dict[str, Any]:
"""获取线程状态"""
response = await self._client.get(f"{self.base_url}/threads/{thread_id}/state")
response.raise_for_status()
return response.json()
async def update_thread_state(
self,
thread_id: str,
values: Dict[str, Any]
) -> Dict[str, Any]:
"""更新线程状态"""
response = await self._client.patch(
f"{self.base_url}/threads/{thread_id}/state",
json={"values": values},
)
response.raise_for_status()
return response.json()
# 使用示例
async def main():
"""SDK使用示例"""
async with LangGraphClient() as client:
# 创建助手
assistant = await client.create_assistant(
name="我的助手",
config={
"model": "gpt-4",
"tools": ["web_search", "calculator"],
"prompt": "你是一个有用的助手",
}
)
print(f"创建助手: {assistant.name} ({assistant.id})")
# 创建对话线程
thread = await client.create_thread(
metadata={"user_id": "user123"}
)
print(f"创建线程: {thread.id}")
# 调用助手
result = await assistant.invoke(
{"messages": [{"role": "user", "content": "你好!"}]},
thread_id=thread.id,
)
print(f"助手回复: {result}")
# 流式调用
print("流式回复:")
async for event in assistant.stream(
{"messages": [{"role": "user", "content": "今天天气怎么样?"}]},
thread_id=thread.id,
):
if event.get("type") == "message":
print(event["content"], end="", flush=True)
print("\n")
if __name__ == "__main__":
asyncio.run(main())
|