diff --git a/.gitignore b/.gitignore index 6a3e68d..e1212eb 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -**/.DS_Store \ No newline at end of file +**/.DS_Store +docs/src/assets/.DS_Store diff --git a/docs/src/.vuepress/public/favicon.ico b/docs/src/.vuepress/public/favicon.ico index c74e547..cd391c5 100644 Binary files a/docs/src/.vuepress/public/favicon.ico and b/docs/src/.vuepress/public/favicon.ico differ diff --git a/docs/src/assets/.DS_Store b/docs/src/assets/.DS_Store index 97d0cd9..7da438c 100644 Binary files a/docs/src/assets/.DS_Store and b/docs/src/assets/.DS_Store differ diff --git a/docs/src/assets/images/assistant.png b/docs/src/assets/images/assistant.png new file mode 100644 index 0000000..1dffcf3 Binary files /dev/null and b/docs/src/assets/images/assistant.png differ diff --git a/docs/src/develop/README.md b/docs/src/develop/README.md index 6c9fabd..17985a2 100644 --- a/docs/src/develop/README.md +++ b/docs/src/develop/README.md @@ -2,29 +2,77 @@ ## Github Copilot -### Completion -### Assistance -### Refactoring -### Test generation -### Documentation -### Architecture diagram +::: tip Update +Copilot can now use other LLMs than OpenAI, including Google, and Anthropic to provide code suggestions +::: -## Cloud LLMs -* Azure APIs, Gemini APIs, OpenAI -* with curl + then python client +Github Copilot is a tool that uses the OpenAI language models to provide code suggestions and suggestions for improving code quality. -## Advanced RAG -* Use of llama-index or Langchain4j so if we want to do JAVA +::: tip Alternative code assistance +There is also other producs indegrated to IDEs such as [Gitlab Duo](https://about.gitlab.com/fr-fr/gitlab-duo/), [Gemini Code Assist](https://cloud.google.com/gemini/docs/codeassist/overview?hl=fr), [SuperMaven](https://supermaven.com/), [AWS CodeWhisperer](https://docs.aws.amazon.com/codewhisperer/latest/userguide/what-is-cwspr.html), and more. +::: -### Function calling / Json Mode -* see Demo Jean François +### Copilot Chat + +Copilot Chat is a chat interface that allows you to ask questions and get suggestions for code improvements. + +it's available on : +- JetBrains IDEs +- Visual Studio +- Visual Studio Code +- In Github mobile App +- Web version in github.com (Preview) + +It is a similar approach to chat GPT prompting optimised for the developper experience. + + + +### CLI +CLI helps you using you command line interpreter +You can use it in the terminal with the following command: + +```bash +gh auth login +gh extension install github.copilot +gh copilot explain "traceroute github.com" +```` +::: warning +Github CLI is not supported yet with our Worldline account, so you need to use the web version with the link here +::: + +### JetBrains integration + +#### Completion +#### Assistance +#### Refactoring +#### Test generation +#### Documentation +#### Architecture diagram + +### VSCode integration + +#### Completion +#### Assistance +#### Refactoring +#### Test generation +#### Documentation +#### Architecture diagram + + +## Gihub Spark +[GitHub Spark](https://githubnext.com/projects/github-spark#introducing-github-spark) is an AI-powered tool for creating and sharing micro apps (“sparks”), which can be tailored to your exact needs and preferences, and are directly usable from your desktop and mobile devices. Without needing to write or deploy any code. + +And it enables this through a combination of three tightly-integrated components: + +An NL-based editor, which allows easily describing your ideas, and then refining them over time +A managed runtime environment, which hosts your sparks, and provides them access to data storage, theming, and LLMs +A PWA-enabled dashboard, which lets you manage and launch your sparks from anywhere -### Local RAG -* (Ollama CLI) ## 🧪 Exercises ## 📖 Further readings -* Data platform, Stephan Pirson, MS, https://worldline365.sharepoint.com/_forms/. spfxsinglesignon.aspx. +*[Worldline AI coding assistant](https://confluence.worldline-solutions.com/display/AICA/AI+Coding+Assistants+Home) +* [Worldline Data platform](https://confluence.worldline-solutions.com/display/DPTECHNO/Data+Platform) diff --git a/docs/src/llm/README.md b/docs/src/llm/README.md index 315112c..de92740 100644 --- a/docs/src/llm/README.md +++ b/docs/src/llm/README.md @@ -3,26 +3,23 @@ LibreChat is a free, open source AI chat platform. This Web UI offers vast customization, supporting numerous AI providers, services, and integrations. Serves all AI Conversations in one place with a familiar interface, innovative enhancements, for as many users as you need. -1. Prompts history -2. AI providers -3. AI model version -4. Preformatted prompts -5. RAG +The full librechat documentation is available [here](https://www.librechat.ai/docs) -## Favorites +Let's discover how to use LibreChat to create efficient and effective conversations with AI for developers. + +## Prompts history +Prompts history allows users to save and load prompts for their conversations and easily access them later. Reusing prompts can save time and effort, especially when working with multiple conversations and keep track of the context and details of a conversation. -The favorites feature in our app is a powerful tool that allows users to save and load favorite prompts for their conversations. +## Favorites +The favorites feature allows users to save and load favorite prompts for their conversations and easily access them later. ## Presets -The `presets` feature in our app is a powerful tool that allows users to save and load predefined settings for initialise a conversations. Users can import and export these presets as JSON files, set a default preset, and share them with others. +The `presets` feature allows users to save and load predefined settings for initialise a conversations. Users can import and export these presets as JSON files, set a default preset, and share them with others. ## Preformatted prompts - -The prompts feature in our app is a powerful tool that allows users to save and load predefined prompts for their conversations. +The prompts feature allows users to save and load predefined prompts to use it during their conversations. You can use a prompt with the /[`prompt command`]. A prompt can have parameters, which are replaced with values when the prompt is used. -Prompts creation is available at the right sidebar. You can create a new prompt, edit an existing prompt, or delete a prompt. - **Exemple of preformatted prompts : Explain the following code snippet in Java, Kotlin or Javascript** * Click on the `+` button to add a new prompt. @@ -42,26 +39,18 @@ Explain the following {{language:Java|Kotlin|Javascript}} snippet of code: ## AI providers ### Azure OpenAI -Azure AI Search (formerly known as "Azure Cognitive Search") provides secure information retrieval at scale over user-owned content in traditional and generative AI search applications. +Azure OpenAI Service provides REST API access to OpenAI's powerful language models, including the o1-preview, o1-mini, GPT-4o, GPT-4o mini, GPT-4 Turbo with Vision, GPT-4, GPT-3.5-Turbo, and Embeddings model series. -Information retrieval is foundational to any app that surfaces text and vectors. Common scenarios include catalog or document search, data exploration, and increasingly feeding query results to prompts based on your proprietary grounding data for conversational and copilot search. When you create a search service, you work with the following capabilities: +### Google Gemini +Gemini is a large language model (LLM) developed by Google. It's designed to be a multimodal AI, meaning it can work with and understand different types of information, including text, code, audio, and images. Google positions Gemini as a highly capable model for a range of tasks, from answering questions and generating creative content to problem-solving and more complex reasoning. There are different versions of Gemini, optimized for different tasks and scales. -* A search engine for vector search and full text and hybrid search over a search index -* Rich indexing with integrated data chunking and vectorization (preview), lexical analysis for text, and optional applied AI for content extraction and transformation -* Rich query syntax for vector queries, text search, hybrid queries, fuzzy search, autocomplete, geo-search and others -* Azure scale, security, and reach -* Azure integration at the data layer, machine learning layer, Azure AI services and Azure OpenAI - -### Google -Google Programmable Search Engine (formerly known as Google Custom Search and Google Co-op) is a platform provided by Google that allows web developers to feature specialized information in web searches, refine and categorize queries and create customized search engines, based on Google Search - -### Anthropic +### Anthropic Claude Claude is an Artificial Intelligence, trained by Anthropic. Claude can process large amounts of information, brainstorm ideas, generate text and code, help you understand subjects, coach you through difficult situations, help simplify your busywork so you can focus on what matters most, and so much more. ## Assistants -The Assistants API enables the creation of AI assistants, offering functionalities like code interpreter, knowledge retrieval of files, and function execution. The Assistants API allows you to build AI assistants within your own applications. An Assistant has instructions and can leverage models, tools, and files to respond to user queries. The Assistants API currently supports three types of tools: Code Interpreter, File Search, and Function calling. +The Assistants API enables the creation of AI assistants, offering functionalities like code interpreter, knowledge retrieval of files, and function execution. The Assistants API allows you to build AI assistants within your own applications for specific needs. An Assistant has instructions and can leverage models, tools, and files to respond to user queries. The Assistants API currently supports three types of tools: Code Interpreter, File Search, and Function calling. -### Azure Assistant +![assistant](../assets/images/assistant.png) ## Plugins The plugins endpoint opens the door to prompting LLMs in new ways other than traditional input/output prompting. @@ -110,31 +99,31 @@ You can mix plugins to create more complex prompts. For example, you can use the ``` Generate the favicon 16x16 pixels based on the content found in https://worldline.github.io/learning-ai/overview/ with Browser plugin -and generate the favicon with DallE. I want no background and black and -white style image +and generate the favicon with DallE. I want no background and black and white image ``` ![prompt](../assets/images/multi_plugin.png) ![Favicon](../assets/images/result_prompt.png) ## RAG -RAG is possible with LIbrechat. You can use RAG to create a conversation with the AI. +RAG is possible with LibreChat. You can use RAG to create a conversation with the AI. To can add files to the conversation, you go to the file tab and select the file you want to add. Then the file will be added to the file manager and you can use it in the prompt. The file can be an png, a video, a text file, or a PDF file. ## 🧪 Exercises -#### Try to make a request respecting Persona, Task and Context, and format structure - -#### Prompt creation +#### 1. Prompt creation Select one prompt engineering technique and make a prompt in librechat that can be called with the `/[prompt_name]` command. -#### Plugins mixing +#### 2. Plugins mixing + +Use the Browse and Dall-E plugins to create a prompt that generates a a favicon based on the content of this learning-ai website. -Use the Browse and Dall-E plugins to create a prompt that generates a technical diagram based on the content of this learning-ai website +#### 3. Make your own assistant +Choose your favorite topic ( cooking, travel, sports, etc.) and create an assistant that can answer questions about it. You can share documents, files and instructions to configure your custom assistant and use it. ## 📖 Further readings * [LibreChat Worldline guides](https://worldline365.sharepoint.com/:u:/r/sites/GenerativeAIQA/SitePages/LibreChat-guides.aspx?csf=1&web=1&e=evKJpU) diff --git a/docs/src/overview/README.md b/docs/src/overview/README.md index 4e66002..e52d3ae 100644 --- a/docs/src/overview/README.md +++ b/docs/src/overview/README.md @@ -102,6 +102,129 @@ During the turing test, the human questioner asks a series of questions to both ![top50](../assets/images/top50.png) + ## 🧪 Exercises + +
+

1. LLMs and MMLLMs are constantly evolving.

+
+ +

2. Multi-Modal LLMs can process and generate only text data.

+
+ +

3. Which of the following are examples of Machine Learning applications?

+
+
+
+ +

4. Deep Learning uses artificial neural networks with multiple layers.

+
+ +

5. Natural Language Processing (NLP) includes which of the following?

+
+
+
+ +

6. RAG stands for Retrieval Augmented Generation.

+
+ +

7. LLMs can only generate text and cannot understand it.

+
+ +

8. Which of the following is NOT a type of Machine Learning?

+
+
+
+ +

9. Deep Learning models require less data than traditional Machine Learning models.

+
+ +

10. Natural Language Processing can be used for sentiment analysis.

+
+ +

11. Which of the following are common applications of Deep Learning?

+
+
+
+ +

12. RAG can improve the accuracy of responses generated by LLMs.

+
+ +

13. Which of the following is a benefit of using Cloud Computing for AI?

+
+
+
+ +

14. The Turing Test is designed to evaluate a machine's ability to exhibit intelligent behavior.

+
+ +

15. Multi-Modal LLMs can only process text and images.

+
+ +
+ + +::: details Solution + +
+

1. LLMs and MMLLMs are constantly evolving.

+
+ +

2. Multi-Modal LLMs can process and generate only text data.

+
+ +

3. Which of the following are examples of Machine Learning applications?

+
+
+
+ +

4. Deep Learning uses artificial neural networks with multiple layers.

+
+ +

5. Natural Language Processing (NLP) includes which of the following?

+
+
+
+ +

6. RAG stands for Retrieval Augmented Generation.

+
+ +

7. LLMs can only generate text and cannot understand it.

+
+ +

8. Which of the following is NOT a type of Machine Learning?

+
+
+
+ +

9. Deep Learning models require less data than traditional Machine Learning models.

+
+ +

10. Natural Language Processing can be used for sentiment analysis.

+
+ +

11. Which of the following are common applications of Deep Learning?

+
+
+
+ +

12. RAG can improve the accuracy of responses generated by LLMs.

+
+ +

13. Which of the following is a benefit of using Cloud Computing for AI?

+
+
+
+ +

14. The Turing Test is designed to evaluate a machine's ability to exhibit intelligent behavior.

+
+ +

15. Multi-Modal LLMs can only process text and images.

+
+ +
+ +::: + ## 📖 Further readings * [Generative AI Taskforce email](mailto:GenAITaskforce@worldline.com) * [Top 100 GenAI](https://a16z.com/100-gen-ai-apps/) diff --git a/docs/src/services/README.md b/docs/src/services/README.md index bec0c0f..21115b9 100644 --- a/docs/src/services/README.md +++ b/docs/src/services/README.md @@ -1,14 +1,77 @@ # AI for services -## Hugging Face +## APIs with LibreChat + +For basic APIs exchange with LibreChat, you can use simple HTTP requests. You can use the `/api/v1/chat/completions` endpoint to send a request to the API and receive a response. + +## CloudAI with GCP +GCP is a suite of cloud computing services provided by Google. It includes a wide range of tools and services for building and consuming LLMs, such as Vertex AI, Google Colab, and ML Flow. + +### Large Consumer-Facing +These products are directly available to consumers, often integrating AI capabilities into everyday applications: + +- **Google Colaboratory (Colab):** A free Jupyter Notebook environment hosted by Google. Excellent for learning, experimentation, and sharing machine learning code. While not a "production" platform like Vertex AI, it's extremely popular for its ease of use and free access to compute resources (though with limitations). +- **Gemini:** Google's large language model (LLM), positioned as a competitor to OpenAI's GPT models. Gemini's capabilities are integrated into various Google products and services, and are also accessible through APIs. Different versions of Gemini (e.g., Gemini Pro, Gemini Ultra) offer varying levels of capability and access. It powers several consumer-facing features across Google's ecosystem. +- **AI Studio** Cloud-based machine learning platform offered by several companies, most notably Google with its Google AI Studio (now largely integrated into Vertex AI) and Amazon with Amazon SageMaker Studio. While both share the general goal of providing a user-friendly environment for building, training, and deploying machine learning models, their specific features and offerings differ. https://aistudio.google.com/ + +### Vertex AI +This is the central hub for most Google Cloud's AI/ML services. It integrates and supersedes many previous offerings. + +- **Vertex AI Training:** Training machine learning models using various algorithms and frameworks (TensorFlow, PyTorch, scikit-learn, XGBoost, etc.). Provides access to managed compute instances (including TPUs). +- **Vertex AI Prediction:** Deploying trained models for inference (making predictions). Offers different deployment options based on scale and latency requirements. +- **Vertex AI Pipelines:** Creating and managing machine learning workflows, including data preprocessing, model training, evaluation, and deployment, as a series of connected steps. +- **Vertex AI Model Monitoring:** Monitoring deployed models for performance degradation and potential issues (drift). +- **Vertex AI Feature Store:** Centralized repository for storing, managing, and versioning features used in machine learning models, improving collaboration and reuse. +- **Vertex AI Matching Engine:** A service for performing similarity searches (for example, recommendation systems). + +### Google Cloud APIs + +Pre-trained Models and APIs: Google offers numerous pre-trained models and APIs for various tasks, making it easier to integrate AI into applications without building models from scratch. Examples include: + +- **Google Cloud Natural Language API:** Processing and understanding text (sentiment analysis, entity recognition, etc.). +Google Cloud Vision API: Analyzing images (object detection, image classification, optical character recognition, etc.). +- **Google Cloud Speech-to-Text API:** Converting audio to text. +- **Google Cloud Text-to-Speech API:** Converting text to audio. +- **Google Cloud Translation API:** Translating text between languages. +- **Other APIs**: Many more APIs exist for various tasks like video intelligence, dialogflow (conversational AI), and more. + +### Specialized AI Products +Beyond the core platform and APIs, Google offers several specialized AI products: + +- **TensorFlow:** A popular open-source machine learning framework developed by Google. While not strictly a "Google Cloud" product, it's deeply integrated with their services. +- **TensorFlow Extended (TFX):** A platform for deploying TensorFlow models at scale, often used in conjunction with Vertex AI. +- **JAX:** A high-performance machine learning library, often used for research and advanced applications. +- **Google AI Platform Notebooks (integrated into Vertex AI):** Jupyter Notebook environments hosted on Google Cloud. (Previously a separate offering, often confused with Google Colab.) +- **Dialogflow CX:** A conversational AI platform for building complex conversational experiences. + +## Manage models (ML Flow) +MLflow provides tools for managing experiments, tracking model versions, deploying models to various environments, and managing models in a central registry. It's designed to be platform-agnostic, meaning it can work with many different cloud providers and even on-premises infrastructure. + +## Function calling (langchain4j) +Function calling is a feature that allows you to call functions from other services. It is useful for working with functions, such as APIs, and for interacting with models that require function calls. + +To use function calling, you need to specify the function name and arguments in the prompt. + +Ressouces Jean François James + +## Structured Outputs (Json Mode) +Json mode is a feature that allows you to send structured data to the model. It is useful for working with structured data, such as JSON objects, and for interacting with models that require structured input. + +To use Json mode, you need to specify the input format as JSON in the prompt. You can do this by adding the following line to the beginning of your prompt: + + +## Advanced RAG (llama-index) +RAG with Ollama CLI with Langchain4j and llama-index + + +## Collaborative (Hugging Face) +The platform where the machine learning community collaborates on models, datasets, and applications. + +Hugging Face is a platform for researchers and developers to share, explore, and build AI models. It provides a centralized repository for models, datasets, and applications, making it easy to find, use, and contribute to the growing ecosystem of AI technologies. + - Creating/deploy/customize a model - Pre-trained model, use behind the APIs, also a ML part, training model generation for use -## AI in GCP -- Introduction to Vertex AI and Gemini, language models, Google Colab, ML flow. - -## AI prototyping -- Introduction to prototyping with Jupyter notebook for AI. ## 🧪 Exercises diff --git a/docs/src/use/README.md b/docs/src/use/README.md index 7071650..fb96e5f 100644 --- a/docs/src/use/README.md +++ b/docs/src/use/README.md @@ -1,7 +1,5 @@ # Prompt with AI -The full documentation is available [here](https://www.librechat.ai/docs) - ## Prompt engineering Prompt engineering involves the design and creation of prompts that are used to elicit specific responses or actions from AI models or interactive systems. These prompts are carefully crafted to guide the behavior or generate particular outputs from the AI, such as generating natural language responses, providing recommendations, or completing specific tasks. @@ -22,7 +20,6 @@ There are four main areas to consider when writing an effective prompt. You don * [`Context`] to [person description] based on [details about relevant program docs]. * [`Format`] Limit to bullet points. -### General usage By using "act as," you are establishing a specific context for the language model and guiding it to understand the type of task or request you are making. This helps to set the right expectations and provides the language model with the necessary context to generate a response tailored to the defined role. ``` @@ -30,29 +27,27 @@ By using "act as," you are establishing a specific context for the language mode on a prompt about a futuristic world where robots have become sentient." ``` -#### Summarize +### Summarize +Summary is a prompt engineering technique that involves providing a summary of a given document or text. It can helps for summarizing changelogs, articles, or other technical documents. + ``` Help me write an article of this document [Insert or copy paste document text] Generate 5 titles out of the following topic…. -Generate a subtitle to catch readers’ attention on the following topic [describe the topic] +Generate a subtitle to catch readers’ attention on the following +topic [describe the topic] ``` -#### Fix -``` -Help me find mistakes in my code [insert your code] -Explain what this snippet of code does [insert code snippet] -What it the correct syntax for a [statement or function] in [programming language] -How do I fix the following programming language code [program language] code which explain the functioning [Insert code snippet] -``` +### Write + +Write is a prompt engineering technique that involves providing a step-by-step guide or instructions for a given task or process. Its useful for developers to create functional and technical documentations. -#### Write ``` Create a template of an email response to customer inquiring about …. Create a guide that explains how to use …. Write step by step instructions ``` -## Developers prompts +## For Developers ### Code explanation Code explanation is a prompt engineering technique that involves providing a detailed explanation of a code snippet or function. This technique is useful for developers who want to understand the inner workings of a codebase or for those who want to document their code. @@ -61,36 +56,37 @@ cf. Preformatted prompts for an example of code explanation ### Generation ``` -Act as a code generator. Generate a Python function that takes a list of numbers as input and returns the sum of all the numbers. +Act as a code generator. Generate a Python function that takes a list of +numbers as input and returns the sum of all the numbers. ``` ### Completion - Code completion is a prompt engineering technique that involves providing a list of possible completions for a given code snippet or function. This technique is useful for developers who want to suggest possible code changes or improvements based on their existing code. ### Conversion - Code conversion is a prompt engineering technique that involves providing a conversion of a code snippet or function from one programming language to another. This technique is useful for developers who want to migrate their code from one language to another or for those who want to use a different programming language for their projects. - ### Review - Code review is a prompt engineering technique that involves providing a code review of a given code snippet or function. This technique is useful for developers who want to review their code for potential issues,bugs, or for those who want to provide feedback on their code. ### Fixing - Code fixing is a prompt engineering technique that involves providing a code fix for a given code snippet or function. This technique is useful for developers who want to fix bugs or issues in their code or for those who want to improve the quality of their code. +``` +Help me find mistakes in my code [insert your code] +Explain what this snippet of code does [insert code snippet] +What it the correct syntax for a [statement or function] +in [programming language] +How do I fix the following programming language code +[program language] code which explain the functioning [Insert code snippet] +``` ### Refactoring - Code refactor is a prompt engineering technique that involves providing a code refactoring of a given code snippet or function within a specific scope. This technique is useful for developers who want to refactor their code within a specific context or for those who want to improve the readability and maintainability of their code. ### Data mocking - Mock data generation is a prompt engineering technique that involves providing a mock data set for a given code snippet or function. This technique is useful for developers who want to test their code with mock data or for those who want to generate test data for their projects. It avoid creating manually fake data for testing. - -## Other prompts +## Go further ### Testing @@ -104,6 +100,18 @@ System design and architecture is a prompt engineering technique that involves p Documentation generation is a prompt engineering technique that involves providing a documentation for a given code snippet or function. This technique is useful for developers who want to document their code or for those who want to provide documentation for their projects. It can be used to generate documentation in various formats such as Markdown, HTML, or PDF. +### Commit Message Generation + +Commit message generation is a prompt engineering technique that involves providing a commit message for a given code snippet or function. This technique is useful for developers who want to generate commit messages for their code or for those who want to ensure that their commit messages are clear and concise. + +### Vulnerability checking + +Vulnerability checking is a prompt engineering technique that involves providing a vulnerability check for a given code snippet or function. This technique is useful for developers who want to check for vulnerabilities in their code or for those who want to ensure that their code is secure. + +::: warning +This prompt is not recommended for production use. It is intended for testing and debugging purposes only and is not a proof of security or safety of your app. +::: + ### Shell/CLI commands manual As a developer, you’re not limited to only writing code. LLMs can assist with CLI such as shell commands and version control using Git. @@ -117,6 +125,200 @@ Explain this regular expression in JavaScript: const regex = /^[A-Za-z0–9._%+-]+@[A-Za-z0–9.-]+\\.[A-Za-z]{2,}$/; ``` +## 🧪 Exercises + + +### Exercise 1: Basic Function Creation + +- Create a function that calculates the factorial of a number. +- Handle both positive integers and zero, with error handling for negative inputs. + +**Expected Output (python)** +```python +def factorial(n): + if n < 0: + raise ValueError("Input must be a non-negative integer.") + if n == 0: + return 1 + result = 1 + for i in range(1, n + 1): + result *= i + return result +``` + + +### Exercise 2: API Request Handling + +- Write a function to fetch data from a given URL using the Fetch API. +- Return the JSON response and handle any potential errors. + +**Expected Output (javascript)** +```javascript +async function fetchData(url) { + try { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + const data = await response.json(); + return data; + } catch (error) { + console.error("Error fetching data:", error); + } +} +``` + +### Exercise 3: Class Definition + +- Define a class representing a book with properties for title, author, and publication year. +- Include a method to display the book's details. + +**Expected Output (C#)** +```csharp +public class Book +{ + public string Title { get; set; } + public string Author { get; set; } + public int PublicationYear { get; set; } + + public void DisplayDetails() + { + Console.WriteLine($"Title: {Title}, Author: {Author}, Year: {PublicationYear}"); + } +} +``` + + +### Exercise 4: Simple Web Server + +- Set up a basic web server that listens on port 3000. +- Respond with a simple message when accessed. + +**Expected Output (Javascript)** +```javascript +const http = require('http'); + +const server = http.createServer((req, res) => { + res.statusCode = 200; + res.setHeader('Content-Type', 'text/plain'); + res.end('Hello, World!\n'); +}); + +server.listen(3000, () => { + console.log('Server running at http://localhost:3000/'); +}); +``` + +--- + +### Exercise 5: Data Validation + +**Details:** +- Write a method to validate if a given string is a valid email address. +- Use a regular expression for the validation. + +**Expected Output (Ruby)** +```ruby +def valid_email?(email) + regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i + !!(email =~ regex) +end +``` + +### Exercise 6: Mock Data Generation + +Create prompts that can generate mock user profiles. The language used is JavaScript. + +The profile should include: +* Name +* Age +* Email +* Address (Street, City, State, Zip Code) +* Phone Number + + +::: details Solutions + +Exercise 1: Basic Function Creation + +**Persona:** Python Developer +**Task:** Create a function +**Context:** You need to calculate the factorial of a number. + +As a Python Developer, create a function named `factorial` that takes a single integer input and returns its factorial. The function should handle both positive integers and zero. Include error handling for negative inputs. + +Exercise 2: API Request Handling + +**Persona:** JavaScript Developer +**Task:** Write a function to handle API requests +**Context:** You need to fetch data from a given URL. + +As a JavaScript Developer, write a function named `fetchData` that takes a URL as an argument and fetches data from that URL using the Fetch API. The function should return the JSON response and handle any errors that may occur during the fetch operation. + +Exercise 3: Class Definition + +**Persona:** C# Developer +**Task:** Define a class +**Context:** You are creating a representation of a book. + +As a C# Developer, create a class named `Book` that has properties for `Title`, `Author`, and `PublicationYear`. Include a method named `DisplayDetails` that prints the book's details in a formatted string. + + +Exercise 4: Simple Web Server + +**Persona:** JavaScript Developer +**Task:** Set up a web server +**Context:** You need to create a simple server that responds to requests. + +As a JavaScript Developer, set up a simple web server using the `http` module that listens on port 3000 and responds with "Hello, World!" when accessed. + +Exercise 5: Data Validation + +**Persona:** Ruby Developer +**Task:** Write a validation method +**Context:** You need to validate email addresses. + +As a Ruby Developer, write a method named `valid_email?` that takes a string as input and returns true if it is a valid email address, and false otherwise. Use a regular expression for validation. + + +Exercise 6: Mock Data Generation + +As a JavaScript Developer, write a function named `generateUserProfile` that generates a mock user profile with the following details: name, age, email, address, and phone number. The function should return an object containing the user profile details. + +```javascript +function generateUserProfile() { + const names = ["Alice", "Bob", "Charlie", "David", "Eva"]; + const randomName = names[Math.floor(Math.random() * names.length)]; + const randomAge = Math.floor(Math.random() * 50) + 18; // Age between 18 and 67 + const randomEmail = `${randomName.toLowerCase()}@example.com`; + const randomAddress = { + street: `${Math.floor(Math.random() * 1000)} Main St`, + city: "Sample City", + state: "CA", + zip: "12345" + }; + const randomPhone = `(${Math.floor(Math.random() * 900) + 100})-${Math.floor(Math.random() * 900) + 100}-${Math.floor(Math.random() * 9000) + 1000}`; + + return { + name: randomName, + age: randomAge, + email: randomEmail, + address: randomAddress, + phone: randomPhone + }; +} + +// Example usage +console.log(generateUserProfile()); +``` + + + +::: + + + +