-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdem1.py
88 lines (66 loc) · 2.36 KB
/
dem1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Response, Request
from langchain import ConversationChain
from langchain.chat_models import ChatOpenAI
import uvicorn
import sqlite3
import secrets
from lanarky import LangchainRouter
load_dotenv()
app = FastAPI()
# Store the secrets in memory
secrets_set = set()
def generate_secret():
# Generate a random secret using the secrets module
return secrets.token_hex(16)
# check preimage
@app.post("/preimages")
async def create_preimage(preimage: str, response: Response):
# Generate a single-use secret/token
secret = generate_secret()
# Set the secret as a cookie
response.set_cookie(key="secret", value=secret, max_age=3600)
# Add the secret to the set of secrets in memory
secrets_set.add(secret)
# Connect to the database
conn = sqlite3.connect("preim.db")
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
# Create the preimages table if not yet exisits
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS preimages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
preimage TEXT NOT NULL
)
"""
)
# Check if the preimage already exists
cursor.execute("SELECT * FROM preimages WHERE preimage=?", (preimage,))
existing_preimage = cursor.fetchone()
if existing_preimage:
conn.close()
raise HTTPException(status_code=409, detail="Preimage already exists")
# Count the total number of records in the table
cursor.execute("SELECT COUNT(*) FROM preimages")
total_records = cursor.fetchone()[0]
if total_records >= 999999:
# Delete the oldest record
cursor.execute("DELETE FROM preimages WHERE id = (SELECT MIN(id) FROM preimages)")
# Insert the new preimage into the database
cursor.execute("INSERT INTO preimages (preimage) VALUES (?)", (preimage,))
# Commit the changes and close the connection
conn.commit()
conn.close()
# preimage is good and not already in DB - return ok!
return
# Make the query/queries
langchain_router = LangchainRouter(
langchain_url="/chat",
langchain_object=ConversationChain(llm=ChatOpenAI(temperature=0), verbose=True),
streaming_mode=0,
)
app.include_router(langchain_router)
# main
if __name__ == "__main__":
uvicorn.run("dem1:app", port=5000, log_level="debug")