genkit-fastapi 0.9.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.
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
#
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
"""FastAPI Plugin for Genkit.
|
|
18
|
+
|
|
19
|
+
This plugin provides FastAPI integration for Genkit, enabling you to expose
|
|
20
|
+
Genkit flows as HTTP endpoints in a FastAPI application.
|
|
21
|
+
|
|
22
|
+
The Dev UI reflection server starts automatically in a background thread when
|
|
23
|
+
``GENKIT_ENV=dev`` is set — no lifespan wiring needed.
|
|
24
|
+
|
|
25
|
+
Example:
|
|
26
|
+
```python
|
|
27
|
+
from fastapi import FastAPI
|
|
28
|
+
from genkit import Genkit
|
|
29
|
+
from genkit_fastapi import genkit_fastapi_handler
|
|
30
|
+
from genkit_google_genai import GoogleAI
|
|
31
|
+
|
|
32
|
+
# 1. Initialize Genkit and FastAPI app
|
|
33
|
+
ai = Genkit(plugins=[GoogleAI()])
|
|
34
|
+
app = FastAPI()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# 2. Define flow and expose as FastAPI endpoint in one clean decorator stack
|
|
38
|
+
@app.post('/chat', response_model=None)
|
|
39
|
+
@genkit_fastapi_handler(ai)
|
|
40
|
+
@ai.flow()
|
|
41
|
+
async def chat_flow(prompt: str) -> str:
|
|
42
|
+
res = await ai.generate(
|
|
43
|
+
model='googleai/gemini-flash-latest',
|
|
44
|
+
prompt=f'Answer concisely: {prompt}',
|
|
45
|
+
)
|
|
46
|
+
return res.text
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# POST /chat {"data": "Why is the sky blue?"}
|
|
50
|
+
# => {"result": "The sky appears blue due to Rayleigh scattering..."}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Running:
|
|
54
|
+
```bash
|
|
55
|
+
# With Genkit Dev UI
|
|
56
|
+
genkit start -- uvicorn main:app --reload
|
|
57
|
+
|
|
58
|
+
# Production (no Dev UI)
|
|
59
|
+
uvicorn main:app
|
|
60
|
+
```
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
from .handler import genkit_fastapi_handler, handle_genkit_request, serve_agent, serve_flow
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def package_name() -> str:
|
|
67
|
+
"""Get the package name for the FastAPI plugin."""
|
|
68
|
+
return 'genkit_fastapi'
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
__all__ = [
|
|
72
|
+
'genkit_fastapi_handler',
|
|
73
|
+
'handle_genkit_request',
|
|
74
|
+
'package_name',
|
|
75
|
+
'serve_agent',
|
|
76
|
+
'serve_flow',
|
|
77
|
+
]
|
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
#
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
"""Genkit FastAPI handler for serving flows and agents as HTTP endpoints."""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import asyncio
|
|
22
|
+
import json
|
|
23
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
|
|
24
|
+
from typing import Any, TypeVar, cast
|
|
25
|
+
|
|
26
|
+
from fastapi import APIRouter, Depends, Request, Response
|
|
27
|
+
from fastapi.responses import StreamingResponse
|
|
28
|
+
from pydantic import BaseModel
|
|
29
|
+
|
|
30
|
+
from genkit import Action, ActionKind, Genkit, GenkitError
|
|
31
|
+
from genkit.agent import Agent, SessionSnapshot
|
|
32
|
+
from genkit.plugin_api import ContextProvider, RequestData, get_callable_json
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def parse_snapshot_lookup_input(input_val: dict[str, Any] | str | None) -> tuple[str | None, str | None]:
|
|
36
|
+
"""Parse snapshot lookup params from payload dict or bare snapshot ID string."""
|
|
37
|
+
if isinstance(input_val, str):
|
|
38
|
+
return input_val, None
|
|
39
|
+
if isinstance(input_val, dict):
|
|
40
|
+
sid = input_val.get('snapshotId') or input_val.get('snapshot_id')
|
|
41
|
+
sess_id = input_val.get('sessionId') or input_val.get('session_id')
|
|
42
|
+
if bool(sid) == bool(sess_id):
|
|
43
|
+
raise GenkitError(
|
|
44
|
+
status='INVALID_ARGUMENT',
|
|
45
|
+
message=(
|
|
46
|
+
"getSnapshot requires exactly one of 'snapshotId' (or 'snapshot_id') "
|
|
47
|
+
"or 'sessionId' (or 'session_id')."
|
|
48
|
+
),
|
|
49
|
+
)
|
|
50
|
+
return sid, sess_id
|
|
51
|
+
raise GenkitError(
|
|
52
|
+
status='INVALID_ARGUMENT',
|
|
53
|
+
message='getSnapshot input must be a dictionary or snapshot ID string.',
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def parse_abort_input(input_val: dict[str, Any] | str | None) -> str:
|
|
58
|
+
"""Parse snapshot ID from payload dict or bare snapshot ID string."""
|
|
59
|
+
if isinstance(input_val, str):
|
|
60
|
+
return input_val
|
|
61
|
+
if isinstance(input_val, dict):
|
|
62
|
+
sid = input_val.get('snapshotId') or input_val.get('snapshot_id')
|
|
63
|
+
if sid:
|
|
64
|
+
return sid
|
|
65
|
+
raise GenkitError(
|
|
66
|
+
status='INVALID_ARGUMENT',
|
|
67
|
+
message="abort requires 'snapshotId' (or 'snapshot_id') in input.",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# Compact JSON (no spaces) for smaller wire payload.
|
|
72
|
+
JSON_SEPARATORS = (',', ':')
|
|
73
|
+
|
|
74
|
+
StateT = TypeVar('StateT', bound=BaseModel)
|
|
75
|
+
InputT = TypeVar('InputT')
|
|
76
|
+
OutputT = TypeVar('OutputT')
|
|
77
|
+
ChunkT = TypeVar('ChunkT')
|
|
78
|
+
InitT = TypeVar('InitT')
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def to_dict(obj: Any) -> Any: # noqa: ANN401
|
|
82
|
+
"""Convert object to dict if it's a Pydantic model, otherwise return as-is."""
|
|
83
|
+
return obj.model_dump(by_alias=True, exclude_none=True) if isinstance(obj, BaseModel) else obj
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class FastAPIRequestData(RequestData):
|
|
87
|
+
"""Wraps FastAPI request data for Genkit context."""
|
|
88
|
+
|
|
89
|
+
def __init__(self, request: Request, body: dict[str, Any] | None) -> None:
|
|
90
|
+
"""Initialize request data wrapper."""
|
|
91
|
+
super().__init__(request=request)
|
|
92
|
+
self.method = request.method
|
|
93
|
+
self.headers = {k.lower(): v for k, v in request.headers.items()}
|
|
94
|
+
self.input = body.get('data') if body else None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def json_error_response(error: Exception, status_code: int = 400) -> Response:
|
|
98
|
+
"""Build a compact JSON error response from an exception."""
|
|
99
|
+
ex = error.cause if isinstance(error, GenkitError) else error
|
|
100
|
+
return Response(
|
|
101
|
+
status_code=status_code,
|
|
102
|
+
content=json.dumps(get_callable_json(ex), separators=JSON_SEPARATORS),
|
|
103
|
+
media_type='application/json',
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def extract_action_input(body: dict[str, Any]) -> object:
|
|
108
|
+
"""Extract action input payload from supported wire formats."""
|
|
109
|
+
if 'data' in body:
|
|
110
|
+
return body['data']
|
|
111
|
+
if 'input' in body:
|
|
112
|
+
return body['input']
|
|
113
|
+
if 'message' in body:
|
|
114
|
+
return {'message': {'role': 'user', 'content': [{'text': str(body['message'])}]}}
|
|
115
|
+
if 'snapshotId' in body or 'sessionId' in body:
|
|
116
|
+
return body
|
|
117
|
+
# Callable clients omit ``data`` when runFlow has no input (POST ``{}``).
|
|
118
|
+
# Match Express: ``request.body.data`` is undefined, not a wire error.
|
|
119
|
+
if not body:
|
|
120
|
+
return None
|
|
121
|
+
raise GenkitError(
|
|
122
|
+
status='INVALID_ARGUMENT',
|
|
123
|
+
message='Action request must be wrapped in {"data": ...} object',
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def resolve_session_init(body: dict[str, Any], query_params: Mapping[str, str]) -> object:
|
|
128
|
+
"""Resolve per-run init data, injecting session_id from query parameters if present."""
|
|
129
|
+
init = body.get('init')
|
|
130
|
+
query_session_id = query_params.get('session_id') or query_params.get('thread_id')
|
|
131
|
+
if not query_session_id:
|
|
132
|
+
return init
|
|
133
|
+
if isinstance(init, dict) and not init.get('session_id') and not init.get('sessionId'):
|
|
134
|
+
return {**init, 'session_id': query_session_id}
|
|
135
|
+
if init is None:
|
|
136
|
+
return {'session_id': query_session_id}
|
|
137
|
+
return init
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def wants_stream(request: Request) -> bool:
|
|
141
|
+
"""Check if the client requested an event stream or NDJSON stream."""
|
|
142
|
+
accept = request.headers.get('accept', '')
|
|
143
|
+
return 'text/event-stream' in accept or request.query_params.get('stream') == 'true'
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def format_stream_chunk(chunk: object) -> str:
|
|
147
|
+
"""Format a stream chunk for SSE."""
|
|
148
|
+
msg_json = json.dumps({'message': to_dict(chunk)}, separators=JSON_SEPARATORS)
|
|
149
|
+
return f'data: {msg_json}\n\n'
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def format_stream_result(result: object) -> str:
|
|
153
|
+
"""Format the final stream result for SSE."""
|
|
154
|
+
res_json = json.dumps({'result': to_dict(result)}, separators=JSON_SEPARATORS)
|
|
155
|
+
return f'data: {res_json}\n\n'
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def format_stream_error(error: Exception) -> str:
|
|
159
|
+
"""Format a stream failure as a canonical SSE data event."""
|
|
160
|
+
ex = error.cause if isinstance(error, GenkitError) else error
|
|
161
|
+
return f'data: {json.dumps({"error": get_callable_json(ex)}, separators=JSON_SEPARATORS)}\n\n'
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
async def handle_genkit_request(
|
|
165
|
+
request: Request,
|
|
166
|
+
*,
|
|
167
|
+
action: Action[InputT, OutputT, ChunkT, InitT],
|
|
168
|
+
context: dict[str, object] | None = None,
|
|
169
|
+
init: InitT | dict[str, Any] | None = None,
|
|
170
|
+
) -> Response | dict[str, Any]:
|
|
171
|
+
"""Run one Genkit action request and return its FastAPI response.
|
|
172
|
+
|
|
173
|
+
This is the wire contract every route sits on. It reads the JSON body in
|
|
174
|
+
whichever shape the client sends (``data`` / ``input`` / ``message``, or a
|
|
175
|
+
snapshot/session lookup), threads ``init`` (an agent's session identity), and
|
|
176
|
+
then either streams SSE frames — ``data: {"message": ...}`` chunks followed by
|
|
177
|
+
a final ``data: {"result": ...}`` — or returns a one-shot ``{"result": ...}``.
|
|
178
|
+
|
|
179
|
+
``context`` and ``init`` are handed straight to the action, so you can resolve
|
|
180
|
+
auth, session identity, and per-request state however you like and pass them in.
|
|
181
|
+
That makes this the escape hatch for full control: write your own ``@app.post``
|
|
182
|
+
endpoint with any ``Depends(...)`` params you need, build context and init, and
|
|
183
|
+
call this to get the exact Genkit wire format without re-implementing it.
|
|
184
|
+
|
|
185
|
+
Args:
|
|
186
|
+
request: The incoming FastAPI request.
|
|
187
|
+
action: The flow or agent action to run.
|
|
188
|
+
context: Optional context dict passed through to the action.
|
|
189
|
+
init: Optional session identity / init payload passed through to the action.
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
A streaming SSE response, a ``{"result": ...}`` dict, or an error Response.
|
|
193
|
+
"""
|
|
194
|
+
body = await request.json()
|
|
195
|
+
if not isinstance(body, dict):
|
|
196
|
+
return json_error_response(
|
|
197
|
+
GenkitError(
|
|
198
|
+
status='INVALID_ARGUMENT',
|
|
199
|
+
message='Action request must be a JSON object',
|
|
200
|
+
)
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
try:
|
|
204
|
+
input_data = extract_action_input(body)
|
|
205
|
+
except GenkitError as err:
|
|
206
|
+
return json_error_response(err)
|
|
207
|
+
|
|
208
|
+
resolved_init = init if init is not None else resolve_session_init(body, request.query_params)
|
|
209
|
+
action_obj = cast(Action[Any, Any, Any, Any], action)
|
|
210
|
+
|
|
211
|
+
if wants_stream(request):
|
|
212
|
+
|
|
213
|
+
async def event_stream() -> AsyncIterator[str]:
|
|
214
|
+
try:
|
|
215
|
+
stream_response = action_obj.stream(input_data, context=context, init=resolved_init)
|
|
216
|
+
async for chunk in stream_response.stream:
|
|
217
|
+
yield format_stream_chunk(chunk)
|
|
218
|
+
result = await stream_response.response
|
|
219
|
+
yield format_stream_result(result)
|
|
220
|
+
except Exception as e:
|
|
221
|
+
yield format_stream_error(e)
|
|
222
|
+
|
|
223
|
+
return StreamingResponse(event_stream(), media_type='text/event-stream')
|
|
224
|
+
|
|
225
|
+
try:
|
|
226
|
+
response = await action_obj.run(input_data, context=context, init=resolved_init)
|
|
227
|
+
if response.response is None and action_obj.kind == ActionKind.AGENT_SNAPSHOT:
|
|
228
|
+
return Response(status_code=404)
|
|
229
|
+
return {'result': to_dict(response.response)}
|
|
230
|
+
except Exception as e:
|
|
231
|
+
return json_error_response(e, status_code=500)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def genkit_fastapi_handler(
|
|
235
|
+
ai: Genkit,
|
|
236
|
+
context_provider: ContextProvider | None = None,
|
|
237
|
+
) -> Callable[
|
|
238
|
+
[Callable[[], Action[InputT, OutputT, ChunkT, InitT]] | Action[InputT, OutputT, ChunkT, InitT]],
|
|
239
|
+
Callable[[Request], Awaitable[Response | dict[str, Any]]],
|
|
240
|
+
]:
|
|
241
|
+
"""Decorator for serving Genkit actions (flows, agents, tools, etc.) via FastAPI.
|
|
242
|
+
|
|
243
|
+
Example (decorator on flow directly):
|
|
244
|
+
```python
|
|
245
|
+
@app.post('/chat', response_model=None)
|
|
246
|
+
@genkit_fastapi_handler(ai)
|
|
247
|
+
@ai.flow()
|
|
248
|
+
async def chat(prompt: str) -> str:
|
|
249
|
+
response = await ai.generate(prompt=prompt)
|
|
250
|
+
return response.text
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
Example (wrapper when flow is defined later; must be async):
|
|
254
|
+
```python
|
|
255
|
+
@app.post('/chat', response_model=None)
|
|
256
|
+
@genkit_fastapi_handler(ai)
|
|
257
|
+
async def chat():
|
|
258
|
+
return my_flow
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
@ai.flow()
|
|
262
|
+
async def my_flow(prompt: str) -> str: ...
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
Args:
|
|
266
|
+
ai: The Genkit instance.
|
|
267
|
+
context_provider: Optional function to extract context from the request.
|
|
268
|
+
|
|
269
|
+
Returns:
|
|
270
|
+
A decorator that wraps an Action or a function returning an Action.
|
|
271
|
+
"""
|
|
272
|
+
|
|
273
|
+
def decorator(
|
|
274
|
+
fn: Callable[[], Action[InputT, OutputT, ChunkT, InitT]] | Action[InputT, OutputT, ChunkT, InitT],
|
|
275
|
+
) -> Callable[[Request], Awaitable[Response | dict[str, Any]]]:
|
|
276
|
+
async def handler(request: Request) -> Response | dict[str, Any]:
|
|
277
|
+
if isinstance(fn, Action):
|
|
278
|
+
action = fn
|
|
279
|
+
else:
|
|
280
|
+
result = fn()
|
|
281
|
+
if not asyncio.iscoroutine(result):
|
|
282
|
+
raise GenkitError(
|
|
283
|
+
status='INVALID_ARGUMENT',
|
|
284
|
+
message='genkit_fastapi_handler wrapper must be async when action is defined elsewhere',
|
|
285
|
+
)
|
|
286
|
+
action = await result
|
|
287
|
+
if not isinstance(action, Action):
|
|
288
|
+
raise GenkitError(
|
|
289
|
+
status='INVALID_ARGUMENT',
|
|
290
|
+
message='genkit_fastapi_handler must wrap an Action or an async function returning an Action',
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
# This decorator reads context from the request itself. Routes that
|
|
294
|
+
# want FastAPI's dependency graph (auth schemes, DB sessions) go
|
|
295
|
+
# through serve_flow/serve_agent's context_dependency instead.
|
|
296
|
+
action_context: dict[str, object] | None = None
|
|
297
|
+
if context_provider:
|
|
298
|
+
body = await request.json()
|
|
299
|
+
request_data = FastAPIRequestData(request, body if isinstance(body, dict) else None)
|
|
300
|
+
context = context_provider(request_data)
|
|
301
|
+
if asyncio.iscoroutine(context):
|
|
302
|
+
context = await context
|
|
303
|
+
if isinstance(context, dict):
|
|
304
|
+
action_context = context
|
|
305
|
+
|
|
306
|
+
return await handle_genkit_request(
|
|
307
|
+
request,
|
|
308
|
+
action=cast(Action[InputT, OutputT, ChunkT, InitT], action), # ty: ignore[redundant-cast]
|
|
309
|
+
context=action_context,
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
return handler
|
|
313
|
+
|
|
314
|
+
return decorator
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _mount_action(
|
|
318
|
+
router: APIRouter,
|
|
319
|
+
path: str,
|
|
320
|
+
action: Action[InputT, OutputT, ChunkT, InitT],
|
|
321
|
+
*,
|
|
322
|
+
context_dependency: Callable[..., Any] | None = None,
|
|
323
|
+
) -> None:
|
|
324
|
+
"""Register one action on the router, honoring FastAPI DI when asked.
|
|
325
|
+
|
|
326
|
+
With a ``context_dependency`` the route's own signature carries the
|
|
327
|
+
dependency, so FastAPI resolves it (and any sub-dependencies or security
|
|
328
|
+
schemes) and the resulting dict is threaded into the action as context.
|
|
329
|
+
"""
|
|
330
|
+
if context_dependency is not None:
|
|
331
|
+
|
|
332
|
+
async def endpoint_with_context(
|
|
333
|
+
request: Request,
|
|
334
|
+
context: Any = Depends(context_dependency), # noqa: ANN401, B008
|
|
335
|
+
) -> Response | dict[str, Any]:
|
|
336
|
+
return await handle_genkit_request(
|
|
337
|
+
request,
|
|
338
|
+
action=action,
|
|
339
|
+
context=context if isinstance(context, dict) else None,
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
router.post(path, response_model=None)(endpoint_with_context)
|
|
343
|
+
return
|
|
344
|
+
|
|
345
|
+
async def endpoint(request: Request) -> Response | dict[str, Any]:
|
|
346
|
+
return await handle_genkit_request(request, action=action)
|
|
347
|
+
|
|
348
|
+
router.post(path, response_model=None)(endpoint)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def serve_flow(
|
|
352
|
+
flow: Action[InputT, OutputT, ChunkT, InitT],
|
|
353
|
+
*,
|
|
354
|
+
base_path: str | None = None,
|
|
355
|
+
context_dependency: Callable[..., Any] | None = None,
|
|
356
|
+
) -> APIRouter:
|
|
357
|
+
"""Build an APIRouter serving a single flow over HTTP.
|
|
358
|
+
|
|
359
|
+
Mount the returned router like any other, so FastAPI's own prefix / dependencies handle wiring::
|
|
360
|
+
|
|
361
|
+
app.include_router(serve_flow(chat_flow), prefix='/api')
|
|
362
|
+
|
|
363
|
+
Args:
|
|
364
|
+
flow: The flow action to serve.
|
|
365
|
+
base_path: Route path. Defaults to /<flow name>.
|
|
366
|
+
context_dependency: A FastAPI dependency whose resolved value becomes the
|
|
367
|
+
action context. Use this to reuse existing ``Depends``-based auth /
|
|
368
|
+
resources.
|
|
369
|
+
|
|
370
|
+
Returns:
|
|
371
|
+
An APIRouter with the single flow route registered.
|
|
372
|
+
"""
|
|
373
|
+
resolved_base_path = f'/{flow.name}' if base_path is None else base_path
|
|
374
|
+
router = APIRouter(tags=[flow.name])
|
|
375
|
+
_mount_action(
|
|
376
|
+
router,
|
|
377
|
+
resolved_base_path,
|
|
378
|
+
flow,
|
|
379
|
+
context_dependency=context_dependency,
|
|
380
|
+
)
|
|
381
|
+
return router
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def serve_agent(
|
|
385
|
+
agent: Agent[StateT],
|
|
386
|
+
*,
|
|
387
|
+
base_path: str | None = None,
|
|
388
|
+
context_dependency: Callable[..., Any] | None = None,
|
|
389
|
+
) -> APIRouter:
|
|
390
|
+
"""Build an APIRouter serving an agent and its snapshot/abort endpoints over HTTP.
|
|
391
|
+
|
|
392
|
+
Mount the returned router like any other::
|
|
393
|
+
|
|
394
|
+
app.include_router(serve_agent(weather_agent), prefix='/api')
|
|
395
|
+
|
|
396
|
+
Args:
|
|
397
|
+
agent: The agent to serve.
|
|
398
|
+
base_path: Route path. Defaults to /<agent name>.
|
|
399
|
+
context_dependency: A FastAPI dependency whose resolved value becomes the
|
|
400
|
+
action context, applied to the turn, getSnapshot, and abort routes.
|
|
401
|
+
Use this to reuse existing ``Depends``-based auth / resources.
|
|
402
|
+
|
|
403
|
+
Returns:
|
|
404
|
+
An APIRouter with the turn route plus snapshot/abort endpoints.
|
|
405
|
+
"""
|
|
406
|
+
resolved_base_path = f'/{agent.name}' if base_path is None else base_path
|
|
407
|
+
router = APIRouter(tags=[agent.name])
|
|
408
|
+
|
|
409
|
+
_mount_action(
|
|
410
|
+
router,
|
|
411
|
+
resolved_base_path,
|
|
412
|
+
agent,
|
|
413
|
+
context_dependency=context_dependency,
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
if agent.store is not None:
|
|
417
|
+
|
|
418
|
+
async def snapshot_fn(input_val: dict[str, Any] | str | None = None) -> SessionSnapshot | None:
|
|
419
|
+
sid, sess_id = parse_snapshot_lookup_input(input_val)
|
|
420
|
+
return await agent.get_snapshot_data(snapshot_id=sid, session_id=sess_id)
|
|
421
|
+
|
|
422
|
+
async def abort_fn(input_val: dict[str, Any] | str | None = None) -> dict[str, object]:
|
|
423
|
+
snapshot_id = parse_abort_input(input_val)
|
|
424
|
+
status = await agent.abort_snapshot_data(snapshot_id)
|
|
425
|
+
return {'snapshotId': snapshot_id, 'status': str(status) if status else None}
|
|
426
|
+
|
|
427
|
+
snapshot_action = Action(
|
|
428
|
+
kind=ActionKind.AGENT_SNAPSHOT,
|
|
429
|
+
name=f'{agent.name}_snapshot',
|
|
430
|
+
fn=snapshot_fn,
|
|
431
|
+
description=f'Gets snapshot data for {agent.name}',
|
|
432
|
+
)
|
|
433
|
+
abort_action = Action(
|
|
434
|
+
kind=ActionKind.AGENT_ABORT,
|
|
435
|
+
name=f'{agent.name}_abort',
|
|
436
|
+
fn=abort_fn,
|
|
437
|
+
description=f'Aborts {agent.name} agent by snapshotId',
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
_mount_action(
|
|
441
|
+
router,
|
|
442
|
+
f'{resolved_base_path}/getSnapshot',
|
|
443
|
+
snapshot_action,
|
|
444
|
+
context_dependency=context_dependency,
|
|
445
|
+
)
|
|
446
|
+
_mount_action(
|
|
447
|
+
router,
|
|
448
|
+
f'{resolved_base_path}/abort',
|
|
449
|
+
abort_action,
|
|
450
|
+
context_dependency=context_dependency,
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
return router
|
genkit_fastapi/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: genkit-fastapi
|
|
3
|
+
Version: 0.9.0
|
|
4
|
+
Summary: Genkit FastAPI Plugin
|
|
5
|
+
Project-URL: Bug Tracker, https://github.com/genkit-ai/genkit/issues
|
|
6
|
+
Project-URL: Changelog, https://github.com/genkit-ai/genkit/blob/main/py/packages/genkit-fastapi/CHANGELOG.md
|
|
7
|
+
Project-URL: Documentation, https://firebase.google.com/docs/genkit
|
|
8
|
+
Project-URL: Homepage, https://github.com/genkit-ai/genkit
|
|
9
|
+
Project-URL: Repository, https://github.com/genkit-ai/genkit/tree/main/py
|
|
10
|
+
Author: Google
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: ai,artificial-intelligence,async,fastapi,generative-ai,genkit,llm,machine-learning,server,web
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Environment :: Console
|
|
16
|
+
Classifier: Environment :: Web Environment
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
19
|
+
Classifier: Operating System :: OS Independent
|
|
20
|
+
Classifier: Programming Language :: Python
|
|
21
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
27
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
28
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
29
|
+
Classifier: Typing :: Typed
|
|
30
|
+
Requires-Python: >=3.10
|
|
31
|
+
Requires-Dist: fastapi>=0.100.0
|
|
32
|
+
Requires-Dist: genkit
|
|
33
|
+
Requires-Dist: pydantic>=2.10.5
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
|
|
36
|
+
# Genkit FastAPI Plugin
|
|
37
|
+
|
|
38
|
+
Serve Genkit flows as FastAPI endpoints.
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install genkit-plugin-fastapi
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
from fastapi import FastAPI
|
|
49
|
+
from genkit import Genkit
|
|
50
|
+
from genkit_fastapi import genkit_fastapi_handler
|
|
51
|
+
from genkit_google_genai import GoogleAI
|
|
52
|
+
|
|
53
|
+
ai = Genkit(plugins=[GoogleAI()])
|
|
54
|
+
app = FastAPI()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@ai.flow()
|
|
58
|
+
async def chat_flow(prompt: str) -> str:
|
|
59
|
+
response = await ai.generate(prompt=prompt)
|
|
60
|
+
return response.text
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@app.post('/chat')
|
|
64
|
+
@genkit_fastapi_handler(ai)
|
|
65
|
+
async def chat():
|
|
66
|
+
return chat_flow
|
|
67
|
+
|
|
68
|
+
## Running
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
# With Genkit Dev UI
|
|
72
|
+
genkit start -- uvicorn main:app --reload
|
|
73
|
+
|
|
74
|
+
# Production (no Dev UI)
|
|
75
|
+
uvicorn main:app
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Streaming
|
|
79
|
+
|
|
80
|
+
The handler automatically supports streaming when the client sends `Accept: text/event-stream`:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
curl -X POST http://localhost:8000/chat \
|
|
84
|
+
-H "Content-Type: application/json" \
|
|
85
|
+
-H "Accept: text/event-stream" \
|
|
86
|
+
-d '{"data": "Tell me a joke"}'
|
|
87
|
+
```
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
genkit_fastapi/__init__.py,sha256=BejGbUzsqjTBw-igJMft7eC0s9bAeMpjhRV2Y99WvUE,2215
|
|
2
|
+
genkit_fastapi/handler.py,sha256=sX8f9dM03-O-owj3cE5h8r1rT4ZxakoE3PmnfiJ2VZ8,17078
|
|
3
|
+
genkit_fastapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
genkit_fastapi-0.9.0.dist-info/METADATA,sha256=dvBR41-tcYjYYOOf60udJEx_39aRcyO2pEjwLPNy2eA,2534
|
|
5
|
+
genkit_fastapi-0.9.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
6
|
+
genkit_fastapi-0.9.0.dist-info/licenses/LICENSE,sha256=bsvE5_qSn_2LH2G-haMvT_AoIeINhX6fvzZTlyq2xJY,11340
|
|
7
|
+
genkit_fastapi-0.9.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Google LLC
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|