You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on May 20, 2025. It is now read-only.
Copy file name to clipboardExpand all lines: docs/guides/python/serverless-ai-api.mdx
+33-16Lines changed: 33 additions & 16 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -93,7 +93,7 @@ Our goal is to create an HTTP endpoint `/summarize` (for example) that accepts s
93
93
94
94
```python
95
95
import os
96
-
import openai
96
+
from openaiimport OpenAI
97
97
from nitric.resources import api
98
98
from nitric.application import Nitric
99
99
from nitric.context import HttpContext
@@ -104,23 +104,31 @@ Here we import `api` to create an API resource, `Nitric` to run the app, and `Ht
104
104
3.**Configure OpenAI API key:** It's best not to hardcode secrets. If you have your OpenAI API key, set it as an environment variable (e.g., create a .env file for the project containing `OPENAI_API_KEY=sk-...`). We can then configure the OpenAI client in code:
105
105
106
106
```python
107
-
openai.api_key = os.environ.get("OPENAI_API_KEY")
108
-
ifnot openai.api_key:
107
+
# Configure OpenAI API key from env
108
+
api_key = os.environ.get("OPENAI_API_KEY")
109
+
ifnot api_key:
109
110
raiseException("Please set the OPENAI_API_KEY environment variable")
110
111
```
111
112
112
113
This will fetch the API key from your environment. (If you prefer, Nitric also has a built-in **Secrets** feature to securely manage secrets, but for simplicity we'll stick to an env var here.)
113
114
114
-
4.**Define the API and route handler:** Now, use Nitric to create a POST route for summarization:
115
+
4.**Create the OpenAI client:** Now, use Nitric to create a POST route for summarization:
115
116
116
117
```python
117
-
# Create an API named 'main'
118
+
# Create OpenAI client
119
+
client = OpenAI(api_key=api_key)
120
+
```
121
+
122
+
5.**Define the API and route handler:** Now, use Nitric to create a POST route for summarization:
123
+
124
+
```python
125
+
# Create a Nitric API named 'main'
118
126
summarize_api = api("main")
119
127
120
128
@summarize_api.post("/summarize")
121
129
asyncdefsummarize_text(ctx: HttpContext) -> None:
122
130
# Extract input text from request (assuming JSON body with a 'text' field)
123
-
req_data = ctx.req.json# parses JSON body into a dict
131
+
req_data = ctx.req.json
124
132
ifnot req_data or'text'notin req_data:
125
133
ctx.res.status =400
126
134
ctx.res.body = {"error": "No text provided for summarization."}
0 commit comments