langgraph-api 0.0.1__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.
Potentially problematic release.
This version of langgraph-api might be problematic. Click here for more details.
- LICENSE +93 -0
- langgraph_api/__init__.py +0 -0
- langgraph_api/api/__init__.py +63 -0
- langgraph_api/api/assistants.py +326 -0
- langgraph_api/api/meta.py +71 -0
- langgraph_api/api/openapi.py +32 -0
- langgraph_api/api/runs.py +463 -0
- langgraph_api/api/store.py +116 -0
- langgraph_api/api/threads.py +263 -0
- langgraph_api/asyncio.py +201 -0
- langgraph_api/auth/__init__.py +0 -0
- langgraph_api/auth/langsmith/__init__.py +0 -0
- langgraph_api/auth/langsmith/backend.py +67 -0
- langgraph_api/auth/langsmith/client.py +145 -0
- langgraph_api/auth/middleware.py +41 -0
- langgraph_api/auth/noop.py +14 -0
- langgraph_api/cli.py +209 -0
- langgraph_api/config.py +70 -0
- langgraph_api/cron_scheduler.py +60 -0
- langgraph_api/errors.py +52 -0
- langgraph_api/graph.py +314 -0
- langgraph_api/http.py +168 -0
- langgraph_api/http_logger.py +89 -0
- langgraph_api/js/.gitignore +2 -0
- langgraph_api/js/build.mts +49 -0
- langgraph_api/js/client.mts +849 -0
- langgraph_api/js/global.d.ts +6 -0
- langgraph_api/js/package.json +33 -0
- langgraph_api/js/remote.py +673 -0
- langgraph_api/js/server_sent_events.py +126 -0
- langgraph_api/js/src/graph.mts +88 -0
- langgraph_api/js/src/hooks.mjs +12 -0
- langgraph_api/js/src/parser/parser.mts +443 -0
- langgraph_api/js/src/parser/parser.worker.mjs +12 -0
- langgraph_api/js/src/schema/types.mts +2136 -0
- langgraph_api/js/src/schema/types.template.mts +74 -0
- langgraph_api/js/src/utils/importMap.mts +85 -0
- langgraph_api/js/src/utils/pythonSchemas.mts +28 -0
- langgraph_api/js/src/utils/serde.mts +21 -0
- langgraph_api/js/tests/api.test.mts +1566 -0
- langgraph_api/js/tests/compose-postgres.yml +56 -0
- langgraph_api/js/tests/graphs/.gitignore +1 -0
- langgraph_api/js/tests/graphs/agent.mts +127 -0
- langgraph_api/js/tests/graphs/error.mts +17 -0
- langgraph_api/js/tests/graphs/langgraph.json +8 -0
- langgraph_api/js/tests/graphs/nested.mts +44 -0
- langgraph_api/js/tests/graphs/package.json +7 -0
- langgraph_api/js/tests/graphs/weather.mts +57 -0
- langgraph_api/js/tests/graphs/yarn.lock +159 -0
- langgraph_api/js/tests/parser.test.mts +870 -0
- langgraph_api/js/tests/utils.mts +17 -0
- langgraph_api/js/yarn.lock +1340 -0
- langgraph_api/lifespan.py +41 -0
- langgraph_api/logging.py +121 -0
- langgraph_api/metadata.py +101 -0
- langgraph_api/models/__init__.py +0 -0
- langgraph_api/models/run.py +229 -0
- langgraph_api/patch.py +42 -0
- langgraph_api/queue.py +245 -0
- langgraph_api/route.py +118 -0
- langgraph_api/schema.py +190 -0
- langgraph_api/serde.py +124 -0
- langgraph_api/server.py +48 -0
- langgraph_api/sse.py +118 -0
- langgraph_api/state.py +67 -0
- langgraph_api/stream.py +289 -0
- langgraph_api/utils.py +60 -0
- langgraph_api/validation.py +141 -0
- langgraph_api-0.0.1.dist-info/LICENSE +93 -0
- langgraph_api-0.0.1.dist-info/METADATA +26 -0
- langgraph_api-0.0.1.dist-info/RECORD +86 -0
- langgraph_api-0.0.1.dist-info/WHEEL +4 -0
- langgraph_api-0.0.1.dist-info/entry_points.txt +3 -0
- langgraph_license/__init__.py +0 -0
- langgraph_license/middleware.py +21 -0
- langgraph_license/validation.py +11 -0
- langgraph_storage/__init__.py +0 -0
- langgraph_storage/checkpoint.py +94 -0
- langgraph_storage/database.py +190 -0
- langgraph_storage/ops.py +1523 -0
- langgraph_storage/queue.py +108 -0
- langgraph_storage/retry.py +27 -0
- langgraph_storage/store.py +28 -0
- langgraph_storage/ttl_dict.py +54 -0
- logging.json +22 -0
- openapi.json +4304 -0
LICENSE
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Elastic License 2.0
|
|
2
|
+
|
|
3
|
+
URL: https://www.elastic.co/licensing/elastic-license
|
|
4
|
+
|
|
5
|
+
## Acceptance
|
|
6
|
+
|
|
7
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
8
|
+
|
|
9
|
+
## Copyright License
|
|
10
|
+
|
|
11
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide,
|
|
12
|
+
non-sublicensable, non-transferable license to use, copy, distribute, make
|
|
13
|
+
available, and prepare derivative works of the software, in each case subject to
|
|
14
|
+
the limitations and conditions below.
|
|
15
|
+
|
|
16
|
+
## Limitations
|
|
17
|
+
|
|
18
|
+
You may not provide the software to third parties as a hosted or managed
|
|
19
|
+
service, where the service provides users with access to any substantial set of
|
|
20
|
+
the features or functionality of the software.
|
|
21
|
+
|
|
22
|
+
You may not move, change, disable, or circumvent the license key functionality
|
|
23
|
+
in the software, and you may not remove or obscure any functionality in the
|
|
24
|
+
software that is protected by the license key.
|
|
25
|
+
|
|
26
|
+
You may not alter, remove, or obscure any licensing, copyright, or other notices
|
|
27
|
+
of the licensor in the software. Any use of the licensor’s trademarks is subject
|
|
28
|
+
to applicable law.
|
|
29
|
+
|
|
30
|
+
## Patents
|
|
31
|
+
|
|
32
|
+
The licensor grants you a license, under any patent claims the licensor can
|
|
33
|
+
license, or becomes able to license, to make, have made, use, sell, offer for
|
|
34
|
+
sale, import and have imported the software, in each case subject to the
|
|
35
|
+
limitations and conditions in this license. This license does not cover any
|
|
36
|
+
patent claims that you cause to be infringed by modifications or additions to
|
|
37
|
+
the software. If you or your company make any written claim that the software
|
|
38
|
+
infringes or contributes to infringement of any patent, your patent license for
|
|
39
|
+
the software granted under these terms ends immediately. If your company makes
|
|
40
|
+
such a claim, your patent license ends immediately for work on behalf of your
|
|
41
|
+
company.
|
|
42
|
+
|
|
43
|
+
## Notices
|
|
44
|
+
|
|
45
|
+
You must ensure that anyone who gets a copy of any part of the software from you
|
|
46
|
+
also gets a copy of these terms.
|
|
47
|
+
|
|
48
|
+
If you modify the software, you must include in any modified copies of the
|
|
49
|
+
software prominent notices stating that you have modified the software.
|
|
50
|
+
|
|
51
|
+
## No Other Rights
|
|
52
|
+
|
|
53
|
+
These terms do not imply any licenses other than those expressly granted in
|
|
54
|
+
these terms.
|
|
55
|
+
|
|
56
|
+
## Termination
|
|
57
|
+
|
|
58
|
+
If you use the software in violation of these terms, such use is not licensed,
|
|
59
|
+
and your licenses will automatically terminate. If the licensor provides you
|
|
60
|
+
with a notice of your violation, and you cease all violation of this license no
|
|
61
|
+
later than 30 days after you receive that notice, your licenses will be
|
|
62
|
+
reinstated retroactively. However, if you violate these terms after such
|
|
63
|
+
reinstatement, any additional violation of these terms will cause your licenses
|
|
64
|
+
to terminate automatically and permanently.
|
|
65
|
+
|
|
66
|
+
## No Liability
|
|
67
|
+
|
|
68
|
+
*As far as the law allows, the software comes as is, without any warranty or
|
|
69
|
+
condition, and the licensor will not be liable to you for any damages arising
|
|
70
|
+
out of these terms or the use or nature of the software, under any kind of
|
|
71
|
+
legal claim.*
|
|
72
|
+
|
|
73
|
+
## Definitions
|
|
74
|
+
|
|
75
|
+
The **licensor** is the entity offering these terms, and the **software** is the
|
|
76
|
+
software the licensor makes available under these terms, including any portion
|
|
77
|
+
of it.
|
|
78
|
+
|
|
79
|
+
**you** refers to the individual or entity agreeing to these terms.
|
|
80
|
+
|
|
81
|
+
**your company** is any legal entity, sole proprietorship, or other kind of
|
|
82
|
+
organization that you work for, plus all organizations that have control over,
|
|
83
|
+
are under the control of, or are under common control with that
|
|
84
|
+
organization. **control** means ownership of substantially all the assets of an
|
|
85
|
+
entity, or the power to direct its management and policies by vote, contract, or
|
|
86
|
+
otherwise. Control can be direct or indirect.
|
|
87
|
+
|
|
88
|
+
**your licenses** are all the licenses granted to you for the software under
|
|
89
|
+
these terms.
|
|
90
|
+
|
|
91
|
+
**use** means anything you do with the software requiring one of your licenses.
|
|
92
|
+
|
|
93
|
+
**trademark** means trademarks, service marks, and similar rights.
|
|
File without changes
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
|
|
3
|
+
from starlette.requests import Request
|
|
4
|
+
from starlette.responses import HTMLResponse, JSONResponse, Response
|
|
5
|
+
from starlette.routing import BaseRoute, Mount, Route
|
|
6
|
+
|
|
7
|
+
from langgraph_api.api.assistants import assistants_routes
|
|
8
|
+
from langgraph_api.api.meta import meta_info, meta_metrics
|
|
9
|
+
from langgraph_api.api.openapi import get_openapi_spec
|
|
10
|
+
from langgraph_api.api.runs import runs_routes
|
|
11
|
+
from langgraph_api.api.store import store_routes
|
|
12
|
+
from langgraph_api.api.threads import threads_routes
|
|
13
|
+
from langgraph_api.auth.middleware import auth_middleware
|
|
14
|
+
from langgraph_api.config import MIGRATIONS_PATH
|
|
15
|
+
from langgraph_api.graph import js_bg_tasks
|
|
16
|
+
from langgraph_api.js.remote import js_healthcheck
|
|
17
|
+
from langgraph_api.validation import DOCS_HTML
|
|
18
|
+
from langgraph_storage.database import connect, healthcheck
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
async def ok(request: Request):
|
|
22
|
+
check_db = int(request.query_params.get("check_db", "0")) # must be "0" or "1"
|
|
23
|
+
if check_db:
|
|
24
|
+
await healthcheck()
|
|
25
|
+
if js_bg_tasks:
|
|
26
|
+
await js_healthcheck()
|
|
27
|
+
return JSONResponse({"ok": True})
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
async def openapi(request: Request):
|
|
31
|
+
spec = await asyncio.to_thread(get_openapi_spec)
|
|
32
|
+
return Response(spec, media_type="application/json")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
async def docs(request: Request):
|
|
36
|
+
return HTMLResponse(DOCS_HTML)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
routes: list[BaseRoute] = [
|
|
40
|
+
Route("/ok", ok, methods=["GET"]),
|
|
41
|
+
Route("/openapi.json", openapi, methods=["GET"]),
|
|
42
|
+
Route("/docs", docs, methods=["GET"]),
|
|
43
|
+
Route("/info", meta_info, methods=["GET"]),
|
|
44
|
+
Route("/metrics", meta_metrics, methods=["GET"]),
|
|
45
|
+
Mount(
|
|
46
|
+
"",
|
|
47
|
+
middleware=[auth_middleware],
|
|
48
|
+
routes=[*assistants_routes, *runs_routes, *threads_routes, *store_routes],
|
|
49
|
+
),
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
if "inmem" in MIGRATIONS_PATH:
|
|
54
|
+
|
|
55
|
+
async def truncate(request: Request):
|
|
56
|
+
from langgraph_storage.checkpoint import Checkpointer
|
|
57
|
+
|
|
58
|
+
Checkpointer().clear()
|
|
59
|
+
async with connect() as conn:
|
|
60
|
+
conn.clear()
|
|
61
|
+
return JSONResponse({"ok": True})
|
|
62
|
+
|
|
63
|
+
routes.insert(0, Route("/internal/truncate", truncate, methods=["POST"]))
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
from uuid import uuid4
|
|
3
|
+
|
|
4
|
+
from langchain_core.runnables.utils import create_model
|
|
5
|
+
from langgraph.pregel import Pregel
|
|
6
|
+
from starlette.exceptions import HTTPException
|
|
7
|
+
from starlette.responses import Response
|
|
8
|
+
from starlette.routing import BaseRoute
|
|
9
|
+
|
|
10
|
+
from langgraph_api.graph import get_assistant_id, get_graph
|
|
11
|
+
from langgraph_api.js.remote import RemotePregel
|
|
12
|
+
from langgraph_api.route import ApiRequest, ApiResponse, ApiRoute
|
|
13
|
+
from langgraph_api.serde import ajson_loads
|
|
14
|
+
from langgraph_api.utils import fetchone, validate_uuid
|
|
15
|
+
from langgraph_api.validation import (
|
|
16
|
+
AssistantCreate,
|
|
17
|
+
AssistantPatch,
|
|
18
|
+
AssistantSearchRequest,
|
|
19
|
+
AssistantVersionChange,
|
|
20
|
+
AssistantVersionsSearchRequest,
|
|
21
|
+
)
|
|
22
|
+
from langgraph_storage.database import connect
|
|
23
|
+
from langgraph_storage.ops import Assistants
|
|
24
|
+
from langgraph_storage.retry import retry_db
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _state_jsonschema(graph: Pregel) -> dict | None:
|
|
28
|
+
fields: dict = {}
|
|
29
|
+
for k in graph.stream_channels_list:
|
|
30
|
+
v = graph.channels[k]
|
|
31
|
+
try:
|
|
32
|
+
create_model(k, __root__=(v.UpdateType, None)).schema()
|
|
33
|
+
fields[k] = (v.UpdateType, None)
|
|
34
|
+
except Exception:
|
|
35
|
+
fields[k] = (Any, None)
|
|
36
|
+
return create_model(graph.get_name("State"), **fields).schema()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _graph_schemas(graph: Pregel) -> dict:
|
|
40
|
+
try:
|
|
41
|
+
input_schema = graph.get_input_jsonschema()
|
|
42
|
+
except Exception:
|
|
43
|
+
input_schema = None
|
|
44
|
+
try:
|
|
45
|
+
output_schema = graph.get_output_jsonschema()
|
|
46
|
+
except Exception:
|
|
47
|
+
output_schema = None
|
|
48
|
+
state_schema = _state_jsonschema(graph)
|
|
49
|
+
try:
|
|
50
|
+
config_schema = (
|
|
51
|
+
graph.config_schema().__fields__["configurable"].annotation.schema()
|
|
52
|
+
if "configurable" in graph.config_schema().__fields__
|
|
53
|
+
else {}
|
|
54
|
+
)
|
|
55
|
+
except Exception:
|
|
56
|
+
config_schema = None
|
|
57
|
+
return {
|
|
58
|
+
"input_schema": input_schema,
|
|
59
|
+
"output_schema": output_schema,
|
|
60
|
+
"state_schema": state_schema,
|
|
61
|
+
"config_schema": config_schema,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@retry_db
|
|
66
|
+
async def create_assistant(request: ApiRequest) -> ApiResponse:
|
|
67
|
+
payload = await request.json(AssistantCreate)
|
|
68
|
+
"""Create an assistant."""
|
|
69
|
+
if assistant_id := payload.get("assistant_id"):
|
|
70
|
+
validate_uuid(assistant_id, "Invalid assistant ID: must be a UUID")
|
|
71
|
+
async with connect() as conn:
|
|
72
|
+
assistant = await Assistants.put(
|
|
73
|
+
conn,
|
|
74
|
+
assistant_id or str(uuid4()),
|
|
75
|
+
config=payload.get("config") or {},
|
|
76
|
+
graph_id=payload["graph_id"],
|
|
77
|
+
metadata=payload.get("metadata") or {},
|
|
78
|
+
if_exists=payload.get("if_exists") or "raise",
|
|
79
|
+
name=payload.get("name") or "Untitled",
|
|
80
|
+
)
|
|
81
|
+
return ApiResponse(await fetchone(assistant, not_found_code=409))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@retry_db
|
|
85
|
+
async def search_assistants(
|
|
86
|
+
request: ApiRequest,
|
|
87
|
+
) -> ApiResponse:
|
|
88
|
+
"""List assistants."""
|
|
89
|
+
payload = await request.json(AssistantSearchRequest)
|
|
90
|
+
async with connect() as conn:
|
|
91
|
+
assistants_iter = await Assistants.search(
|
|
92
|
+
conn,
|
|
93
|
+
graph_id=payload.get("graph_id"),
|
|
94
|
+
metadata=payload.get("metadata"),
|
|
95
|
+
limit=payload.get("limit") or 10,
|
|
96
|
+
offset=payload.get("offset") or 0,
|
|
97
|
+
)
|
|
98
|
+
return ApiResponse([assistant async for assistant in assistants_iter])
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@retry_db
|
|
102
|
+
async def get_assistant(
|
|
103
|
+
request: ApiRequest,
|
|
104
|
+
) -> ApiResponse:
|
|
105
|
+
assistant_id = request.path_params["assistant_id"]
|
|
106
|
+
"""Get an assistant by ID."""
|
|
107
|
+
validate_uuid(assistant_id, "Invalid assistant ID: must be a UUID")
|
|
108
|
+
async with connect() as conn:
|
|
109
|
+
assistant = await Assistants.get(conn, assistant_id)
|
|
110
|
+
return ApiResponse(await fetchone(assistant))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@retry_db
|
|
114
|
+
async def get_assistant_graph(
|
|
115
|
+
request: ApiRequest,
|
|
116
|
+
) -> ApiResponse:
|
|
117
|
+
"""Get an assistant by ID."""
|
|
118
|
+
assistant_id = get_assistant_id(str(request.path_params["assistant_id"]))
|
|
119
|
+
validate_uuid(assistant_id, "Invalid assistant ID: must be a UUID")
|
|
120
|
+
async with connect() as conn:
|
|
121
|
+
assistant_ = await Assistants.get(conn, assistant_id)
|
|
122
|
+
assistant = await fetchone(assistant_)
|
|
123
|
+
config = await ajson_loads(assistant["config"])
|
|
124
|
+
graph = get_graph(assistant["graph_id"], config)
|
|
125
|
+
|
|
126
|
+
xray: bool | int = False
|
|
127
|
+
xray_query = request.query_params.get("xray")
|
|
128
|
+
if xray_query:
|
|
129
|
+
if xray_query in ("true", "True"):
|
|
130
|
+
xray = True
|
|
131
|
+
elif xray_query in ("false", "False"):
|
|
132
|
+
xray = False
|
|
133
|
+
else:
|
|
134
|
+
try:
|
|
135
|
+
xray = int(xray_query)
|
|
136
|
+
except ValueError:
|
|
137
|
+
raise HTTPException(422, detail="Invalid xray value") from None
|
|
138
|
+
|
|
139
|
+
if xray <= 0:
|
|
140
|
+
raise HTTPException(422, detail="Invalid xray value") from None
|
|
141
|
+
|
|
142
|
+
if isinstance(graph, RemotePregel):
|
|
143
|
+
drawable_graph = await graph.fetch_graph(xray=xray)
|
|
144
|
+
return ApiResponse(drawable_graph.to_json())
|
|
145
|
+
return ApiResponse(graph.get_graph(xray=xray).to_json())
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@retry_db
|
|
149
|
+
async def get_assistant_subgraphs(
|
|
150
|
+
request: ApiRequest,
|
|
151
|
+
) -> ApiResponse:
|
|
152
|
+
"""Get an assistant by ID."""
|
|
153
|
+
assistant_id = request.path_params["assistant_id"]
|
|
154
|
+
validate_uuid(assistant_id, "Invalid assistant ID: must be a UUID")
|
|
155
|
+
async with connect() as conn:
|
|
156
|
+
assistant_ = await Assistants.get(conn, assistant_id)
|
|
157
|
+
assistant = await fetchone(assistant_)
|
|
158
|
+
config = await ajson_loads(assistant["config"])
|
|
159
|
+
graph = get_graph(assistant["graph_id"], config)
|
|
160
|
+
namespace = request.path_params.get("namespace")
|
|
161
|
+
|
|
162
|
+
if isinstance(graph, RemotePregel):
|
|
163
|
+
return ApiResponse(
|
|
164
|
+
await graph.fetch_subgraphs(
|
|
165
|
+
namespace=namespace,
|
|
166
|
+
recurse=request.query_params.get("recurse", "False")
|
|
167
|
+
in ("true", "True"),
|
|
168
|
+
)
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
return ApiResponse(
|
|
172
|
+
{
|
|
173
|
+
ns: _graph_schemas(subgraph)
|
|
174
|
+
async for ns, subgraph in graph.aget_subgraphs(
|
|
175
|
+
namespace=namespace,
|
|
176
|
+
recurse=request.query_params.get("recurse", "False")
|
|
177
|
+
in ("true", "True"),
|
|
178
|
+
)
|
|
179
|
+
}
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@retry_db
|
|
184
|
+
async def get_assistant_schemas(
|
|
185
|
+
request: ApiRequest,
|
|
186
|
+
) -> ApiResponse:
|
|
187
|
+
"""Get an assistant by ID."""
|
|
188
|
+
assistant_id = request.path_params["assistant_id"]
|
|
189
|
+
validate_uuid(assistant_id, "Invalid assistant ID: must be a UUID")
|
|
190
|
+
async with connect() as conn:
|
|
191
|
+
assistant_ = await Assistants.get(conn, assistant_id)
|
|
192
|
+
assistant = await fetchone(assistant_)
|
|
193
|
+
config = await ajson_loads(assistant["config"])
|
|
194
|
+
graph = get_graph(assistant["graph_id"], config)
|
|
195
|
+
|
|
196
|
+
if isinstance(graph, RemotePregel):
|
|
197
|
+
schemas = await graph.fetch_state_schema()
|
|
198
|
+
return ApiResponse(
|
|
199
|
+
{
|
|
200
|
+
"graph_id": assistant["graph_id"],
|
|
201
|
+
"input_schema": schemas.get("input"),
|
|
202
|
+
"output_schema": schemas.get("output"),
|
|
203
|
+
"state_schema": schemas.get("state"),
|
|
204
|
+
"config_schema": schemas.get("config"),
|
|
205
|
+
}
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
try:
|
|
209
|
+
input_schema = graph.get_input_schema().schema()
|
|
210
|
+
except Exception:
|
|
211
|
+
input_schema = None
|
|
212
|
+
try:
|
|
213
|
+
output_schema = graph.get_output_schema().schema()
|
|
214
|
+
except Exception:
|
|
215
|
+
output_schema = None
|
|
216
|
+
|
|
217
|
+
state_schema = _state_jsonschema(graph)
|
|
218
|
+
try:
|
|
219
|
+
config_schema = (
|
|
220
|
+
graph.config_schema().__fields__["configurable"].annotation.schema()
|
|
221
|
+
if "configurable" in graph.config_schema().__fields__
|
|
222
|
+
else {}
|
|
223
|
+
)
|
|
224
|
+
except Exception:
|
|
225
|
+
config_schema = None
|
|
226
|
+
return ApiResponse(
|
|
227
|
+
{
|
|
228
|
+
"graph_id": assistant["graph_id"],
|
|
229
|
+
"input_schema": input_schema,
|
|
230
|
+
"output_schema": output_schema,
|
|
231
|
+
"state_schema": state_schema,
|
|
232
|
+
"config_schema": config_schema,
|
|
233
|
+
}
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@retry_db
|
|
238
|
+
async def patch_assistant(
|
|
239
|
+
request: ApiRequest,
|
|
240
|
+
) -> ApiResponse:
|
|
241
|
+
"""Update an assistant."""
|
|
242
|
+
assistant_id = request.path_params["assistant_id"]
|
|
243
|
+
validate_uuid(assistant_id, "Invalid assistant ID: must be a UUID")
|
|
244
|
+
payload = await request.json(AssistantPatch)
|
|
245
|
+
async with connect() as conn:
|
|
246
|
+
assistant = await Assistants.patch(
|
|
247
|
+
conn,
|
|
248
|
+
assistant_id,
|
|
249
|
+
config=payload.get("config"),
|
|
250
|
+
graph_id=payload.get("graph_id"),
|
|
251
|
+
metadata=payload.get("metadata"),
|
|
252
|
+
name=payload.get("name"),
|
|
253
|
+
)
|
|
254
|
+
return ApiResponse(await fetchone(assistant))
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
@retry_db
|
|
258
|
+
async def delete_assistant(request: ApiRequest) -> ApiResponse:
|
|
259
|
+
"""Delete an assistant by ID."""
|
|
260
|
+
assistant_id = request.path_params["assistant_id"]
|
|
261
|
+
validate_uuid(assistant_id, "Invalid assistant ID: must be a UUID")
|
|
262
|
+
async with connect() as conn:
|
|
263
|
+
aid = await Assistants.delete(conn, assistant_id)
|
|
264
|
+
await fetchone(aid)
|
|
265
|
+
return Response(status_code=204)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
@retry_db
|
|
269
|
+
async def get_assistant_versions(request: ApiRequest) -> ApiResponse:
|
|
270
|
+
"""Get all versions of an assistant."""
|
|
271
|
+
assistant_id = request.path_params["assistant_id"]
|
|
272
|
+
validate_uuid(assistant_id, "Invalid assistant ID: must be a UUID")
|
|
273
|
+
payload = await request.json(AssistantVersionsSearchRequest)
|
|
274
|
+
async with connect() as conn:
|
|
275
|
+
assistants_iter = await Assistants.get_versions(
|
|
276
|
+
conn,
|
|
277
|
+
assistant_id,
|
|
278
|
+
metadata=payload.get("metadata") or {},
|
|
279
|
+
limit=payload.get("limit") or 10,
|
|
280
|
+
offset=payload.get("offset") or 0,
|
|
281
|
+
)
|
|
282
|
+
return ApiResponse([assistant async for assistant in assistants_iter])
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
@retry_db
|
|
286
|
+
async def set_latest_assistant_version(request: ApiRequest) -> ApiResponse:
|
|
287
|
+
"""Change the version of an assistant."""
|
|
288
|
+
assistant_id = request.path_params["assistant_id"]
|
|
289
|
+
payload = await request.json(AssistantVersionChange)
|
|
290
|
+
validate_uuid(assistant_id, "Invalid assistant ID: must be a UUID")
|
|
291
|
+
async with connect() as conn:
|
|
292
|
+
assistant = await Assistants.set_latest(
|
|
293
|
+
conn, assistant_id, payload.get("version")
|
|
294
|
+
)
|
|
295
|
+
return ApiResponse(await fetchone(assistant, not_found_code=404))
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
assistants_routes: list[BaseRoute] = [
|
|
299
|
+
ApiRoute("/assistants", create_assistant, methods=["POST"]),
|
|
300
|
+
ApiRoute("/assistants/search", search_assistants, methods=["POST"]),
|
|
301
|
+
ApiRoute(
|
|
302
|
+
"/assistants/{assistant_id}/latest",
|
|
303
|
+
set_latest_assistant_version,
|
|
304
|
+
methods=["POST"],
|
|
305
|
+
),
|
|
306
|
+
ApiRoute(
|
|
307
|
+
"/assistants/{assistant_id}/versions", get_assistant_versions, methods=["POST"]
|
|
308
|
+
),
|
|
309
|
+
ApiRoute("/assistants/{assistant_id}", get_assistant, methods=["GET"]),
|
|
310
|
+
ApiRoute("/assistants/{assistant_id}/graph", get_assistant_graph, methods=["GET"]),
|
|
311
|
+
ApiRoute(
|
|
312
|
+
"/assistants/{assistant_id}/schemas", get_assistant_schemas, methods=["GET"]
|
|
313
|
+
),
|
|
314
|
+
ApiRoute(
|
|
315
|
+
"/assistants/{assistant_id}/subgraphs", get_assistant_subgraphs, methods=["GET"]
|
|
316
|
+
),
|
|
317
|
+
ApiRoute(
|
|
318
|
+
"/assistants/{assistant_id}/subgraphs/{namespace}",
|
|
319
|
+
get_assistant_subgraphs,
|
|
320
|
+
methods=["GET"],
|
|
321
|
+
),
|
|
322
|
+
ApiRoute("/assistants/{assistant_id}", patch_assistant, methods=["PATCH"]),
|
|
323
|
+
ApiRoute("/assistants/{assistant_id}", delete_assistant, methods=["DELETE"]),
|
|
324
|
+
]
|
|
325
|
+
|
|
326
|
+
assistants_routes = [route for route in assistants_routes if route is not None]
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from starlette.responses import JSONResponse, PlainTextResponse
|
|
4
|
+
|
|
5
|
+
from langgraph_api import config
|
|
6
|
+
from langgraph_api.queue import WORKERS
|
|
7
|
+
from langgraph_api.route import ApiRequest
|
|
8
|
+
from langgraph_license.validation import plus_features_enabled
|
|
9
|
+
from langgraph_storage.database import connect, pool_stats
|
|
10
|
+
from langgraph_storage.ops import Runs
|
|
11
|
+
|
|
12
|
+
METRICS_FORMATS = {"prometheus", "json"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
async def meta_info(request: ApiRequest):
|
|
16
|
+
plus = plus_features_enabled()
|
|
17
|
+
return JSONResponse(
|
|
18
|
+
{
|
|
19
|
+
"flags": {
|
|
20
|
+
"assistants": True,
|
|
21
|
+
"crons": plus and config.FF_CRONS_ENABLED,
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
async def meta_metrics(request: ApiRequest):
|
|
28
|
+
# determine output format
|
|
29
|
+
format = request.query_params.get("format", "prometheus")
|
|
30
|
+
if format not in METRICS_FORMATS:
|
|
31
|
+
format = "prometheus"
|
|
32
|
+
|
|
33
|
+
# collect stats
|
|
34
|
+
workers_max = config.N_JOBS_PER_WORKER
|
|
35
|
+
workers_active = len(WORKERS)
|
|
36
|
+
workers_available = workers_max - workers_active
|
|
37
|
+
|
|
38
|
+
if format == "json":
|
|
39
|
+
async with connect() as conn:
|
|
40
|
+
return JSONResponse(
|
|
41
|
+
{
|
|
42
|
+
**pool_stats(),
|
|
43
|
+
"workers": {
|
|
44
|
+
"max": workers_max,
|
|
45
|
+
"active": workers_active,
|
|
46
|
+
"available": workers_available,
|
|
47
|
+
},
|
|
48
|
+
"queue": await Runs.stats(conn),
|
|
49
|
+
}
|
|
50
|
+
)
|
|
51
|
+
elif format == "prometheus":
|
|
52
|
+
# LANGSMITH_HOST_PROJECT_ID and HOSTED_LANGSERVE_REVISION_ID are injected
|
|
53
|
+
# into the deployed image by host-backend.
|
|
54
|
+
project_id = os.getenv("LANGSMITH_HOST_PROJECT_ID")
|
|
55
|
+
revision_id = os.getenv("HOSTED_LANGSERVE_REVISION_ID")
|
|
56
|
+
|
|
57
|
+
metrics = [
|
|
58
|
+
"# HELP lg_api_workers_max The maximum number of workers available.",
|
|
59
|
+
"# TYPE lg_api_workers_max gauge",
|
|
60
|
+
f'lg_api_workers_max{{project_id="{project_id}", revision_id="{revision_id}"}} {workers_max}',
|
|
61
|
+
"# HELP lg_api_workers_active The number of currently active workers.",
|
|
62
|
+
"# TYPE lg_api_workers_active gauge",
|
|
63
|
+
f'lg_api_workers_active{{project_id="{project_id}", revision_id="{revision_id}"}} {workers_active}',
|
|
64
|
+
"# HELP lg_api_workers_available The number of available (idle) workers.",
|
|
65
|
+
"# TYPE lg_api_workers_available gauge",
|
|
66
|
+
f'lg_api_workers_available{{project_id="{project_id}", revision_id="{revision_id}"}} {workers_available}',
|
|
67
|
+
# In the future, we can add more metrics to be scraped by Prometheus.
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
metrics_response = "\n".join(metrics)
|
|
71
|
+
return PlainTextResponse(metrics_response)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from functools import lru_cache
|
|
2
|
+
|
|
3
|
+
import orjson
|
|
4
|
+
|
|
5
|
+
from langgraph_api.config import LANGGRAPH_AUTH_TYPE
|
|
6
|
+
from langgraph_api.graph import GRAPHS
|
|
7
|
+
from langgraph_api.validation import openapi
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@lru_cache(maxsize=1)
|
|
11
|
+
def get_openapi_spec() -> str:
|
|
12
|
+
# patch the graph_id enums
|
|
13
|
+
graph_ids = list(GRAPHS.keys())
|
|
14
|
+
for schema in (
|
|
15
|
+
"Assistant",
|
|
16
|
+
"AssistantCreate",
|
|
17
|
+
"AssistantPatch",
|
|
18
|
+
"GraphSchema",
|
|
19
|
+
"AssistantSearchRequest",
|
|
20
|
+
):
|
|
21
|
+
openapi["components"]["schemas"][schema]["properties"]["graph_id"]["enum"] = (
|
|
22
|
+
graph_ids
|
|
23
|
+
)
|
|
24
|
+
# patch the auth schemes
|
|
25
|
+
if LANGGRAPH_AUTH_TYPE == "langsmith":
|
|
26
|
+
openapi["security"] = [
|
|
27
|
+
{"x-api-key": []},
|
|
28
|
+
]
|
|
29
|
+
openapi["components"]["securitySchemes"] = {
|
|
30
|
+
"x-api-key": {"type": "apiKey", "in": "header", "name": "x-api-key"}
|
|
31
|
+
}
|
|
32
|
+
return orjson.dumps(openapi)
|