Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 7 additions & 39 deletions src/nylas/router.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
"""Nylas router module."""

from apscheduler.schedulers.background import (
BackgroundScheduler,
)
from asyncio import (
ensure_future,
)
from fastapi import (
APIRouter,
Depends,
Expand Down Expand Up @@ -73,33 +67,7 @@ async def exchange_code_for_token(
Exchanges an authorization code for an access token.
"""
try:
from src.main import (
code_app,
)

scheduler = BackgroundScheduler()
response = await nylas_crud.login_user(request.token, session)

if response:
# send a welcome email in the background
ensure_future(
nylas_crud.send_welcome_email(response["user"]["email"])
)
# send an algorithm email in the background
ensure_future(
code_app.state.openai.async_send_algorithm_email(
response["user"]["email"], "python"
)
)
scheduler.add_job(
code_app.state.openai.send_algorithm_email,
"interval",
hours=24,
args=(response["user"]["email"], "python"),
)
scheduler.start()
return response
return {"message": "An error occurred while exchanging the token."}
return await nylas_crud.login_user(request.token, session)
except Exception as e:
print(e)
return {"message": "An error occurred while exchanging the token."}
Expand Down Expand Up @@ -134,7 +102,7 @@ async def fetch_emails(
status_code=200,
name="nylas:mail",
)
def get_message(
async def get_message(
mailId: str,
current_user: users_schemas.UserObjectSchema = Depends(
dependencies.get_current_user
Expand All @@ -157,7 +125,7 @@ def get_message(
status_code=200,
name="nylas:send-email",
)
def send_email(
async def send_email(
request_body: nylas_schemas.SendEmailSchema,
current_user: users_schemas.UserObjectSchema = Depends(
dependencies.get_current_user
Expand Down Expand Up @@ -236,7 +204,7 @@ async def delete_label(
status_code=200,
name="nylas:send-email",
)
def create_label(
async def create_label(
request_body: nylas_schemas.CreateLabelSchema,
current_user: users_schemas.UserObjectSchema = Depends(
dependencies.get_current_user
Expand All @@ -262,7 +230,7 @@ def create_label(
status_code=200,
name="nylas:folders",
)
def update_folder(
async def update_folder(
items: List[str],
current_user: users_schemas.UserObjectSchema = Depends(
dependencies.get_current_user
Expand All @@ -282,7 +250,7 @@ def update_folder(
status_code=200,
name="nylas:reply-email",
)
def reply_email(
async def reply_email(
request_body: nylas_schemas.ReplyEmailSchema,
current_user: users_schemas.UserObjectSchema = Depends(
dependencies.get_current_user
Expand Down Expand Up @@ -316,7 +284,7 @@ def reply_email(
status_code=200,
name="nylas:contacts",
)
def read_contacts(
async def read_contacts(
current_user: users_schemas.UserObjectSchema = Depends(
dependencies.get_current_user
),
Expand Down
2 changes: 1 addition & 1 deletion src/users/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ async def update_user_info(
{
"full_name": personal_info.full_name,
"bio": personal_info.bio,
"proramming_language": personal_info.proramming_language,
"programming_language": personal_info.programming_language,
"modified_date": datetime.utcnow(),
}
)
Expand Down
62 changes: 62 additions & 0 deletions src/users/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@

"""

from apscheduler.schedulers.background import (
BackgroundScheduler,
)
from asyncio import (
ensure_future,
)
from deta import Deta
from fastapi import (
APIRouter,
Expand All @@ -43,6 +49,9 @@
from src.config import (
settings,
)
from src.nylas import (
crud as nylas_crud,
)
from src.users import (
crud as users_crud,
schemas as users_schemas,
Expand Down Expand Up @@ -160,3 +169,56 @@ async def update_personal_information(
}
except Exception:
return {"status_code": 400, "message": "Something went wrong!"}


@router.put(
"/user/language",
response_model=Dict[str, Any],
status_code=200,
name="user:language",
)
async def update_language(
request_body: users_schemas.LanguageSchema,
current_user: users_schemas.UserObjectSchema = Depends(
dependencies.get_current_user
),
session: AIOSession = Depends(dependencies.get_db_transactional_session),
) -> Dict[str, Any]:
"""
Set the programming language for a specific user using their access token.
"""
try:
from src.main import (
code_app,
)

scheduler = BackgroundScheduler()
user_info = users_schemas.PersonalInfo(
full_name=current_user.full_name,
bio=current_user.bio,
programming_language=request_body.language,
)
await users_crud.update_user_info(user_info, current_user, session)
# send a welcome email in the background
ensure_future(nylas_crud.send_welcome_email(current_user.email))
# send an algorithm email in the background
ensure_future(
code_app.state.openai.async_send_algorithm_email(
current_user.email, request_body.language
)
)
# send an algorithm email every 24 hours
scheduler.add_job(
code_app.state.openai.send_algorithm_email,
"interval",
hours=24,
args=(current_user.email, request_body.language),
)
scheduler.start()
return {
"status_code": 200,
"message": "Your programming language has been updated successfully!",
}
except Exception as e:
print(e)
return {"status_code": 400, "message": "Something went wrong!"}
11 changes: 11 additions & 0 deletions src/users/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,14 @@ class LogoutSchema(BaseModel):
"""

token: str = Field(..., example="123456789", description="User's token.")


class LanguageSchema(BaseModel):
"""Languge Schema

A Pydantic class that defines the language schema for updating the programming language for a user.
"""

language: str = Field(
..., example="python", description="User's programming language."
)
58 changes: 35 additions & 23 deletions src/utils/openai_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class OpenAIAPI:
api_token: str
model: str = "gpt-3.5-turbo"
temperature: float = 0
max_tokens: int = 128
max_tokens: int = 512
top_p: float = 1
frequency_penalty: float = 0
presence_penalty: float = 0.6
Expand All @@ -56,31 +56,43 @@ def __post_init__(self) -> None:
self.prompt = """ # noqa: E501
**Task Prompt:**

As an algorithm expert, your task is to generate a comprehensive algorithm tutorial. The tutorial should cover a specific algorithmic topic of your choice (e.g., sorting algorithms, search algorithms, dynamic programming, graph algorithms, etc.) and provide in-depth explanations, code samples in {programming_language}, and relevant external links for further reading.
As an algorithm expert, your mission is to craft a comprehensive algorithm tutorial. Your tutorial should delve into a specific algorithmic topic of your choice, such as sorting algorithms, search algorithms, dynamic programming, graph algorithms, or any other area of expertise you possess.

**Instructions:**

1. Choose an algorithmic topic that you are knowledgeable about or interested in.
2. Create a tutorial that covers the selected topic in detail.
3. Your tutorial should be structured as an HTML page and include the following sections:

- Title: A clear and informative title for the tutorial.
- Introduction: Briefly introduce the algorithmic topic you will be covering and explain its importance or relevance.
- Overview: Provide an overview of the key concepts and principles related to the algorithm.
- Detailed Explanations: Break down the algorithm into its components and explain each step or concept thoroughly. Use clear and concise language.
- {programming_language} Code Samples: Include {programming_language} code examples that illustrate how the algorithm works. Ensure that the code is well-commented and easy to understand.
- Visualizations (optional): If applicable, include visual representations or diagrams to aid in understanding.
- Complexity Analysis: Discuss the time and space complexity of the algorithm and analyze its efficiency.
- Applications: Describe real-world applications or scenarios where the algorithm is commonly used.
- External Links: Provide links to external resources, research papers, or additional reading materials for those who want to explore the topic further.
- Conclusion: Summarize the key takeaways from the tutorial and reiterate the significance of the algorithm.

4. Ensure that your HTML page is well-structured, with appropriate headings, paragraphs, and code formatting.
5. Use hyperlinks to connect sections, references, and external links.
6. Make use of proper HTML tags for formatting and styling, such as headings, lists, and code blocks.
7. Proofread and edit your tutorial for clarity, accuracy, and completeness.

**Note:** Make sure to choose a unique algorithmic topic every day. Your tutorial should be detailed, educational, and suitable for both beginners and those with some algorithmic knowledge.
1. **Choose Your Algorithm:** Select a unique, different algorithmic topic each time that piques your interest or falls within your domain of expertise.

2. **Craft Your Tutorial:** Your tutorial should be structured as an HTML document, and it must encompass the following sections:

- **Title:** Create a captivating and informative title that encapsulates the essence of your tutorial.

- **Introduction:** Begin with a concise introduction to the chosen algorithmic topic. Explain why this algorithm is significant and relevant in the world of computer science.

- **Overview:** Provide an overview that outlines the fundamental principles and concepts related to the algorithm. Offer a high-level understanding before diving into the specifics.

- **In-Depth Explanation:** Break down the algorithm into its core components, and meticulously elucidate each step or concept. Utilize clear and succinct language to ensure your readers can grasp the material effortlessly.

- **{programming_language} Code Samples:** Embed code examples written in {programming_language} to illustrate the algorithm's inner workings. Ensure your code is well-commented and easily comprehensible. Make sure that your code samples are written in {programming_language}. Don't use any other programming language.

- **Visualizations (optional):** If applicable, consider incorporating visual aids such as diagrams or flowcharts to facilitate understanding.

- **Complexity Analysis:** Engage in a comprehensive discussion about the time and space complexity of the algorithm. Analyze its efficiency and performance.

- **Real-World Applications:** Explore real-world scenarios and use cases where the algorithm finds common application. Make the algorithm's practicality tangible to your readers.

- **External Resources:** Enhance your tutorial by offering links to external resources, research papers, or supplementary reading materials for those eager to delve deeper into the subject.

- **Conclusion:** Summarize the key takeaways from your tutorial, reaffirming the algorithm's importance and relevance.

3. **Structural Integrity:** Ensure that your HTML page is meticulously structured with appropriate headings, well-organized paragraphs, and clean code formatting.

4. **Hyperlink Integration:** Employ hyperlinks to seamlessly connect sections, cross-reference content, and provide quick access to external resources.

5. **HTML Tags for Enhancement:** Utilize proper HTML tags to enhance formatting and styling. Leverage headings, lists, and code blocks to make your content visually appealing and reader-friendly.

6. **Proofreading and Refinement:** Before finalizing your tutorial, meticulously proofread and edit it to guarantee clarity, accuracy, and comprehensiveness.

**Note:** Challenge yourself to explore a unique algorithmic topic each day. Your tutorial should serve as an educational resource catering to both beginners and those possessing some prior knowledge of algorithms. Also, make sure that your tutorial code samples are written in {programming_language}. Don't use any other programming language.
"""

def send_algorithm_email(self, to: str, language: str) -> None:
Expand Down