Quardo commited on
Commit
97339e2
1 Parent(s): 24c061e

Updated space.

Browse files
Files changed (1) hide show
  1. index.html +166 -53
index.html CHANGED
@@ -10,7 +10,7 @@
10
  <meta property="og:title" content="Quardo's OpenAI proxy">
11
  <meta property="og:description" content="Documentation for Quardo's OpenAI proxy">
12
  <meta property="og:type" content="website">
13
- <meta property="og:url" content="https://chat.cow.rip/api/v1/docs">
14
  <meta property="og:image" content="https://tenor.com/view/cat-cat-e-cat-meme-cat-face-gif-23642589">
15
  <meta name="twitter:card" content="summary_large_image">
16
  <meta name="twitter:title" content="Quardo's OpenAI proxy">
@@ -126,65 +126,179 @@
126
  <li>Privacy: Please avoid sharing any personal information.</li>
127
  </ul>
128
  <p>By continuing to use our API, you explicitly consent to the collection, use, and potential sharing of your data as described above. If you disagree with our data collection, usage, and sharing practices, we advise you not to use our API.</p>
129
- <textarea id="example1" name="example1"># Example 1: Using OpenAI Python client
130
- from openai import OpenAI
 
 
131
 
132
- client = OpenAI(
133
- # Or use the `OPENAI_BASE_URL` env var
134
- base_url="https://cow.rip/api/v1",
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- # You can get a key by logging in at https://cow.rip/api/v1/oauth/hf
137
- api_key="..."
138
- )
139
 
140
- completion = client.ChatCompletion.acreate(
141
- model="gpt-4o-mini",
142
- messages=[
143
- {
144
- "role": "user",
145
- "content": "Say this is a test",
146
- }
147
- ],
148
- )
149
 
150
- print(completion.choices[0].message.content)</textarea>
151
- <hr/>
152
- <textarea id="example2" name="example2"># Example 2: Using OpenAI Python client with different syntax
153
- import openai
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
- openai.api_key = '...' # You can get a key by logging in at https://cow.rip/api/v1/oauth/hf
156
- openai.base_url = "https://cow.rip/api/v1" # Or use the `OPENAI_BASE_URL` env var
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
- completion = openai.ChatCompletion.acreate(
159
- model="gpt-4o-mini",
160
- messages=[
161
- {
162
- "role": "user",
163
- "content": "Say this is a test",
164
- },
165
- ],
166
- )
167
 
168
- print(completion.choices[0].message.content)</textarea>
 
169
  <hr/>
170
- <textarea id="example3" name="example3">// For Node.js:
171
- const openai = new (require('openai')).OpenAI({
172
- baseURL: "https://cow.rip/api/v1", // Or use the `OPENAI_BASE_URL` env var
173
- apiKey: "..." // You can get a key by logging in at https://cow.rip/api/v1/oauth/hf
174
- });
175
- (async()=>{
176
- var completion = await openai.chat.completions.create({
177
- model: "gpt-4o-mini",
178
- messages=[
179
- {
180
- "role": "user",
181
- "content": "Say this is a test",
182
- }
183
- ]
184
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
- console.log(completion.choices[0].message.content)
187
- })()
188
  </textarea>
189
  <hr/>
190
  <div>
@@ -197,8 +311,7 @@ const openai = new (require('openai')).OpenAI({
197
  </div>
198
  <script>
199
  CodeMirror.fromTextArea(document.getElementById("example1"), { lineNumbers: true, mode: "python", theme: "monokai", readOnly: true });
200
- CodeMirror.fromTextArea(document.getElementById("example2"), { lineNumbers: true, mode: "python", theme: "monokai", readOnly: true });
201
- CodeMirror.fromTextArea(document.getElementById("example3"), { lineNumbers: true, mode: "javascript", theme: "monokai", readOnly: true });
202
  </script>
203
  </body>
204
  </html>
 
10
  <meta property="og:title" content="Quardo's OpenAI proxy">
11
  <meta property="og:description" content="Documentation for Quardo's OpenAI proxy">
12
  <meta property="og:type" content="website">
13
+ <meta property="og:url" content="https://https://quardo-gpt-4o-mini.hf.space/api/v1/docs">
14
  <meta property="og:image" content="https://tenor.com/view/cat-cat-e-cat-meme-cat-face-gif-23642589">
15
  <meta name="twitter:card" content="summary_large_image">
16
  <meta name="twitter:title" content="Quardo's OpenAI proxy">
 
126
  <li>Privacy: Please avoid sharing any personal information.</li>
127
  </ul>
128
  <p>By continuing to use our API, you explicitly consent to the collection, use, and potential sharing of your data as described above. If you disagree with our data collection, usage, and sharing practices, we advise you not to use our API.</p>
129
+ <textarea id="example1" name="example1"># For Python3:
130
+ import asyncio
131
+ import aiohttp
132
+ import json
133
 
134
+ base_url = "https://cow.rip/api/v1"
135
+ key = "sk-quardo-..." # You can get a key by logging in at https://cow.rip/api/v1/oauth/hf
136
+ params = {
137
+ # Model to use for the chat. You can view the models at https://cow.rip/api/v1/models in your browser
138
+ 'model': "gpt-4o-mini",
139
+
140
+ # List of messages to send to the API. Each message should be a dictionary with 'role' and 'content'.
141
+ 'messages': [
142
+ {'role': 'user', 'content': 'Hello!'}
143
+ ],
144
+
145
+ # Boolean to enable or disable streaming of the response.
146
+ 'stream': True
147
+
148
+ # For any other paramater please take a look at https://platform.openai.com/docs/api-reference/chat
149
+ }
150
 
151
+ async def chat(params):
152
+ """
153
+ Function to interact with the chat API.
154
 
155
+ Args:
156
+ params (dict): Parameters to be sent to the API. Must include 'model', 'messages', and optionally any other paramaters that OpenAI supports (https://platform.openai.com/docs/api-reference/chat).
 
 
 
 
 
 
 
157
 
158
+ Yields:
159
+ str: The content of the response message from the API.
160
+ """
161
+ async with aiohttp.ClientSession() as session:
162
+ async with session.post(
163
+ f'{base_url}/chat/completions',
164
+ headers={
165
+ 'Content-Type': 'application/json',
166
+ 'Authorization': f'Bearer {key}'
167
+ },
168
+ json=params,
169
+ timeout=10 # Timeout for the request in seconds
170
+ ) as response:
171
+ # Check if the response has a content body
172
+ if not response.content:
173
+ raise Exception('No response body received')
174
 
175
+ # If streaming is enabled, process the response line by line
176
+ if params.get('stream', False):
177
+ async for line in response.content:
178
+ data = line.decode('utf-8').strip()
179
+ if data.startswith("data: ") and (msg := data[6:]) != "[DONE]":
180
+ try:
181
+ parsed = json.loads(msg)
182
+ if 'choices' in parsed:
183
+ choice = parsed['choices'][0]
184
+ if 'delta' in choice and 'content' in choice['delta']:
185
+ yield choice['delta']['content']
186
+ except json.JSONDecodeError as e:
187
+ print(f"Failed to parse JSON event: {e}")
188
+ else:
189
+ # If streaming is not enabled, process the entire response at once
190
+ result = await response.json()
191
+ if 'choices' in result:
192
+ choice = result['choices'][0]
193
+ if 'message' in choice:
194
+ yield choice['message']['content']
195
+ else:
196
+ yield "{Invalid response received}"
197
+ else:
198
+ yield "{Invalid response received}"
199
 
200
+ async def main():
201
+ """
202
+ Main function to initiate the chat interaction.
203
+
204
+ This function sets up the parameters for the chat API call and processes the response.
205
+ """
206
+ async for msg in chat(params):
207
+ print(msg, end="", flush=True)
208
+ print()
209
 
210
+ if __name__ == "__main__":
211
+ asyncio.run(main())</textarea>
212
  <hr/>
213
+ <textarea id="example2" name="example2">// For Node.JS:
214
+ const baseUrl = "https://cow.rip/api/v1";
215
+ const key = "sk-quardo-..."; // You can get a key by logging in at https://cow.rip/api/v1/oauth/hf
216
+ const params = {
217
+ // Model to use for the chat. You can view the models at https://cow.rip/api/v1/models in your browser or use the models() function.
218
+ model: "gpt-4o-mini",
219
+
220
+ // List of messages to send to the API. Each message should be a dictionary with 'role' and 'content'.
221
+ messages: [
222
+ { role: "user", content: "Hello!" }
223
+ ],
224
+
225
+ // Boolean to enable or disable streaming of the response.
226
+ stream: true
227
+
228
+ // For any other parameter please take a look at https://platform.openai.com/docs/api-reference/chat
229
+ };
230
+
231
+ /**
232
+ * Function to interact with the chat API.
233
+ *
234
+ * @param {Object} params - Parameters to be sent to the API. Must include 'model', 'messages', and optionally any other paramaters that OpenAI supports (https://platform.openai.com/docs/api-reference/chat).
235
+ * @yields {string} - The content of the response message from the API.
236
+ */
237
+ async function* chat(params) {
238
+ const response = await fetch(`${baseUrl}/chat/completions`, {
239
+ method: 'POST',
240
+ headers: {
241
+ 'Content-Type': 'application/json',
242
+ 'Authorization': `Bearer ${key}`
243
+ },
244
+ body: JSON.stringify(params)
245
+ });
246
+
247
+ if (!response.body) {
248
+ throw new Error('No response body received');
249
+ }
250
+
251
+ if (params.stream) {
252
+ const reader = response.body.getReader();
253
+ let done, value, buffer = '';
254
+
255
+ while (!done) {
256
+ ({ value, done } = await reader.read());
257
+ if (value) {
258
+ buffer += new TextDecoder().decode(value);
259
+ let boundaryIndex;
260
+ while ((boundaryIndex = buffer.indexOf("\n\n")) !== -1) {
261
+ const chunk = buffer.slice(0, boundaryIndex + 2);
262
+ buffer = buffer.slice(boundaryIndex + 2);
263
+ if (chunk.trim().startsWith("data: ")) {
264
+ const data = chunk.substring(6).trim();
265
+ if (data !== "[DONE]") {
266
+ try {
267
+ const parsed = JSON.parse(data);
268
+ if (parsed.choices && parsed.choices[0] && parsed.choices[0].delta) {
269
+ yield parsed.choices[0].delta.content || "";
270
+ }
271
+ } catch (e) {
272
+ console.error(`Failed to parse JSON event: ${e.message}`);
273
+ }
274
+ }
275
+ }
276
+ }
277
+ }
278
+ }
279
+ } else {
280
+ const result = await response.json();
281
+ if (result.choices && result.choices[0] && result.choices[0].message) {
282
+ yield result.choices[0].message.content || "{Invalid response received}";
283
+ } else {
284
+ yield "{Invalid response received}";
285
+ }
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Main function to initiate the chat interaction.
291
+ *
292
+ * This function sets up the parameters for the chat API call and processes the response.
293
+ */
294
+ async function main() {
295
+ for await (const msg of chat(params)) {
296
+ process.stdout.write(msg);
297
+ }
298
+ process.stdout.write("\n");
299
+ }
300
 
301
+ main().catch(console.error);
 
302
  </textarea>
303
  <hr/>
304
  <div>
 
311
  </div>
312
  <script>
313
  CodeMirror.fromTextArea(document.getElementById("example1"), { lineNumbers: true, mode: "python", theme: "monokai", readOnly: true });
314
+ CodeMirror.fromTextArea(document.getElementById("example2"), { lineNumbers: true, mode: "javascript", theme: "monokai", readOnly: true });
 
315
  </script>
316
  </body>
317
  </html>