cometapii commited on
Commit
ac35771
·
verified ·
1 Parent(s): ad068d5

Upload 2 files

Browse files
Files changed (2) hide show
  1. proxy.py +67 -0
  2. requirements (3).txt +3 -0
proxy.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request, HTTPException, Depends
2
+ from fastapi.responses import StreamingResponse
3
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
4
+ import httpx
5
+ import json
6
+
7
+ app = FastAPI()
8
+ security = HTTPBearer()
9
+
10
+ API_KEY = "connectkey"
11
+ OLLAMA_BASE = "http://localhost:11434"
12
+
13
+
14
+ def verify_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
15
+ if credentials.credentials != API_KEY:
16
+ raise HTTPException(status_code=401, detail="Invalid API key")
17
+ return credentials.credentials
18
+
19
+
20
+ @app.get("/api/version")
21
+ async def version(key: str = Depends(verify_key)):
22
+ async with httpx.AsyncClient() as client:
23
+ r = await client.get(f"{OLLAMA_BASE}/api/version")
24
+ return r.json()
25
+
26
+
27
+ @app.get("/api/tags")
28
+ async def tags(key: str = Depends(verify_key)):
29
+ async with httpx.AsyncClient() as client:
30
+ r = await client.get(f"{OLLAMA_BASE}/api/tags")
31
+ return r.json()
32
+
33
+
34
+ async def _stream(url: str, body: dict):
35
+ body["stream"] = True
36
+ async with httpx.AsyncClient(timeout=None) as client:
37
+ async with client.stream("POST", url, json=body) as r:
38
+ async for chunk in r.aiter_bytes():
39
+ yield chunk
40
+
41
+
42
+ @app.post("/api/generate")
43
+ async def generate(request: Request, key: str = Depends(verify_key)):
44
+ body = await request.json()
45
+ body["stream"] = True
46
+ return StreamingResponse(
47
+ _stream(f"{OLLAMA_BASE}/api/generate", body),
48
+ media_type="application/x-ndjson",
49
+ )
50
+
51
+
52
+ @app.post("/api/chat")
53
+ async def chat(request: Request, key: str = Depends(verify_key)):
54
+ body = await request.json()
55
+ body["stream"] = True
56
+ return StreamingResponse(
57
+ _stream(f"{OLLAMA_BASE}/api/chat", body),
58
+ media_type="application/x-ndjson",
59
+ )
60
+
61
+
62
+ @app.post("/api/embeddings")
63
+ async def embeddings(request: Request, key: str = Depends(verify_key)):
64
+ body = await request.json()
65
+ async with httpx.AsyncClient(timeout=None) as client:
66
+ r = await client.post(f"{OLLAMA_BASE}/api/embeddings", json=body)
67
+ return r.json()
requirements (3).txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ httpx