From 257ae8a2b479a2cfb7a768146c568987f836ef9f Mon Sep 17 00:00:00 2001 From: Vineeth Voruganti <13438633+VVoruganti@users.noreply.github.com> Date: Sun, 24 Mar 2024 18:47:02 -0700 Subject: [PATCH 1/4] Basic Auth Header validation --- api/.env.template | 4 ++++ api/docker-compose.yml.example | 1 + api/src/main.py | 37 ++++++++++++++++++++++++++++++++++ sdk/honcho/client.py | 34 ++++++++++++++++++++++--------- sdk/honcho/sync_client.py | 34 ++++++++++++++++++++++--------- sdk/poetry.lock | 17 +++++++++++++++- sdk/pyproject.toml | 1 + sdk/tests/test_sync.py | 8 ++++++-- 8 files changed, 115 insertions(+), 21 deletions(-) diff --git a/api/.env.template b/api/.env.template index 747fcaa..7940192 100644 --- a/api/.env.template +++ b/api/.env.template @@ -8,6 +8,10 @@ OPENAI_API_KEY= OPENTELEMETRY_ENABLED=false # Set to true to enable OpenTelemetry logging and tracing SENTRY_ENABLED=false # Set to true to enable Sentry logging and tracing +# Auth + +USE_AUTH_SERVICE=false + ## Sentry SENTRY_DSN= diff --git a/api/docker-compose.yml.example b/api/docker-compose.yml.example index 5be0752..7aabd04 100644 --- a/api/docker-compose.yml.example +++ b/api/docker-compose.yml.example @@ -25,6 +25,7 @@ services: - OTEL_RESOURCE_ATTRIBUTES= - DEBUG_LOG_OTEL_TO_PROVIDER=false - DEBUG_LOG_OTEL_TO_CONSOLE=true + - USE_AUTH_SERVICE=false database: image: ankane/pgvector restart: always diff --git a/api/src/main.py b/api/src/main.py index 8d7f9d6..167d003 100644 --- a/api/src/main.py +++ b/api/src/main.py @@ -9,6 +9,7 @@ from fastapi import ( APIRouter, FastAPI, + Request, ) from fastapi.responses import PlainTextResponse from fastapi_pagination import add_pagination @@ -43,6 +44,8 @@ from slowapi.middleware import SlowAPIMiddleware from slowapi.util import get_remote_address from starlette.exceptions import HTTPException as StarletteHTTPException +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.responses import Response from src.routers import ( apps, @@ -216,6 +219,40 @@ async def lifespan(app: FastAPI): add_pagination(app) +USE_AUTH_SERVICE = os.getenv("USE_AUTH_SERVICE", "False").lower() == "true" + + +# TODO make the API Token Validation Optional +class BearerTokenMiddleware(BaseHTTPMiddleware): + async def dispatch(self, request: Request, call_next): + authorization: Optional[str] = request.headers.get("Authorization") + if authorization: + scheme, _, token = authorization.partition(" ") + if scheme.lower() == "bearer": + if token == "default": + return await call_next(request) + + return Response(content="Invalid token.", status_code=400) + # Here you can add your token validation logic + # For example, checking token validity, expiration, etc. + # If the token is valid, you let the request pass through: + else: + # If the scheme is not Bearer, you might want to either + # 1. Reject the request + # 2. Ignore and proceed with the next middleware or the request + # This example demonstrates rejecting the request: + return Response( + content="Invalid authentication scheme.", status_code=400 + ) + + # If no Authorization header is present, you can choose to reject the request or let it pass + # This example demonstrates rejecting the request: + return Response(content="Authorization header missing.", status_code=401) + + +if USE_AUTH_SERVICE: + app.add_middleware(BearerTokenMiddleware) + @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request, exc): diff --git a/sdk/honcho/client.py b/sdk/honcho/client.py index 268ce54..23df5ce 100644 --- a/sdk/honcho/client.py +++ b/sdk/honcho/client.py @@ -6,10 +6,12 @@ import datetime import json +import os import uuid from typing import Optional import httpx +from dotenv import load_dotenv from .schemas import Document, Message, Metamessage @@ -345,7 +347,12 @@ async def next(self): class AsyncHoncho: """Honcho API Client Object""" - def __init__(self, app_name: str, base_url: str = "https://demo.honcho.dev"): + def __init__( + self, + app_name: str, + base_url: str = "https://demo.honcho.dev", + api_key: str = "default", + ): """Constructor for Client Args: @@ -353,21 +360,30 @@ def __init__(self, app_name: str, base_url: str = "https://demo.honcho.dev"): base_url (str): Base URL for the instance of the Honcho API defaults to https://demo.honcho.dev """ + load_dotenv() + token = os.getenv("HONCHO_API_KEY", api_key) self.server_url: str = base_url # Base URL for the instance of the Honcho API - self.client: httpx.AsyncClient = httpx.AsyncClient() + self.client: httpx.AsyncClient = httpx.AsyncClient( + headers={"Authorization": f"Bearer {token}"} + ) self.app_name: str = app_name # Representing name of the client application self.app_id: uuid.UUID self.metadata: dict async def initialize(self): """Run initialization tasks for the Honcho client""" - res = await self.client.get( - f"{self.server_url}/apps/get_or_create/{self.app_name}" - ) - res.raise_for_status() - data = res.json() - self.app_id: uuid.UUID = data["id"] - self.metadata: dict = data["metadata"] + try: + res = await self.client.get( + f"{self.server_url}/apps/get_or_create/{self.app_name}" + ) + res.raise_for_status() + data = res.json() + self.app_id: uuid.UUID = data["id"] + self.metadata: dict = data["metadata"] + except httpx.HTTPStatusError as e: + error_content = e.response.content + print(error_content) + raise Exception(error_content) from None async def init(self): """Synonym for initialize""" diff --git a/sdk/honcho/sync_client.py b/sdk/honcho/sync_client.py index 205df5b..a47d4da 100644 --- a/sdk/honcho/sync_client.py +++ b/sdk/honcho/sync_client.py @@ -6,10 +6,12 @@ import datetime import json +import os import uuid from typing import Optional import httpx +from dotenv import load_dotenv from .schemas import Document, Message, Metamessage @@ -345,7 +347,12 @@ def next(self): class Honcho: """Honcho API Client Object""" - def __init__(self, app_name: str, base_url: str = "https://demo.honcho.dev"): + def __init__( + self, + app_name: str, + base_url: str = "https://demo.honcho.dev", + api_key: str = "default", + ): """Constructor for Client Args: @@ -353,21 +360,30 @@ def __init__(self, app_name: str, base_url: str = "https://demo.honcho.dev"): base_url (str): Base URL for the instance of the Honcho API defaults to https://demo.honcho.dev """ + load_dotenv() + token = os.getenv("HONCHO_API_KEY", api_key) self.server_url: str = base_url # Base URL for the instance of the Honcho API - self.client: httpx.Client = httpx.Client() + self.client: httpx.Client = httpx.Client( + headers={"Authorization": f"Bearer {token}"} + ) self.app_name: str = app_name # Representing name of the client application self.app_id: uuid.UUID self.metadata: dict def initialize(self): """Run initialization tasks for the Honcho client""" - res = self.client.get( - f"{self.server_url}/apps/get_or_create/{self.app_name}" - ) - res.raise_for_status() - data = res.json() - self.app_id: uuid.UUID = data["id"] - self.metadata: dict = data["metadata"] + try: + res = self.client.get( + f"{self.server_url}/apps/get_or_create/{self.app_name}" + ) + res.raise_for_status() + data = res.json() + self.app_id: uuid.UUID = data["id"] + self.metadata: dict = data["metadata"] + except httpx.HTTPStatusError as e: + error_content = e.response.content + print(error_content) + raise Exception(error_content) from None def init(self): """Synonym for initialize""" diff --git a/sdk/poetry.lock b/sdk/poetry.lock index a2c2b7c..9dde738 100644 --- a/sdk/poetry.lock +++ b/sdk/poetry.lock @@ -668,6 +668,21 @@ pytest = ">=7.0.0,<9" docs = ["sphinx (>=5.3)", "sphinx-rtd-theme (>=1.0)"] testing = ["coverage (>=6.2)", "hypothesis (>=5.7.1)"] +[[package]] +name = "python-dotenv" +version = "1.0.1" +description = "Read key-value pairs from a .env file and set them as environment variables" +category = "main" +optional = false +python-versions = ">=3.8" +files = [ + {file = "python-dotenv-1.0.1.tar.gz", hash = "sha256:e324ee90a023d808f1959c46bcbc04446a10ced277783dc6ee09987c37ec10ca"}, + {file = "python_dotenv-1.0.1-py3-none-any.whl", hash = "sha256:f7b63ef50f1b690dddf550d03497b66d609393b40b564ed0d674909a68ebf16a"}, +] + +[package.extras] +cli = ["click (>=5.0)"] + [[package]] name = "requests" version = "2.31.0" @@ -968,4 +983,4 @@ testing = ["big-O", "jaraco.functools", "jaraco.itertools", "more-itertools", "p [metadata] lock-version = "2.0" python-versions = "^3.9" -content-hash = "3265d992168555f7d9d60f6f03c18dc515b32de3b975290158b086d82247fefc" +content-hash = "181a418ea413f687cc31004dc10c50b606aba04cd4073391270d11ab99430e56" diff --git a/sdk/pyproject.toml b/sdk/pyproject.toml index a4eb01c..5403326 100644 --- a/sdk/pyproject.toml +++ b/sdk/pyproject.toml @@ -10,6 +10,7 @@ packages = [{include = "honcho"}] [tool.poetry.dependencies] python = "^3.9" httpx = "^0.26.0" +python-dotenv = "^1.0.1" [tool.poetry.group.test.dependencies] pytest = "^7.4.4" diff --git a/sdk/tests/test_sync.py b/sdk/tests/test_sync.py index fc20b11..0077ff0 100644 --- a/sdk/tests/test_sync.py +++ b/sdk/tests/test_sync.py @@ -251,7 +251,9 @@ def test_paginated_messages(): created_session.create_message(is_user=False, content="Hi") page_size = 7 - get_message_response = created_session.get_messages(page=1, page_size=page_size) + get_message_response = created_session.get_messages( + page=1, page_size=page_size + ) assert get_message_response is not None assert isinstance(get_message_response, GetMessagePage) @@ -446,7 +448,9 @@ def test_collection_query(): collection = user.create_collection(col_name) # Add documents - doc1 = collection.create_document(content="The user loves puppies", metadata={}) + doc1 = collection.create_document( + content="The user loves puppies", metadata={} + ) doc2 = collection.create_document(content="The user owns a dog", metadata={}) doc3 = collection.create_document(content="The user is a doctor", metadata={}) From a3e9e56eb1ce4f0079d3186fe163537c05becfec Mon Sep 17 00:00:00 2001 From: Vineeth Voruganti <13438633+VVoruganti@users.noreply.github.com> Date: Mon, 25 Mar 2024 01:01:56 -0700 Subject: [PATCH 2/4] Basic Auth Service --- api/poetry.lock | 2 +- api/pyproject.toml | 1 + api/src/main.py | 42 +++++++++++++++++++++++++++++------------ api/src/routers/apps.py | 33 ++++++++++++++++++++++++++++---- 4 files changed, 61 insertions(+), 17 deletions(-) diff --git a/api/poetry.lock b/api/poetry.lock index 3275945..34d8d27 100644 --- a/api/poetry.lock +++ b/api/poetry.lock @@ -2696,4 +2696,4 @@ testing = ["big-O", "jaraco.functools", "jaraco.itertools", "more-itertools", "p [metadata] lock-version = "2.0" python-versions = "^3.8.1" -content-hash = "aa7928d0a259d20dd9805ab5b159eebb293eac0b2e46a40d5df55f797222a8f3" +content-hash = "d2b0e968cff39082c16334498a3571c90b10fec28268f89821f13e2764990393" diff --git a/api/pyproject.toml b/api/pyproject.toml index 17c6c60..3b1619f 100644 --- a/api/pyproject.toml +++ b/api/pyproject.toml @@ -27,6 +27,7 @@ realtime = "^1.0.2" psycopg = {extras = ["binary"], version = "^3.1.18"} langchain = "^0.1.12" langchain-openai = "^0.0.8" +httpx = "^0.27.0" [tool.ruff.lint] # from https://docs.astral.sh/ruff/linter/#rule-selection example diff --git a/api/src/main.py b/api/src/main.py index 167d003..08e567f 100644 --- a/api/src/main.py +++ b/api/src/main.py @@ -1,10 +1,12 @@ import json import logging import os +import re import uuid from contextlib import asynccontextmanager from typing import Optional, Sequence +import httpx import sentry_sdk from fastapi import ( APIRouter, @@ -220,33 +222,49 @@ async def lifespan(app: FastAPI): add_pagination(app) USE_AUTH_SERVICE = os.getenv("USE_AUTH_SERVICE", "False").lower() == "true" +AUTH_SERVICE_URL = os.getenv("AUTH_SERVICE_URL", "http://localhost:8001") -# TODO make the API Token Validation Optional class BearerTokenMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): authorization: Optional[str] = request.headers.get("Authorization") if authorization: scheme, _, token = authorization.partition(" ") - if scheme.lower() == "bearer": - if token == "default": + if scheme.lower() == "bearer" and token: + id_pattern = r"\/apps\/([^\/]+)" + name_pattern = r"\/apps\/name\/([^\/]+)|\/apps\/get_or_create\/([^\/]+)" + match_id = re.search(id_pattern, request.url.path) + match_name = re.search(name_pattern, request.url.path) + payload = {"token": token} + if match_name: + payload["name"] = match_name.group(1) + elif match_id: + payload["app_id"] = match_id.group(1) + + res = httpx.get( + f"{AUTH_SERVICE_URL}/validate", + params=payload, + ) + data = res.json() + if ( + data["app_id"] or data["name"] + ): # Anything that checks app_id if True is valid return await call_next(request) + if data["token"]: + check_pattern = r"^\/apps$|^\/apps\/get_or_create" + match = re.search(check_pattern, request.url.path) + if match: + return await call_next(request) return Response(content="Invalid token.", status_code=400) - # Here you can add your token validation logic - # For example, checking token validity, expiration, etc. - # If the token is valid, you let the request pass through: else: - # If the scheme is not Bearer, you might want to either - # 1. Reject the request - # 2. Ignore and proceed with the next middleware or the request - # This example demonstrates rejecting the request: return Response( content="Invalid authentication scheme.", status_code=400 ) - # If no Authorization header is present, you can choose to reject the request or let it pass - # This example demonstrates rejecting the request: + exclude_paths = ["/docs", "/redoc", "/openapi.json"] + if request.url.path in exclude_paths: + return await call_next(request) return Response(content="Authorization header missing.", status_code=401) diff --git a/api/src/routers/apps.py b/api/src/routers/apps.py index 648c28b..d45f72f 100644 --- a/api/src/routers/apps.py +++ b/api/src/routers/apps.py @@ -1,5 +1,8 @@ +import os import uuid +from typing import Optional +import httpx from fastapi import APIRouter, HTTPException, Request from sqlalchemy.ext.asyncio import AsyncSession @@ -57,8 +60,30 @@ async def create_app(request: Request, app: schemas.AppCreate, db=db): schemas.App: Created App object """ - - return await crud.create_app(db, app=app) + USE_AUTH_SERVICE = os.getenv("USE_AUTH_SERVICE", "False").lower() == "true" + if USE_AUTH_SERVICE: + AUTH_SERVICE_URL = os.getenv("AUTH_SERVICE_URL", "http://localhost:8001") + authorization: Optional[str] = request.headers.get("Authorization") + if authorization: + scheme, _, token = authorization.partition(" ") + if token is not None: + honcho_app = await crud.create_app(db, app=app) + if token == "default": + return honcho_app + res = httpx.put( + f"{AUTH_SERVICE_URL}/organizations", + json={ + "id": str(honcho_app.id), + "name": honcho_app.name, + "token": token, + }, + ) + data = res.json() + if data: + return honcho_app + else: + honcho_app = await crud.create_app(db, app=app) + return honcho_app @router.get("/get_or_create/{name}", response_model=schemas.App) @@ -73,9 +98,9 @@ async def get_or_create_app(request: Request, name: str, db=db): """ print("name", name) - app = await crud.get_app_by_name(db, name=name) + app = await crud.get_app_by_name(db=db, name=name) if app is None: - app = await crud.create_app(db, app=schemas.AppCreate(name=name)) + app = await create_app(request=request, db=db, app=schemas.AppCreate(name=name)) return app From ed7ac7d61055a7ea721bec3fce23447acb2aab7d Mon Sep 17 00:00:00 2001 From: Vineeth Voruganti <13438633+VVoruganti@users.noreply.github.com> Date: Mon, 25 Mar 2024 15:48:58 -0700 Subject: [PATCH 3/4] Deriver reliability and default auth revoke --- api/fly.toml | 15 --- api/src/deriver.py | 21 ++++- api/src/harvester.py | 203 ---------------------------------------- api/src/routers/apps.py | 4 +- 4 files changed, 22 insertions(+), 221 deletions(-) delete mode 100644 api/src/harvester.py diff --git a/api/fly.toml b/api/fly.toml index cf47e59..9f884c8 100644 --- a/api/fly.toml +++ b/api/fly.toml @@ -7,25 +7,10 @@ app = "honcho" kill_signal = "SIGINT" kill_timeout = "5s" -[experimental] - auto_rollback = true - -[build] - [processes] api = "python -m uvicorn src.main:app --host 0.0.0.0 --port 8000" deriver = "python -m src.deriver" -[[services]] - auto_stop_machines = false - auto_start_machines = true - min_machines_running = 1 - processes = ["deriver"] - protocol = "tcp" - [services.concurrency] - hard_limit = 250 - soft_limit = 200 - [http_service] internal_port = 8000 auto_stop_machines = false diff --git a/api/src/deriver.py b/api/src/deriver.py index 6fbb760..1149708 100644 --- a/api/src/deriver.py +++ b/api/src/deriver.py @@ -1,5 +1,6 @@ import asyncio import os +import time import uuid from typing import List @@ -15,6 +16,7 @@ from realtime.connection import Socket from sqlalchemy import select from sqlalchemy.orm import selectinload +from websockets.exceptions import ConnectionClosedError from . import crud, models, schemas from .db import SessionLocal @@ -32,7 +34,7 @@ SUPABASE_ID = os.getenv("SUPABASE_ID") SUPABASE_API_KEY = os.getenv("SUPABASE_API_KEY") -llm = ChatOpenAI(model_name="gpt-4") +llm = ChatOpenAI(model_name="gpt-3.5") output_parser = NumberedListOutputParser() SYSTEM_DERIVE_FACTS = load_prompt( @@ -200,9 +202,26 @@ async def check_dups( return new_facts +# def listen_to_websocket(url): +# while True: +# try: +# s = Socket(url) +# s.connect() +# channel = s.set_channel("realtime:public:messages") +# channel.join().on( +# "INSERT", lambda payload: asyncio.create_task(callback(payload)) +# ) + +# s.listen() +# except ConnectionClosedError: +# print("Connection closed, attempting to reconnect...") +# time.sleep(5) + + if __name__ == "__main__": URL = f"wss://{SUPABASE_ID}.supabase.co/realtime/v1/websocket?apikey={SUPABASE_API_KEY}&vsn=1.0.0" # URL = f"ws://127.0.0.1:54321/realtime/v1/websocket?apikey={SUPABASE_API_KEY}" # For local Supabase + # listen_to_websocket(URL) s = Socket(URL) s.connect() diff --git a/api/src/harvester.py b/api/src/harvester.py deleted file mode 100644 index 7be78bc..0000000 --- a/api/src/harvester.py +++ /dev/null @@ -1,203 +0,0 @@ -import asyncio -import os -import uuid -from typing import List - -from dotenv import load_dotenv -from langchain_core.output_parsers import NumberedListOutputParser -from langchain_core.prompts import ( - ChatPromptTemplate, - SystemMessagePromptTemplate, - load_prompt, -) -from langchain_openai import ChatOpenAI -from realtime.connection import Socket -from sqlalchemy import select -from sqlalchemy.orm import selectinload - -from . import crud, models, schemas -from .db import SessionLocal - -load_dotenv() - -SUPABASE_ID = os.getenv("SUPABASE_ID") -SUPABASE_API_KEY = os.getenv("SUPABASE_API_KEY") - -llm = ChatOpenAI(model_name="gpt-4") -output_parser = NumberedListOutputParser() - -SYSTEM_DERIVE_FACTS = load_prompt( - os.path.join(os.path.dirname(__file__), "prompts/derive_facts.yaml") -) -SYSTEM_CHECK_DUPS = load_prompt( - os.path.join(os.path.dirname(__file__), "prompts/check_dup_facts.yaml") -) - -system_check_dups: SystemMessagePromptTemplate = SystemMessagePromptTemplate( - prompt=SYSTEM_CHECK_DUPS -) - -system_derive_facts: SystemMessagePromptTemplate = SystemMessagePromptTemplate( - prompt=SYSTEM_DERIVE_FACTS -) - - -async def callback(payload): - # print(payload["record"]["is_user"]) - # print(type(payload["record"]["is_user"])) - if payload["record"]["is_user"]: # Check if the message is from a user - session_id = payload["record"]["session_id"] - message_id = payload["record"]["id"] - content = payload["record"]["content"] - - # Example of querying for a user_id based on session_id, adjust according to your schema - session: models.Session - user_id: uuid.UUID - app_id: uuid.UUID - async with SessionLocal() as db: - stmt = ( - select(models.Session) - .join(models.Session.messages) - .where(models.Message.id == message_id) - .where(models.Session.id == session_id) - .options(selectinload(models.Session.user)) - ) - result = await db.execute(stmt) - session = result.scalars().one() - user = session.user - user_id = user.id - app_id = user.app_id - collection: models.Collection - async with SessionLocal() as db: - collection = await crud.get_collection_by_name( - db, app_id, user_id, "honcho" - ) - if collection is None: - collection_create = schemas.CollectionCreate(name="honcho", metadata={}) - collection = await crud.create_collection( - db, - collection=collection_create, - app_id=app_id, - user_id=user_id, - ) - collection_id = collection.id - await process_user_message( - content, app_id, user_id, session_id, collection_id, message_id - ) - return - - -async def process_user_message( - content: str, - app_id: uuid.UUID, - user_id: uuid.UUID, - session_id: uuid.UUID, - collection_id: uuid.UUID, - message_id: uuid.UUID, -): - # TODO get messages for the session - async with SessionLocal() as db: - messages_stmt = await crud.get_messages( - db=db, app_id=app_id, user_id=user_id, session_id=session_id, reverse=True - ) - messages_stmt = messages_stmt.limit(10) - response = await db.execute(messages_stmt) - messages = response.scalars().all() - messages = messages[::-1] - contents = [m.content for m in messages] - # print(contents) - - facts = await derive_facts(messages, content) - print("===================") - print(f"DERIVED FACTS: {facts}") - print("===================") - new_facts = await check_dups(app_id, user_id, collection_id, facts) - - print("===================") - print(f"CHECKED FOR DUPLICATES: {new_facts}") - print("===================") - - for fact in new_facts: - create_document = schemas.DocumentCreate(content=fact) - async with SessionLocal() as db: - doc = await crud.create_document( - db, - document=create_document, - app_id=app_id, - user_id=user_id, - collection_id=collection_id, - ) - print(f"Returned Document: {doc}") - # doc = crud.create_document(content=fact) - # for fact in new_facts: - # session.create_metamessage( - # message=user_message, metamessage_type="fact", content=fact - # ) - # print(f"Created fact: {fact}") - - -async def derive_facts(chat_history, input: str) -> List[str]: - """Derive facts from the user input""" - - fact_derivation = ChatPromptTemplate.from_messages([system_derive_facts]) - chain = fact_derivation | llm - response = await chain.ainvoke( - { - "chat_history": [ - ( - "user: " + message.content - if message.is_user - else "ai: " + message.content - ) - for message in chat_history - ], - "user_input": input, - } - ) - facts = output_parser.parse(response.content) - - return facts - - -async def check_dups( - app_id: uuid.UUID, user_id: uuid.UUID, collection_id: uuid.UUID, facts: List[str] -): - """Check that we're not storing duplicate facts""" - - check_duplication = ChatPromptTemplate.from_messages([system_check_dups]) - query = " ".join(facts) - result = None - async with SessionLocal() as db: - result = await crud.query_documents( - db=db, - app_id=app_id, - user_id=user_id, - collection_id=collection_id, - query=query, - top_k=10, - ) - # result = collection.query(query=query, top_k=10) - existing_facts = [document.content for document in result] - print("===================") - print(f"Existing Facts {existing_facts}") - print("===================") - if len(existing_facts) == 0: - return facts - chain = check_duplication | llm - response = await chain.ainvoke({"existing_facts": existing_facts, "facts": facts}) - new_facts = output_parser.parse(response.content) - print("===================") - print(f"New Facts {facts}") - print("===================") - return new_facts - - -if __name__ == "__main__": - URL = f"wss://{SUPABASE_ID}.supabase.co/realtime/v1/websocket?apikey={SUPABASE_API_KEY}&vsn=1.0.0" - # URL = f"ws://127.0.0.1:54321/realtime/v1/websocket?apikey={SUPABASE_API_KEY}" # For local Supabase - s = Socket(URL) - s.connect() - - channel = s.set_channel("realtime:public:messages") - channel.join().on("INSERT", lambda payload: asyncio.create_task(callback(payload))) - s.listen() diff --git a/api/src/routers/apps.py b/api/src/routers/apps.py index d45f72f..e9d3df6 100644 --- a/api/src/routers/apps.py +++ b/api/src/routers/apps.py @@ -68,8 +68,8 @@ async def create_app(request: Request, app: schemas.AppCreate, db=db): scheme, _, token = authorization.partition(" ") if token is not None: honcho_app = await crud.create_app(db, app=app) - if token == "default": - return honcho_app + # if token == "default": + # return honcho_app res = httpx.put( f"{AUTH_SERVICE_URL}/organizations", json={ From bab7e0e6940cf5380cd7e51bf488599fd83f4dba Mon Sep 17 00:00:00 2001 From: Vineeth Voruganti <13438633+VVoruganti@users.noreply.github.com> Date: Mon, 25 Mar 2024 15:55:31 -0700 Subject: [PATCH 4/4] .env.template --- api/.env.template | 1 + 1 file changed, 1 insertion(+) diff --git a/api/.env.template b/api/.env.template index 7940192..4cf2a18 100644 --- a/api/.env.template +++ b/api/.env.template @@ -11,6 +11,7 @@ SENTRY_ENABLED=false # Set to true to enable Sentry logging and tracing # Auth USE_AUTH_SERVICE=false +AUTH_SERVICE_URL=http://localhost:8001 ## Sentry SENTRY_DSN=