genkit-fastapi 0.12.0__tar.gz → 0.13.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: genkit-fastapi
3
- Version: 0.12.0
3
+ Version: 0.13.0
4
4
  Summary: Hang flows and agents on the FastAPI app you already have
5
5
  Project-URL: Bug Tracker, https://github.com/genkit-ai/genkit/issues
6
6
  Project-URL: Changelog, https://github.com/genkit-ai/genkit/releases
@@ -31,14 +31,24 @@ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
31
31
  Classifier: Typing :: Typed
32
32
  Requires-Python: >=3.10
33
33
  Requires-Dist: fastapi>=0.100.0
34
- Requires-Dist: genkit
35
- Requires-Dist: pydantic>=2.10.5
34
+ Requires-Dist: genkit<2,>=0.13.0
35
+ Requires-Dist: pydantic>=2.11
36
36
  Description-Content-Type: text/markdown
37
37
 
38
38
  # Genkit FastAPI Plugin
39
39
 
40
40
  Expose Genkit flows and agents as HTTP endpoints in a FastAPI application.
41
41
 
42
+ > **Building with a coding agent? Install the Genkit Python skill first.**
43
+ >
44
+ > ```bash
45
+ > npx skills add genkit-ai/skills --skill developing-genkit-python
46
+ > ```
47
+ >
48
+ > It teaches your agent the current Genkit Python APIs and common gotchas.
49
+ > Source, manual install and skills for other languages:
50
+ > [genkit-ai/skills](https://github.com/genkit-ai/skills).
51
+
42
52
  ## Installation
43
53
 
44
54
  ```bash
@@ -57,7 +67,7 @@ from genkit import Genkit
57
67
  from genkit_fastapi import serve_flow
58
68
  from genkit_google_genai import GoogleAI
59
69
 
60
- ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini_model('gemini-flash-latest'))
70
+ ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
61
71
  app = FastAPI()
62
72
 
63
73
 
@@ -81,15 +91,15 @@ app.include_router(serve_flow(chat_flow), prefix='/api')
81
91
 
82
92
  ### Serving Agents (`serve_agent`)
83
93
 
84
- Use `serve_agent` to expose an agent as FastAPI routes (including `/getSnapshot` and `/abort` endpoints when session state storage is enabled):
94
+ Use `serve_agent` to expose an agent as FastAPI routes (including `/getSnapshot` and `/abort` endpoints when session state storage is enabled). Agents are experimental, so `serve_agent` comes from `genkit_fastapi.exp`:
85
95
 
86
96
  ```python
87
97
  from fastapi import FastAPI
88
98
  from genkit.exp import Genkit
89
- from genkit_fastapi import serve_agent
99
+ from genkit_fastapi.exp import serve_agent
90
100
  from genkit_google_genai import GoogleAI
91
101
 
92
- ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini_model('gemini-flash-latest'))
102
+ ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
93
103
  app = FastAPI()
94
104
 
95
105
 
@@ -100,7 +110,7 @@ async def get_weather(location: str) -> str:
100
110
 
101
111
  weather_agent = ai.define_agent(
102
112
  name='weatherAgent',
103
- model=GoogleAI.gemini_model('gemini-flash-latest'),
113
+ model=GoogleAI.gemini('gemini-flash-latest'),
104
114
  system='You are a helpful weather assistant.',
105
115
  tools=[get_weather],
106
116
  )
@@ -132,6 +142,63 @@ app.include_router(
132
142
  )
133
143
  ```
134
144
 
145
+ ### Streaming from Custom Routes (`genkit.web.to_sse`)
146
+
147
+ `to_sse(handle)` frames any streaming handle as Genkit SSE events: a `data: {"message": ...}` per chunk, then `data: {"result": ...}`, or `data: {"error": ...}` if the run fails. It takes `flow.stream()`, `ai.generate_stream()`, `prompt.stream()` and `chat.send_stream()`, so your route keeps its own typed params and `Depends(...)` and still sends the frames `serve_flow` sends:
148
+
149
+ ```python
150
+ from fastapi import Depends, FastAPI
151
+ from fastapi.responses import StreamingResponse
152
+ from genkit import FlowContext, Genkit
153
+ from genkit.web import to_sse
154
+
155
+ ai = Genkit(...)
156
+ app = FastAPI()
157
+
158
+
159
+ @ai.flow()
160
+ async def ask_chef(prompt: str, ctx: FlowContext[str]) -> str:
161
+ stream = ai.generate_stream(prompt=prompt)
162
+ async for chunk in stream:
163
+ ctx.send_chunk(chunk.text)
164
+ return (await stream.response).text
165
+
166
+
167
+ @app.post('/chat/stream')
168
+ async def chat_stream(prompt: str, user: User = Depends(current_user)):
169
+ # 1. FastAPI owns the route: typed params, Depends, OpenAPI
170
+ stream = ask_chef.stream(prompt, context={'user_id': user.id})
171
+
172
+ # 2. Genkit owns the wire
173
+ return StreamingResponse(to_sse(stream), media_type='text/event-stream')
174
+ # => data: {"message":"Pad thai"}
175
+ # data: {"message":", no peanuts."}
176
+ # data: {"result":"Pad thai, no peanuts."}
177
+ ```
178
+
179
+ > [!WARNING]
180
+ > The `result` frame is whatever the run returns, over SSE and JSON alike. Return `response.text` or `response.output` from a served flow, not the `ModelResponse`: its `request` field carries the system prompt, tool definitions, retrieved documents and history. The same goes for `to_sse(ai.generate_stream(...))`, whose result is the whole `ModelResponse`.
181
+
182
+ `to_sse(chat.send_stream(...))` frames agent turns the same way `serve_agent` does (`AgentStreamChunk` messages, then the `AgentOutput` result). Failures are logged with Python's logging module (5xx with a traceback, 4xx as a warning), so they show up wherever your app's logging config sends them.
183
+
184
+ ### Handling Full Genkit Requests (`handle_genkit_request`)
185
+
186
+ When FastAPI owns the route signature and `Depends(...)` parameters (for authentication, rate limiting, or database sessions) and you want one endpoint to serve both JSON `POST` (`{"result": ...}`) and SSE streaming (`Accept: text/event-stream` or `?stream=true`), delegate the HTTP turn to `handle_genkit_request`:
187
+
188
+ ```python
189
+ from fastapi import Depends, Request
190
+ from genkit_fastapi import handle_genkit_request
191
+
192
+
193
+ @app.post('/api/deploy')
194
+ async def deploy_endpoint(request: Request, user: User = Depends(current_user)):
195
+ return await handle_genkit_request(
196
+ request,
197
+ action=deploy_service,
198
+ context={'user_id': user.id},
199
+ )
200
+ ```
201
+
135
202
  ### Decorator Handler (`genkit_fastapi_handler`)
136
203
 
137
204
  For custom route definitions, you can also use `@genkit_fastapi_handler`:
@@ -140,7 +207,7 @@ For custom route definitions, you can also use `@genkit_fastapi_handler`:
140
207
  from genkit_fastapi import genkit_fastapi_handler
141
208
 
142
209
 
143
- @app.post('/custom-chat', response_model=None)
210
+ @app.post('/custom-chat')
144
211
  @genkit_fastapi_handler(ai)
145
212
  @ai.flow()
146
213
  async def custom_chat(prompt: str) -> str:
@@ -0,0 +1,203 @@
1
+ # Genkit FastAPI Plugin
2
+
3
+ Expose Genkit flows and agents as HTTP endpoints in a FastAPI application.
4
+
5
+ > **Building with a coding agent? Install the Genkit Python skill first.**
6
+ >
7
+ > ```bash
8
+ > npx skills add genkit-ai/skills --skill developing-genkit-python
9
+ > ```
10
+ >
11
+ > It teaches your agent the current Genkit Python APIs and common gotchas.
12
+ > Source, manual install and skills for other languages:
13
+ > [genkit-ai/skills](https://github.com/genkit-ai/skills).
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ uv add genkit-fastapi genkit-google-genai
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ### Serving Flows (`serve_flow`)
24
+
25
+ Use `serve_flow` to register a Genkit flow as a FastAPI endpoint:
26
+
27
+ ```python
28
+ from fastapi import FastAPI
29
+ from genkit import Genkit
30
+ from genkit_fastapi import serve_flow
31
+ from genkit_google_genai import GoogleAI
32
+
33
+ ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
34
+ app = FastAPI()
35
+
36
+
37
+ @ai.tool(description='Get current weather for a location')
38
+ async def get_weather(location: str) -> str:
39
+ return f'Sunny in {location}'
40
+
41
+
42
+ @ai.flow()
43
+ async def chat_flow(prompt: str) -> str:
44
+ response = await ai.generate(
45
+ prompt=prompt,
46
+ tools=[get_weather],
47
+ )
48
+ return response.text
49
+
50
+
51
+ # Mount flow endpoint at POST /api/chat_flow
52
+ app.include_router(serve_flow(chat_flow), prefix='/api')
53
+ ```
54
+
55
+ ### Serving Agents (`serve_agent`)
56
+
57
+ Use `serve_agent` to expose an agent as FastAPI routes (including `/getSnapshot` and `/abort` endpoints when session state storage is enabled). Agents are experimental, so `serve_agent` comes from `genkit_fastapi.exp`:
58
+
59
+ ```python
60
+ from fastapi import FastAPI
61
+ from genkit.exp import Genkit
62
+ from genkit_fastapi.exp import serve_agent
63
+ from genkit_google_genai import GoogleAI
64
+
65
+ ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
66
+ app = FastAPI()
67
+
68
+
69
+ @ai.tool(description='Get current weather for a location')
70
+ async def get_weather(location: str) -> str:
71
+ return f'Sunny in {location}'
72
+
73
+
74
+ weather_agent = ai.define_agent(
75
+ name='weatherAgent',
76
+ model=GoogleAI.gemini('gemini-flash-latest'),
77
+ system='You are a helpful weather assistant.',
78
+ tools=[get_weather],
79
+ )
80
+
81
+ # Mount agent turn route at POST /api/weatherAgent (plus /getSnapshot and /abort companion endpoints)
82
+ app.include_router(serve_agent(weather_agent), prefix='/api')
83
+ ```
84
+
85
+ ### Custom Base Path & Dependency Injection
86
+
87
+ Customize the base path or resolve request context using FastAPI's dependency injection system:
88
+
89
+ ```python
90
+ from fastapi import Depends, Header
91
+ from genkit_fastapi import serve_flow
92
+
93
+
94
+ async def user_context(authorization: str = Header(...)):
95
+ return {'uid': parse_token(authorization)}
96
+
97
+
98
+ app.include_router(
99
+ serve_flow(
100
+ chat_flow,
101
+ base_path='/chat',
102
+ context_dependency=user_context,
103
+ ),
104
+ prefix='/api',
105
+ )
106
+ ```
107
+
108
+ ### Streaming from Custom Routes (`genkit.web.to_sse`)
109
+
110
+ `to_sse(handle)` frames any streaming handle as Genkit SSE events: a `data: {"message": ...}` per chunk, then `data: {"result": ...}`, or `data: {"error": ...}` if the run fails. It takes `flow.stream()`, `ai.generate_stream()`, `prompt.stream()` and `chat.send_stream()`, so your route keeps its own typed params and `Depends(...)` and still sends the frames `serve_flow` sends:
111
+
112
+ ```python
113
+ from fastapi import Depends, FastAPI
114
+ from fastapi.responses import StreamingResponse
115
+ from genkit import FlowContext, Genkit
116
+ from genkit.web import to_sse
117
+
118
+ ai = Genkit(...)
119
+ app = FastAPI()
120
+
121
+
122
+ @ai.flow()
123
+ async def ask_chef(prompt: str, ctx: FlowContext[str]) -> str:
124
+ stream = ai.generate_stream(prompt=prompt)
125
+ async for chunk in stream:
126
+ ctx.send_chunk(chunk.text)
127
+ return (await stream.response).text
128
+
129
+
130
+ @app.post('/chat/stream')
131
+ async def chat_stream(prompt: str, user: User = Depends(current_user)):
132
+ # 1. FastAPI owns the route: typed params, Depends, OpenAPI
133
+ stream = ask_chef.stream(prompt, context={'user_id': user.id})
134
+
135
+ # 2. Genkit owns the wire
136
+ return StreamingResponse(to_sse(stream), media_type='text/event-stream')
137
+ # => data: {"message":"Pad thai"}
138
+ # data: {"message":", no peanuts."}
139
+ # data: {"result":"Pad thai, no peanuts."}
140
+ ```
141
+
142
+ > [!WARNING]
143
+ > The `result` frame is whatever the run returns, over SSE and JSON alike. Return `response.text` or `response.output` from a served flow, not the `ModelResponse`: its `request` field carries the system prompt, tool definitions, retrieved documents and history. The same goes for `to_sse(ai.generate_stream(...))`, whose result is the whole `ModelResponse`.
144
+
145
+ `to_sse(chat.send_stream(...))` frames agent turns the same way `serve_agent` does (`AgentStreamChunk` messages, then the `AgentOutput` result). Failures are logged with Python's logging module (5xx with a traceback, 4xx as a warning), so they show up wherever your app's logging config sends them.
146
+
147
+ ### Handling Full Genkit Requests (`handle_genkit_request`)
148
+
149
+ When FastAPI owns the route signature and `Depends(...)` parameters (for authentication, rate limiting, or database sessions) and you want one endpoint to serve both JSON `POST` (`{"result": ...}`) and SSE streaming (`Accept: text/event-stream` or `?stream=true`), delegate the HTTP turn to `handle_genkit_request`:
150
+
151
+ ```python
152
+ from fastapi import Depends, Request
153
+ from genkit_fastapi import handle_genkit_request
154
+
155
+
156
+ @app.post('/api/deploy')
157
+ async def deploy_endpoint(request: Request, user: User = Depends(current_user)):
158
+ return await handle_genkit_request(
159
+ request,
160
+ action=deploy_service,
161
+ context={'user_id': user.id},
162
+ )
163
+ ```
164
+
165
+ ### Decorator Handler (`genkit_fastapi_handler`)
166
+
167
+ For custom route definitions, you can also use `@genkit_fastapi_handler`:
168
+
169
+ ```python
170
+ from genkit_fastapi import genkit_fastapi_handler
171
+
172
+
173
+ @app.post('/custom-chat')
174
+ @genkit_fastapi_handler(ai)
175
+ @ai.flow()
176
+ async def custom_chat(prompt: str) -> str:
177
+ response = await ai.generate(
178
+ prompt=prompt,
179
+ tools=[get_weather],
180
+ )
181
+ return response.text
182
+ ```
183
+
184
+ ## Running
185
+
186
+ ```bash
187
+ # With Genkit Dev UI
188
+ genkit start -- uvicorn main:app --reload
189
+
190
+ # Production (no Dev UI)
191
+ uvicorn main:app
192
+ ```
193
+
194
+ ## Streaming
195
+
196
+ Endpoints automatically support streaming when the client sends `Accept: text/event-stream` or specifies `?stream=true`:
197
+
198
+ ```bash
199
+ curl -X POST http://localhost:8000/api/chat_flow \
200
+ -H "Content-Type: application/json" \
201
+ -H "Accept: text/event-stream" \
202
+ -d '{"data": "Tell me a joke"}'
203
+ ```
@@ -36,7 +36,7 @@ classifiers = [
36
36
  "Typing :: Typed",
37
37
  "License :: OSI Approved :: Apache Software License",
38
38
  ]
39
- dependencies = ["genkit", "pydantic>=2.10.5", "fastapi>=0.100.0"]
39
+ dependencies = ["genkit>=0.13.0,<2", "pydantic>=2.11", "fastapi>=0.100.0"]
40
40
  description = "Hang flows and agents on the FastAPI app you already have"
41
41
  keywords = [
42
42
  "genkit",
@@ -47,7 +47,7 @@ license = "Apache-2.0"
47
47
  name = "genkit-fastapi"
48
48
  readme = "README.md"
49
49
  requires-python = ">=3.10"
50
- version = "0.12.0"
50
+ version = "0.13.0"
51
51
 
52
52
  [project.urls]
53
53
  "Bug Tracker" = "https://github.com/genkit-ai/genkit/issues"
@@ -0,0 +1,60 @@
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
+ """Serve Genkit flows as FastAPI routes.
18
+
19
+ With ``GENKIT_ENV=dev``, the Dev UI reflection server starts on a background
20
+ thread. No lifespan wiring needed.
21
+
22
+ ```python
23
+ from fastapi import FastAPI
24
+ from genkit import Genkit
25
+ from genkit_fastapi import serve_flow
26
+ from genkit_google_genai import GoogleAI
27
+
28
+ ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
29
+ app = FastAPI()
30
+
31
+
32
+ @ai.flow()
33
+ async def suggest_dish(cuisine: str) -> str:
34
+ response = await ai.generate(prompt=f'Suggest one {cuisine} dish.')
35
+ return response.text
36
+
37
+
38
+ # POST /api/suggest_dish
39
+ app.include_router(serve_flow(suggest_dish), prefix='/api')
40
+ ```
41
+
42
+ For a custom route, stack ``@genkit_fastapi_handler(ai)`` over ``@ai.flow()``.
43
+
44
+ Agents are experimental, so their routes come from ``genkit_fastapi.exp``::
45
+
46
+ from genkit_fastapi.exp import serve_agent
47
+
48
+ ```bash
49
+ genkit start -- uvicorn main:app --reload # with Dev UI
50
+ uvicorn main:app # production
51
+ ```
52
+ """
53
+
54
+ from ._handler import genkit_fastapi_handler, handle_genkit_request, serve_flow
55
+
56
+ __all__ = [
57
+ 'genkit_fastapi_handler',
58
+ 'handle_genkit_request',
59
+ 'serve_flow',
60
+ ]