Skip to content

Commit

Permalink
fix server and client communication
Browse files Browse the repository at this point in the history
Signed-off-by: Swapnil Tripathi <[email protected]>
  • Loading branch information
swaptr committed Aug 14, 2024
1 parent 5883491 commit 1a8da59
Show file tree
Hide file tree
Showing 21 changed files with 396 additions and 206 deletions.
162 changes: 162 additions & 0 deletions src/core/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
39 changes: 20 additions & 19 deletions src/core/api.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
import os
import uvicorn
from utils import load_yaml_file
from main_router import main_router
from rag_router import rag_router
from api_router import api_router
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
# from routes.main import router as main_router
from routes.test import router as test_router

config_data = load_yaml_file("config.yaml")

app = FastAPI()

# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["*"],
)
def create_app() -> FastAPI:
# Create the FastAPI application
app = FastAPI()

# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["*"],
)

# app.include_router(main_router)
app.include_router(test_router)

# Include routers
app.include_router(main_router)
api_router.include_router(rag_router)
app.include_router(api_router,prefix="/api")
return app

uvicorn.run(app,host=config_data["host"],port=config_data["port"])
uvicorn.run(create_app,host=config_data["host"],port=config_data["port"])
58 changes: 0 additions & 58 deletions src/core/api_router.py

This file was deleted.

3 changes: 1 addition & 2 deletions src/core/main.py → src/core/conversation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import torch
from utils import load_yaml_file
from transformers import pipeline
from langchain_huggingface import HuggingFacePipeline
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
Expand All @@ -11,7 +10,7 @@
from tokenizer import initialize_tokenizer
from embeddings import embedding_function
from session_history import get_session_history

from utils import load_yaml_file

def get_conversation():
config_data = load_yaml_file("config.yaml")
Expand Down
8 changes: 0 additions & 8 deletions src/core/main_router.py

This file was deleted.

Empty file added src/core/routes/__init__.py
Empty file.
10 changes: 3 additions & 7 deletions src/core/rag_router.py → src/core/routes/main.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from main import get_conversation

from conversation import get_conversation

conversational_rag_chain = get_conversation()


# define the Query class that contains the question
class Query(BaseModel):
text: str


#Initialization of the router :
rag_router = APIRouter()

router = APIRouter()

# reply to POST requests: '{"text": "How to install Hyperledger fabric?"}'
@rag_router.post("/query")
@router.post("/query")
def answer(q: Query):
question = q.text
ai_msg_1 = conversational_rag_chain.invoke(
Expand Down
54 changes: 54 additions & 0 deletions src/core/routes/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from typing import List
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import uuid

router = APIRouter(
prefix="/api/test"
)

class ResponseMessage(BaseModel):
id: str
content: str
type: int

class ResponseConversation(BaseModel):
id: str
message: ResponseMessage

class RequestConversation(BaseModel):
id: str
content: str
type: int

responses = {
"What is Hyperledger Fabric?": "Hyperledger Fabric is an open-source blockchain framework designed for enterprise solutions. It allows for a modular architecture where different components like consensus mechanisms, membership services, and ledger storage can be tailored to specific needs.",
"How to install Hyperledger Fabric?": "To install Hyperledger Fabric, follow these steps:\n1. Install Docker and Docker Compose.\n2. Download the Hyperledger Fabric binaries and docker images using the Fabric CA and Fabric binaries script.\n3. Set up the environment variables for Fabric binaries.\n4. Verify the installation by running Fabric sample network scripts.",
"How to deploy a Hyperledger Fabric network?": "To deploy a Hyperledger Fabric network:\n1. Define the network topology and configuration files (e.g., 'configtx.yaml').\n2. Use the 'fabric-cli' or scripts to create channel artifacts.\n3. Launch the network by starting the necessary Docker containers and services using 'docker-compose' or Kubernetes.\n4. Instantiate and upgrade chaincode as needed.",
"How to run a Hyperledger Fabric network?": "To run a Hyperledger Fabric network:\n1. Start the network by running 'docker-compose up' or the appropriate command for your setup.\n2. Use the Fabric CLI tools or SDKs to interact with the network, including creating and joining channels, and submitting transactions.\n3. Monitor the network's health and performance using Fabric's built-in tools or external monitoring solutions.",
"How to ensure data privacy in Hyperledger Fabric?": "To ensure data privacy in Hyperledger Fabric:\n1. Use private data collections to restrict access to sensitive data.\n2. Implement access control policies and endorsement policies.\n3. Utilize encryption for data at rest and in transit.\n4. Regularly review and update security configurations and practices."
}

def get_hyperledger_fabric_answer(question):
return responses.get(question, "Question not found in the database.")

# TODO: Get all chats for a user in a paginated format
@router.post("/conversations")
def get_conversations(offset: int = 0, limit: int = 30, order: str = "updated") -> ResponseConversation:
pass

# TODO: Get a single chat for a user
@router.post("/conversation/{id}")
def post_conversation(id:str):
pass

@router.post("/conversation", response_model=ResponseConversation)
def post_conversation(item: RequestConversation) -> ResponseConversation:
return ResponseConversation(
id=item.id,
message=ResponseMessage(
content=get_hyperledger_fabric_answer(item.content),
type=1,
id=str(uuid.uuid4())
),
)
2 changes: 1 addition & 1 deletion src/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ def load_yaml_file(file_name):
file_path = os.path.join(base_path, file_name)

with open(file_path, 'r') as f:
return yaml.safe_load(f)
return yaml.safe_load(f)
Loading

0 comments on commit 1a8da59

Please sign in to comment.