Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - ChatGPT

108 Articles
article-image-ai-in-the-real-world-real-estate
Julian Melanson
20 Jul 2023
4 min read
Save for later

AI in the Real World: Real Estate

Julian Melanson
20 Jul 2023
4 min read
The fast-paced development of Artificial Intelligence has already started reshaping various sectors, with the real estate industry standing out as a prominent beneficiary. Of particular interest is the potential AI presents in streamlining property valuation, a critical process that underlies a myriad of real estate activities, including setting sale prices, making investment decisions, and optimizing home insurance premiums. While the conventional means of property valuation have their merits, they are far from perfect. This article delves into the potential of AI, specifically OpenAI's ChatGPT, in transforming property valuation in the real estate sector, discussing the challenges inherent to traditional approaches and exploring the benefits offered by this AI-driven approach.The Current State of Property ValuationProperty valuation is a meticulous process that draws on a variety of data sources, both public and private. Depending on the valuation's purpose, the time and effort committed to research can differ significantly. For instance, real estate brokers might base their Broker Price Opinions on a limited set of comparable properties, while appraisers might undertake a thorough firsthand inspection to understand a property's condition, quality, and value comprehensively.Despite the evolution of valuation methodologies over the years, traditional approaches still grapple with certain obstacles. One of the primary issues is data inconsistency, mainly arising from the dispersed and scattered nature of relevant property data across various sources. While attempts have been made to centralize information on property features, ownership changes, and other key insights, consistency in data remains elusive. The result is disparities in the Automated Valuation Models (AVMs) currently used, which can lead to divergent valuations for the same property.Moreover, human bias forms a significant challenge in property appraisals. It's often difficult to find identical properties for comparison, leading to inevitable subjectivity in adjustments made to reconcile price differences. Studies show that appraised values fall below the agreed purchase price in just 10% of cases, suggesting a propensity towards price confirmation bias, a situation that calls for greater objectivity in home appraisals.Integrating AI into Property Valuation: The Role of ChatGPTIn response to these challenges, the integration of AI into the property valuation process presents a promising solution. The application of AI, especially advanced language models like ChatGPT, can offer consistent examinations of a property’s condition and quality, mitigating issues associated with data inconsistencies and human bias.ChatGPT, a generative pre-trained transformer, has been designed to understand and generate human-like text based on given input. In the context of real estate, it offers tremendous potential in data analysis and, consequently, in generating accurate property valuations. Traditionally, property valuations have been conducted by human appraisers who assess a property’s worth based on a range of factors such as location, size, and condition. However, this approach can be time-consuming, costly, and susceptible to human error.By incorporating ChatGPT into the valuation process, real estate professionals can input relevant data into the AI model, which can then analyze the data and supply a detailed valuation report. The implications of this are transformative for the industry: it offers considerable time savings, reduces the potential for errors, and enhances the transparency of the valuation process.A Practical Application of ChatGPT in Property ValuationHere’s a very simple prompt that illuminates how ChatGPT can be a great guide in the property valuation process:    The evolution of AI has unlocked numerous opportunities for innovation and efficiency across a variety of sectors, with the real estate industry being no exception. Particularly, the advent of AI models like ChatGPT has opened new avenues for enhancing the accuracy and efficiency of property valuations. By surmounting the obstacles inherent to traditional valuation methodologies, such as data inconsistencies and human bias, AI offers a more streamlined, transparent, and precise approach to property valuation. Author BioJulian Melanson is one of the founders of Leap Year Learning. Leap Year Learning is a cutting-edge online school that specializes in teaching creative disciplines and integrating AI tools. We believe that creativity and AI are the keys to a successful future and our courses help equip students with the skills they need to succeed in a continuously evolving world. Our seasoned instructors bring real-world experience to the virtual classroom and our interactive lessons help students reinforce their learning with hands-on activities.No matter your background, from beginners to experts, hobbyists to professionals, Leap Year Learning is here to bring in the future of creativity, productivity, and learning!
Read more
  • 0
  • 0
  • 2429

article-image-mitigating-the-risks-of-chatgpt-in-finance
Julian Melanson
13 Jul 2023
5 min read
Save for later

Mitigating the Risks of ChatGPT in Finance

Julian Melanson
13 Jul 2023
5 min read
The application of advanced AI tools, such as ChatGPT, in various industries, particularly finance, has proven transformative due to its extensive language processing capabilities. ChatGPT's functions within the financial sector are diverse and impressive. It can understand financial market dynamics, suggest products, identify specific entities, and generate financial summaries, reports, and forecasts. Furthermore, the potential of training ChatGPT for fraud prevention and detection is an exciting prospect.However, as the integration of ChatGPT into the financial services realm becomes more prevalent, it brings to the fore several ethical challenges. Therefore, the onus is on both researchers and practitioners to ensure that the technology's use is responsible and advantageous to all parties involved. The solutions to these ethical challenges often require a multi-faceted approach, focusing on data exposure, misinformation, technology dependency, privacy concerns, and social engineering.The Ethical Challenges InvolvedOne of the paramount ethical challenges is data exposure. For example, ChatGPT users working with financial data might unintentionally disclose sensitive information. Additionally, during the AI model's training phase, there's a risk of exposing confidential elements such as proprietary code snippets, API keys, or login credentials.ChatGPT can sometimes generate biased or inaccurate responses, causing misinformation. The tool, at present, operates based on data sets that only run up to September 2021, which are sourced online and not always accurate. Therefore, financial professionals must exercise caution while using such advice to prevent the propagation of misinformation.Furthermore, while AI can be a powerful tool for financial decision-making, relying solely on technology can undermine human judgment and intuition. Financial professionals could fall into the trap of misinterpreting or overly depending on ChatGPT's advice, thereby overlooking the importance of human expertise in the financial sector. Therefore, it is crucial to strike a balance between utilizing AI's efficiency and maintaining human critical thinking.As ChatGPT requires an extensive amount of data for training, this raises significant privacy concerns. The information collected could pose serious risks to both individuals and organizations if exposed or used maliciously. In tandem with privacy concerns, social engineering issues arise as well. There is a potential for cybercriminals to misuse ChatGPT, impersonating individuals or organizations to conduct successful phishing attacks.Solving the ProblemAddressing these ethical challenges requires robust solutions. Firstly, the co-creation approach, which emphasizes public participation and stakeholder involvement in designing the AI algorithm. This strategy includes key choices in the algorithm, from the scope of its use to mitigating biases and tackling misinformation. It also ensures that humans keep a certain level of control over the AI tool, thus preventing total dependency on the technology.Secondly, the institutional approach can ensure the ethical use of ChatGPT in finance. This approach demands the establishment of concrete rules for managing ChatGPT, including training policy regulators to scrutinize and audit the AI algorithm and developing regulations. The focus is on creating transparent tools that ensure user privacy and constantly upgrade security measures to prevent breaches by cybercriminals.Lastly, it's vital to maintain a harmonious blend of AI-based decision-making and human intuition. While ChatGPT can crunch data and analyze trends with efficiency, human professionals have the experiential knowledge to make intuitive financial decisions. The amalgamation of both AI and human insight can lead to mutual learning and overall improvement in financial decision-making. It can also help address legal obstacles in financial domains that AI might overlook, thus ensuring the accuracy and reliability of financial decisions.The UK Finance paper on AI Fairness in Financial Services recommends a multi-disciplinary approach:Frontline business must be clear on the objective of the use of AI, the risks to individuals and to the business, and the extent to which risks of unfair treatment will be managed and explained to stakeholders.Data scientists are central to the technical aspects of the use, testing and monitoring of AI.Legal and Compliance need to be involved (including in any preliminary stages) to provide appropriate challenge, to oversee testing and to assist with fair process and related transparency principle.In addition, human application can mitigate the looming threat of job loss due to automation. While technology like ChatGPT can automate many functions, it is essential to preserve roles where human intuition, expertise, and judgment are irreplaceable.While the adoption of ChatGPT in finance is indeed a technological advancement, it comes with ethical challenges that require strategic and thoughtful solutions. Companies must adopt strategies such as co-creation and institutional approaches to ensure ethical usage. Furthermore, they need to strike a balance between AI and human insight to maintain the integrity of financial decisions. By addressing these challenges and implementing relevant strategies, we can ensure a future where AI not only augments the financial sector but also respects the values that we hold dear.Author BioJulian Melanson is one of the founders of Leap Year Learning. Leap Year Learning is a cutting-edge online school that specializes in teaching creative disciplines and integrating AI tools. We believe that creativity and AI are the keys to a successful future and our courses help equip students with the skills they need to succeed in a continuously evolving world. Our seasoned instructors bring real-world experience to the virtual classroom and our interactive lessons help students reinforce their learning with hands-on activities.No matter your background, from beginners to experts, hobbyists to professionals, Leap Year Learning is here to bring in the future of creativity, productivity, and learning!
Read more
  • 0
  • 0
  • 5677

article-image-chatgpt-and-ai-in-the-crypto-market
Julian Melanson
12 Jul 2023
6 min read
Save for later

ChatGPT and AI in the Crypto Market

Julian Melanson
12 Jul 2023
6 min read
OpenAI’s ChatGPT has gained significant attention since it first launched, and with its versatile capabilities and high accuracy, it has the potential to make a substantial impact on the crypto market. It’s crucial that we explore how AI and Natural Language Processing (NLP) can assist in fraud detection and prevention, understand the capabilities and limitations of ChatGPT in the crypto industry and trading, highlight the importance of AI in safeguarding the crypto market, and discuss ChatGPT's role in crypto compliance, AML, security, and its future implications.AI and NLP for Fraud Detection and PreventionNLP is a branch of AI that enables machines to read, understand, and draw conclusions from human languages. By using computational linguistics and statistical models, NLP can show suspicious behavior patterns and uncover fraud in financial transactions. For instance, NLP can detect inconsistencies in credit applications or identify suspicious transactions on credit cards.Capabilities and Limitations of ChatGPT in the Crypto IndustryIn the crypto industry, ChatGPT has various applications, particularly in trading. It can supply a historical overview of a certain type of cryptocurrency, analyze market data, forecast price movements, create strategies, and find trading opportunities. By leveraging ChatGPT, traders can make better-informed decisions and capitalize on emerging possibilities.Here is a very simple example of how ChatGPT can aid in creating a strategy for identifying Chainlink bottoms using the relative strength index (RSI), support and resistance levels, and moving averages:While ChatGPT can elucidate various aspects of the crypto arena, it's imperative to recognize its potential limitations, particularly pertaining to the source reliability of its information. The internet is fraught with misinformation, and since the advent of GPT-4 that offers web-browsing capabilities, such misinformation could inadvertently affect AI tools like ChatGPT. Within the volatile crypto market, such unreliable information can lead to imprudent investments. It’s advisable to fact-check the data ChatGPT provides to mitigate the risk of utilizing information from dubious sources.The Importance of AI in Safeguarding the Crypto MarketThe adoption of blockchain technology has brought benefits such as increased openness, data consistency, and security. By integrating AI with blockchain, a more secure and intelligent system can be established. Blockchain ensures the integrity of shared information and models used by AI, while AI enhances fraud detection capabilities. The combination of AI and blockchain creates a more resilient system that is resistant to attacks and fraud.ChatGPT in Crypto Fraud DetectionChatGPT, with its NLP capabilities, can contribute to fraud detection in the crypto market in several ways:Identifying Suspicious Transactions and Activities: By analyzing emails for suspicious language patterns and detecting anomalies, ChatGPT can help identify potential fraud. It can compare email texts to earlier communications from the same individual, ensuring consistency and detecting deviations.Analyzing Patterns and Anomalies in Crypto Trading Data: ChatGPT can analyze market data and find significant patterns and trends that can aid traders in making informed decisions.Monitoring Social Media and External Sources: ChatGPT can help compliance teams in monitoring chat and social networking platforms for suspicious activities, such as market manipulation and insider trading.Utilizing Advanced Machine Learning Algorithms for Risk Assessment: Machine learning algorithms can predict the likelihood of default on loans or identify risky transactions. This information helps lenders make more informed decisions and manage risks effectively.ChatGPT in Crypto Compliance and AMLIdentifying and Verifying the Identity of Crypto Traders and Investors: ChatGPT excels in identifying and verifying the identity of traders and investors, ensuring the authenticity of individuals involved in crypto transactions.Monitoring for Money Laundering and Financial Crimes: By leveraging AI capabilities, compliance teams can monitor transactions and identify suspicious patterns indicative of money laundering or other financial crimes.Keeping Up with Regulatory Changes and Compliance Requirements: AI chatbots like ChatGPT can adapt to regulatory changes and comply with requirements set by authorities to ensure seamless operations within legal frameworks.Developing and Implementing Effective KYC and AML Procedures: NLP and monitored machine learning techniques play a vital role in streamlining Know Your Customer (KYC) procedures. These technologies facilitate efficient identity verification and analysis of unstructured content.ChatGPT in Crypto SecurityProtecting Crypto Assets and Digital Wallets: AI tools like ChatGPT enhance security measures in crypto exchanges and platforms, safeguarding digital assets and wallets from potential threats.Enhancing Security in Crypto Exchanges and Platforms: ChatGPT helps in verifying the identities of investors, bolstering the overall security mechanism of crypto exchanges and platforms.Identifying and Preventing Phishing and Hacking Attempts: AI algorithms can block unauthorized smart contracts and reduce the risk of phishing and hacking attacks, thereby enhancing the security of the crypto industry.Developing and Implementing Advanced Security Protocols: AI algorithms and machine learning techniques help organizations identify vulnerabilities in their security architecture and improve overall system security.Future Developments and Implications of ChatGPT in CryptoAdvancements in NLP and AI are expected to have a significant impact on fraud detection and prevention. As society moves toward a cashless economy, the role of AI in identifying and preventing digital fraud becomes increasingly critical. ChatGPT's ability to fine-tune popular themes enables traders to stay updated on crypto news, retrieve relevant data, and generate trading strategies based on historical information. However, it is crucial to consider the ethical implications and potential risks associated with using AI for fraud detection and in financial systems. Responsible and informed use of AI technologies can contribute to building trust and credibility in the crypto market.ChatGPT, with its advanced NLP capabilities, offers exciting possibilities for the crypto market. Its potential to enhance fraud detection, bolster security measures, and build trust and credibility is promising. However, it is essential to approach AI adoption in the crypto market cautiously, taking into account ethical considerations and potential implications. As technology continues to evolve, the responsible and informed use of AI can pave the way for a safer and more efficient crypto ecosystem.Author BioJulian Melanson is one of the founders of Leap Year Learning. Leap Year Learning is a cutting-edge online school that specializes in teaching creative disciplines and integrating AI tools. We believe that creativity and AI are the keys to a successful future and our courses help equip students with the skills they need to succeed in a continuously evolving world. Our seasoned instructors bring real-world experience to the virtual classroom and our interactive lessons help students reinforce their learning with hands-on activities.No matter your background, from beginners to experts, hobbyists to professionals, Leap Year Learning is here to bring in the future of creativity, productivity, and learning!
Read more
  • 0
  • 0
  • 12427

article-image-data-analysis-made-easy-with-chatgpt
Sagar Lad
02 Jul 2023
5 min read
Save for later

Data Analysis Made Easy with ChatGPT

Sagar Lad
02 Jul 2023
5 min read
Are you weary of trawling through heaps of analysis data in search of meaningful insights? With ChatGPT, the rules will soon alter. ChatGPT may reveal hidden patterns and trends in your data that you never imagined were there because of its sophisticated natural language processing skills. In this blog article, we'll look at how exploratory data analysis with ChatGPT can revolutionize your data and change the way you conduct business.Data Analysis with ChatGPTFor data analysts, ChatGPT can be a useful tool for processing, exploring, communicating, and collaborating on their data-driven ideas. Large volumes of data can be analyzed and processed by ChatGPT fast and effectively. Written inquiries can be interpreted and understood by ChatGPT through its language processing skills, which also allow it to extract pertinent insights from the data. Here are a few benefits that ChatGPT can provide: Data analysts can use ChatGPT to study their data, spot trends, and even produce useful data visualizations. The data is clearly outlined in these graphics, which makes it simpler for analysts to spot trends and insights. Data analysts can utilize ChatGPT to explain their findings to non-technical stakeholders. The chatbot can assist data analysts in providing simple explanations of complicated data ideas and insights by using natural language. Data analysts might benefit from ChatGPT's help in coming up with fresh, insightful queries to pose to their data. Analysts can investigate novel lines of inquiry and unearth previously unconsidered hidden insights by using natural language queries. Let's look at how chatGPT can make data analysis easy and straightforward. As a data modeler, I want to investigate the data's dictionary and metadata first. Image 1: : Data Dictionary Using ChatGPT, Part 1Image 2 : Data Dictionary Using ChatGPT, Part 2ChatGPT gives us thorough details about the data dictionary for each column, including a complete description of each column. The final user will benefit from this guidance on when and how to use the data.Asking chatGPT about the dataset's number of rows and columns will help you better grasp the overall statistics.  Image 2 : Dataset Statistics  As seen in the image above, chatGPT gives us a precise estimate of the dataset's number of rows and columns. After getting a broad overview of the dataset, let's examine the data's quality: Image 3 : Exploratory Data Analysis - Null Value StatisticsHere, we've given the chatGPT an input containing the dataset and requested it to determine the percentage of null values therein in order to determine whether the data can be used for analytics. The dataset does not contain any null values, hence chanGPT responds that the given dataset contains no missing values.Now, we can observe that the data set's header information is absent. Before we can use the data, the columns must contain meaningful data. Image 4 : Dataset Column Naming ConventionLet's ask chatGPT how it can deliver valuable header data. As you can see, the output of chatGPT is a column header with a description and business-specific naming standards. The technical team's and business users' lives are made easier in terms of using this data.We now know that the data quality is good. As this will affect the results of the data analysis, let's look for any outliers in the dataset. Image 5 : Detect Outliers in the DatasetIn this case, chatGPT is carrying out an in-depth analysis at the column level to see whether any outliers are there. It's okay if it doesn't exist. If it does, it also offers advice on what kind of outlier is present and how it can affect the entire data analysis procedure.Let's now look at how to use chatGPT to eliminate those outliers.Image 7 : Remove Outliers from the dataset using python, Part 1 Image 8 : Remove Outliers from the dataset using python, Part 2Therefore, for a given sample dataset, ChatGPT offers a thorough Python code that can be used to automatically eliminate the observed outliers. The team may have business analysts who are unfamiliar with Python. Let's see how chatGPT can assist business analysts with their data analysis work.Image 7 : SQL Query to calculate monthly revenue, Part 1Image 8 : SQL Query to calculate monthly revenueIn this case, chatGPT offers a default query that the business analyst may utilize to figure out the monthly income for a particular dataset. Let's then ask chatGPT to take on the role of a data analyst and offer further insights for a certain dataset. Image 8 : Step by Step Data Analysis using chatGPT, Part 1  Image 9 : Step-by-Step Data Analysis using ChatGPT, Part 2As we can see from the chatGPT's results, it offers us step-by-step advice on various studies and results that may be applied on top of this particular dataset. The execution of each of these tasks using chatGPT is possible for each phase of the overall data analysis process.Let's ask chatGPT to undertake this data analysis work so that it may use Python to analyze prices for the given dataset:Image 9 : Price Analysis using python, Part 1Image 10 : Price Analysis using python, Part 2Image 11 : Price Analysis using Python, Part 2For the purpose of doing price analysis on a given dataset, ChatGPT has developed a Python code and sample output. We can draw a judgment about how the prices are changing over time based on the data points at hand from this output.ConclusionIn this article, we go into great detail on how to use chatGPT for a variety of exploratory data analysis tasks. Additionally, we looked closely at different approaches to carrying out data analysis tasks using Python and SQL. ChatGPT is, in a word, a very useful tool for performing exploratory data analysis tasks while working with massive volumes of data.Author BioSagar Lad is a Cloud Data Solution Architect with a leading organization and has deep expertise in designing and building Enterprise-grade Intelligent Azure Data and Analytics Solutions. He is a published author, content writer, Microsoft Certified Trainer, and C# Corner MVP. Link - Medium , Amazon , LinkedIn 
Read more
  • 0
  • 0
  • 4898

article-image-making-the-most-of-chatgpt-code-interpreter-plugin
Julian Melanson
22 Jun 2023
5 min read
Save for later

Making the Most of ChatGPT Code Interpreter Plugin

Julian Melanson
22 Jun 2023
5 min read
As we stand on the threshold of a new age in Artificial Intelligence,, OpenAI recently announced the rollout of its ChatGPT Code Interpreter plugin for ChatGPT Plus subscribers, marking a significant evolution in the capabilities of AI. This groundbreaking technology is not merely another link in the AI chain but rather an exemplar of the transformative capabilities AI can bring to the table, particularly in programming and data analysis.The ChatGPT Code Interpreter plugin positions itself as an invaluable tool for developers, promising to significantly augment and streamline their workflows. Among its multiple functionalities, three stand out due to their potential impact on the programming landscape and data analysis, which work in tandem to extract valuable insights.Data VisualizationAt its core, the ChatGPT Code Interpreter excels in the domain of data visualization. In a world increasingly reliant on data, the ability to transform complex datasets into visually comprehensible and comprehensive formats is priceless. The plugin simplifies the arduous task of crunching through complex numbers and data sets, producing insightful visualizations without the need for prompt engineering. This proficiency in creatively rendering data echoes the power of platforms like Wolfram, introducing a new era of ease and efficiency in data comprehension.Here’s an example from Justin Fineberg’s TikTok: Click hereFile ConversionThe ChatGPT Code Interpreter extends its versatility into the realm of file conversion. This feature provides a simple solution to the often cumbersome task of converting files from one format to another. Its impressive functionality ranges from changing audio file formats, like MP3 to WAV, to converting an image into a text file. This capability paves the way for more accessible content transformation, such as easily convert PDF documents into editable text files.Here’s an example from Twitter user Riley Goodside: Click herePython Code ExecutionWhat sets the ChatGPT Code Interpreter plugin apart is its prowess in executing Python code within a sandboxed, firewalled execution environment. This essentially means that all the data visualizations are generated using Python, thereby lending the plugin an additional layer of power and versatility.As the plugin is still in its alpha stage, gaining access currently involves joining a waitlist, and  OpenAI has not publicly stated when a large-scale rollout will take place. However, those eager to explore its features have an alternative route via Discord's GPT Assistant bot, which already incorporates the Code Interpreter plugin to enhance its features and functionalities.This revolutionary plugin is not merely an advanced code interpreter; it's a complete tool that uses Python to generate code from natural language input and run it. The results are then presented within the dialogue box. The chatbot’s functionality extends to solving mathematical problems, data analysis and visualization, and file conversion, with an adeptness in these domains that rivals experienced coders.Beyond its immediate capabilities, the ChatGPT Code Interpreter plugin has broader implications for the programming and data analysis industry. It is reminiscent of Github Copilot X in its design, aimed at making workflows more creative and efficient. For instance, when asked to plot a function, the plugin not only generates the graph but also offers the option to 'show work', revealing the exact code it created and executed to generate the graph.The accessibility and user-friendliness of the plugin are expected to democratize the coding landscape, opening up the world of programming to a wider audience. This feature holds tremendous potential to accelerate collaborations, allowing technical and non-technical team members to work together more effectively on data analysis projects.Practical use cases for the ChatGPT Code Interpreter extend beyond the realm of programming, spanning various industries. Marketing teams, for instance, can leverage their capabilities to analyze customer data, segment audiences, and create targeted campaigns. Finance teams can utilize the plugin for tasks like financial modeling, forecasting, and risk analysis. Similarly, human resource teams can use it to analyze employee data, identify performance trends, and make data-driven hiring decisions. Even the healthcare sector stands to benefit, as the tool can analyze patient data, identify patterns in health outcomes, and thus enhance patient care.Accessing ChatGPT Code InterpreterIf you’re selected from the waitlist, here’s a step-by-step guide on how to install the plugin:Ensure you're a ChatGPT Plus subscriber, paying the $20 monthly fee.Log into ChatGPT on the OpenAI website.Click on 'Settings', then the three-dot menu next to your login name.In the 'Beta features' menu, enable 'Plug-ins'. For web browsing access, enable that too.Close the menu, find the language model selector, and choose 'Plugin Store' from the drop-down.Click 'All plug-ins', find 'Code Interpreter' in the list and install it.Now, you can interact with ChatGPT using the Code Interpreter plug-in.SummaryThe ChatGPT Code Interpreter plugin presents a transformative approach to programming and data analysis, automating code generation, facilitating data exploration, and improving code quality. This plugin empowers users to derive more value from their data, aiding in the formulation of strategic insights. As AI continues to evolve, tools like the ChatGPT Code Interpreter will undoubtedly play an instrumental role in shaping the future of data interaction and understanding, ultimately revolutionizing the landscape of data analysis.Author BioJulian Melanson is one of the founders of Leap Year Learning. Leap Year Learning is a cutting-edge online school that specializes in teaching creative disciplines and integrating AI tools. We believe that creativity and AI are the keys to a successful future and our courses help equip students with the skills they need to succeed in a continuously evolving world. Our seasoned instructors bring real-world experience to the virtual classroom and our interactive lessons help students reinforce their learning with hands-on activities.No matter your background, from beginners to experts, hobbyists to professionals, Leap Year Learning is here to bring in the future of creativity, productivity, and learning!
Read more
  • 0
  • 0
  • 5087

article-image-creating-cicd-pipelines-effortlessly-using-chatgpt
Sagar Lad
22 Jun 2023
5 min read
Save for later

Creating CI/CD Pipelines Effortlessly using ChatGPT

Sagar Lad
22 Jun 2023
5 min read
 In the fast-paced world of software development, continuous integration and continuous delivery (CI/CD) pipelines have become crucial for efficient and reliable software deployment. However, building and maintaining these pipelines can be a daunting task, requiring extensive knowledge and expertise. But what if there was a way to simplify this process and make it more accessible to developers of all skill levels? Enter ChatGPT, the groundbreaking language model developed by OpenAI. In this article, we explore how ChatGPT can effortlessly guide developers in building robust CI/CD pipelines, revolutionizing the way software is delivered.What is DevOps?DevOps team is a combination of the Development team and Operations team working together in order to accelerate the time to market and quality of the software development. DevOps way of working is more a shift in the mindset which has a major effect on the team and organization’s way of working. With the DevOps mindset, there are no silos between the development and operations teams. DevOps team mainly focuses on the automation to increase the reliability by enabling continuous integration, and continuous deployment pipelines.Image 1 : DevOps Lifecycle DevOps Lifecycle mainly consists of setting up an automated and collaborative environment to discover, plan, build, and test the artefacts. Once the artefacts are downloaded, they can be deployed to their respective environments. Throughout the DevOps lifecycle, the complete team has to work closely to maintain the alignment, velocity, and quality of the deliverables.DevOps implementation mainly involves below activities :Discover productAn iterative approach for agile planningBuild pipelines for branching, merging, and workflows for the development processAutomated Testing using CI pipelines Deployment using release pipelinesOperationalize and manage end-to-end IT deliveryContinuous monitoring of the deployed softwareContinuous feedback and improvements for future releaseChatGPT for DevOpsAutomation: DevOps Tools like Jenkins, Ansible, Terraform, etc provide workflow automation. On the other hand, we can use chatGPT to automate the below DevOps activities that require manual intervention.Automation Testing: Testing scenarios and automated testing can be enabled using the chatGPT as a part of the continuous build pipeline.Release documentation: Maintaining documentation for each feature is a manual and tedious task. With the help of chatGPT, we can write code in any language to create an automated documentation for each release. With ChatGPT, we can generate code for bicep templates and YAML for Azure DevOps, Terraform , Jenkins, and Lambda code for the DevOps activities.  DevSecOps Implementation: Security is a critical factor in order to develop any software. ChatGPT can be used to monitor cloud resources, manage and detect security vulnerabilities , and scan for networking issues, open ports, database, and storage configurations as per the industry standards and requirements.Continuous Monitoring: Customised dashboard for monitoring is a key metric for proactive monitoring and taking data-driven decisions. We can create a dashboard using the chatGPT to generate code including a variety of components such as charts, graphs, and tables.Let’s now ask chatGPT for each of these steps to create a DevOps process flow for a software project. The first step is to set up the Azure DevOps repository structure including the branching policies, and pre, and post-deployment approval:Image 2: Azure Devop Repo structure & branching policiesAs you can see, a recommendation from ChatGPT is to create a new Azure DevOps repository with proper naming conventions. In order to set up the branching policies, we need to configure the build validations, set up the reviewers, status check, and work item linking in the Azure Boards.Image 3: Azure DevOps Continuous Integration PipelineHere, we have requested chatGPT to create a YAML continuous integration build pipeline in Azure DevOps including the code quality checks and testing. ChatGPT provides us with a YAML pipeline that has multiple stages - one for sonarqube, one for fortify code quality checks, one for automation testing, and one to download the artefacts. Once the CI pipeline is ready, let’s ask ChatGPT to build IaC(Infrastructure as a Code Pipeline) to deploy Azure services like Azure Data Factory and Azure Databricks.Image 4 : Azure DevOps Continuous Deployment PipelinesHere, we can see the step-by-step process to build the continuous deployment pipelines which are using shell script to deploy the Azure Data Factory and Azure CLI to deploy the Azure Databricks. This pipeline also has an integration with the branches to include and it is using variable groups to create a generic pipeline. Let’s see how we can build monitoring dashboards using chatGPT:ConclusionSo chatGPT is not a threat to the DevOps engineers but it will boost up productivity by embracing the technology to set up and implement the DevOps way of working.  In order to get the desired results, detailed prompt input should be provided to generate content from chatGPT to meet the expectations.Author BioSagar Lad is a Cloud Data Solution Architect with a leading organization and has deep expertise in designing and building Enterprise-grade Intelligent Azure Data and Analytics Solutions. He is a published author, content writer, Microsoft Certified Trainer, and C# Corner MVP.Link - Medium , Amazon , LinkedIn
Read more
  • 0
  • 0
  • 12518
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-creating-essay-generation-methods-with-chatgpt-api
Martin Yanev
22 Jun 2023
11 min read
Save for later

Creating Essay Generation Methods with ChatGPT API

Martin Yanev
22 Jun 2023
11 min read
This article is an excerpt from the book, Building AI Applications with ChatGPT API, by Martin Yanev. This book will help you master ChatGPT, Whisper, and DALL-E APIs by building nine innovative AI projectsIn this section, we will dive into the implementation of the key functions within the essay generator application. These functions are responsible for generating the essay based on user input and saving the generated essay to a file. By understanding the code, you will be able to grasp the inner workings of the application and gain insight into how the essay generation and saving processes are accomplished.We will begin by exploring the generate_essay() function. This function will retrieve the topic entered by the user from the input field. It will then set the engine type for the OpenAI API, create a prompt using the topic, and make a request to the OpenAI API for essay generation. The response received from the API will contain the generated essay, which will be extracted and displayed in the essay output area of the application. To add that functionality, simply remove the pass placeholder and follow the code below.def generate_essay(self): topic = self.topic_input.text()    length = 500    engine = "text-davinci-003"    prompt = f"Write an {length/1.5} words essay on the following topic: {topic} \n\n"    response = openai.Completion.create(engine=engine, prompt=prompt, max_tokens=length)    essay = response.choices[0].text    self.essay_output.setText(essay)Here, we retrieve the topic entered by the user from the topic_input QLineEdit widget and assign it to the topic variable using the text() method. This captures the user's chosen topic for the essay. For now, we can define the length variable and set it to 500. This indicates the desired length of the generated essay. We will modify this value later by adding a dropdown menu with different token sizes to generate essays of different lengths.We can also specify the engine used for the OpenAI API to be text-davinci-003, which will generate the essay. You can adjust this value to utilize different language models or versions based on your requirements. We can also create the prompt variable, which is a string containing the prompt for the essay generation.It is constructed by concatenating the text Write a {length/1.5} essay on the following topic: where the length/1.5 variable specifies how many words our essay should be. We need to divide the tokens number by 1.5, as 1 word in English represents about 1.5 tokes. After specifying the instructions, we can pass the topic variable to the prompt. This prompt serves as the initial input for the essay generation process and provides context for the generated essay.Once all variables are defined, we make a request to the ChatGPT API with the specified engine, prompt, and the maximum number of tokens (in this case, 500). The API processes the prompt and generates a response, which is stored in the response variable. From the response, we extract the generated essay by accessing the text attribute of the first choice. This represents the generated text of the essay. Finally, we can pass the AI response to the essay_output, displaying it in the user interface for the user to read and interact with.Moving on, we will examine the save_essay() function. This function will retrieve the topic and the generated essay. It will utilize the docx library to create a new Word document and add the final essay to the document. The document will then be saved with the filename based on the provided topic, resulting in a Word document that contains the generated essay. After removing the pass keyword, you can implement the described functionality using the code snippet below.def save_essay(self):    topic = self.topic_input.text()    final_text = self.essay_output.toPlainText()    document = docx.Document()    document.add_paragraph(final_text)    document.save(topic + ".docx")Here we retrieve the text entered in the topic_input widget and assign it to the topic variable using the text() method. This captures the topic entered by the user, which will be used as the filename for the saved essay. Next, we use the toPlainText() method on the essay_output widget to retrieve the generated essay text and assign it to the final_text variable. This ensures that the user can edit the ChatGPT-generated essay before saving it. By capturing the topic and the final text, we are now equipped to proceed with the necessary steps to save the essay to a file.We can now use the docx library to create a new Word document by calling docx.Document(), which initializes an empty document. We then add a paragraph to the document by using the add_paragraph() method and passing in the final_text variable, which contains the generated essay text. This adds the generated essay as a paragraph to the document. We can now save the document by calling document.save() and providing a filename constructed by concatenating the topic variable, which represents the topic entered by the user. This saves the document as a Word file with the specified filename.You can now test your Essay Generator by running the code in PyCharm and generating an essay following the steps below (see Figure 8.3):Enter a topic: Write an essay topic of your choice in the Topic Input field. For this example, I have chosen the topic “Ancient Egypt”.Generate Essay: Perform a single click on the Generate Essay button. The app will reach ChatGPT API and within a few seconds, you will have your essay displayed inside the Essay Output field.Edit the Essay: You can edit the essay generated by the Artificial Intelligence before saving it.Save: Perform a single click on the Save button. This action will save the edited essay to a Word document utilizing the save_essay() method. The Word document will be saved in the root directory of your project.Figure 8.3: Essay Generator creating an “Ancient Egypt” essayOnce the essay has been saved to a Word document, you can reshare it with your peers, submit it as a school assignment or use any Word styling options on it.This section discussed the implementation of key functions in our essay generator application using the ChatGPT API. We built the generate_essay() method that retrieved the user’s topic input and sent a request to the ChatGPT API for generating an AI essay. We also developed the save_essay() method that saved the generated essay in a Word document.In the next section, we will introduce additional functionality to the essay generator application. Specifically, we will allow the user to change the number of AI tokens used for generating the essay.Controlling the ChatGPT API TokensIn this section, we will explore how to enhance the functionality of the essay generator application by allowing users to have control over the number of tokens used when communicating with ChatGPT. By enabling this feature, users will be able to generate essays of different lengths, tailored to their specific needs or preferences. Currently, our application has a fixed value of 500 tokens, but we will modify it to include a dropdown menu that provides different options for token sizes.To implement this functionality, we will make use of a dropdown menu that presents users with a selection of token length options. By selecting a specific value from the dropdown, users can indicate their desired length for the generated essay. We will integrate this feature seamlessly into the existing application, empowering users to customize their essay-generation experience.Let's delve into the code snippet that will enable users to control the token length. You can add that code inside the initUI() methods, just under the essay_output resizing:self.essay_output.resize(1100, 500) length_label = QLabel('Select Essay Length:', self) length_label.move(327, 40) self.length_dropdown = QComboBox(self) self.length_dropdown.move(320, 60) self.length_dropdown.addItems(["500", "1000", "2000", "3000", "4000"])The code above introduces a QLabel, length_label, which serves as a visual indication for the purpose of the dropdown menu. It displays the text Select Essay Length to inform users about the functionality.Next, we create a QcomboBox length_dropdown which provides users with a dropdown menu to choose the desired token length. It is positioned below the length_label using the move() method. The addItems() function is then used to populate the dropdown menu with a list of token length options, ranging from 500 to 4000 tokens. Users can select their preferred length from this list.The final step is to implement the functionality that allows users to control the number of tokens used when generating the essay, we need to modify the generate_essay() function. The modified code should be the following:def generate_essay(self):    topic = self.topic_input.text()    length = int(self.length_dropdown.currentText())    engine = "text-davinci-003"    prompt = f"Write an {length/1.5} words essay on the following topic: {topic} \n\n"    response = openai.Completion.create(engine=engine, prompt=prompt, max_tokens=length)    essay = response.choices[0].text   self.essay_output.setText(essay)In the modified code, the length variable is updated to retrieve the selected token length from the length_dropdown dropdown menu. The currentText() method is used to obtain the currently selected option as a string, which is then converted to an integer using the int() function. This allows the chosen token length to be assigned to the length variable dynamically.By making this modification, the generate_essay() the function will utilize the user-selected token length when making the request to the ChatGPT API for essay generation. This ensures that the generated essay will have the desired length specified by the user through the dropdown menu.We can now click on the Run button in PyCharm and verify that the Dropdown menu works properly. As shown in Figure 8.4, a click on the Dropdown menu will show users all options specified by the addItems() function.Figure 8.4: Controlling essay length.The user will be able to choose a token amount between 500 and 4000. Now you can select the 4000 tokens option, resulting in a longer length of the generated essay. We can follow the steps from our previous example and verify that the ChatGPT API generates a longer essay for “Ancient Egypt” when the number of tokens is increased from 500 to 4000.This is how you can enhance the functionality of an essay generator application by allowing users to control the number of tokens used when communicating with ChatGPT. By selecting a specific value from the dropdown menu, users can now indicate their desired length for the generated essay. We achieved that by using the QComboBox to create the dropdown menu itself. The modified generate_essay() method retrieved the selected token length from the dropdown menu and dynamically assigned it to the length variable.SummaryIn conclusion, leveraging the capabilities of ChatGPT API to enhance essay generation opens up a world of interactive creativity. By incorporating practical examples and step-by-step instructions, we have explored how to generate essay-generating elements and make them interact seamlessly with ChatGPT. This powerful combination allows for the production of compelling, coherent, and engaging essays effortlessly. With the ever-evolving potential of AI, the future of essay generation holds immense possibilities. By embracing these techniques, writers and researchers can unlock their full creative potential and revolutionize the way we generate written content.Author BioMartin Yanev is an experienced Software Engineer who has worked in the aerospace and medical industries for over 8 years. He specializes in developing and integrating software solutions for air traffic control and chromatography systems. Martin is a well-respected instructor with over 280,000 students worldwide, and he is skilled in using frameworks like Flask, Django, Pytest, and TensorFlow. He is an expert in building, training, and fine-tuning AI systems with the full range of OpenAI APIs. Martin has dual master's degrees in Aerospace Systems and Software Engineering, which demonstrates his commitment to both practical and theoretical aspects of the industry.LinkedInUdemy
Read more
  • 0
  • 0
  • 5548

article-image-exploring-openai-chatgpt-as-a-researcher-a-writer-and-a-software-user
Urszula Witherell
22 Jun 2023
6 min read
Save for later

Exploring OpenAI ChatGPT as a Researcher, a Writer and a Software User

Urszula Witherell
22 Jun 2023
6 min read
Artificial Intelligence is now a hot topic. The concept is not that new. In translations from one language to another, it was used since the 1960s to prepare rough drafts with the idea that the text will be refined by human editors. We interviewed Urszula Witherell, the author of the book Adobe Acrobat Ninja for her perspectives on using AI, specifically freely available ChatGPT: as a Reader, a Writer, and a Software User. What is your experience using ChatGPT as a Reader/Researcher?I am a curious person, and my mind constantly questions where and why. I love exploring new ideas, learning about people living in different cultures, and exploring different perspectives on topics that matter to me. AI as a research tool is wonderful, although very quickly I learned about its limitations. A simple test was to search for my own name. It knew nothing. My ego was not bruised as I am not a celebrity or want to be one. On the other hand, a simple search on Google very quickly found my name, my address, my family members, and everything I did online going back at least a decade. ChatGPT insisted that it knew nothing about me since its training ended in September 2021, 2 years ago. Similarly, when asked about a company website that has been active for at least 20 years it gave this reply: “I apologize for the confusion, but as an AI language model, I don't have the capability to browse the internet or visit specific websites. My responses are based on pre-existing knowledge up until September 2021. Therefore, I'm unable to provide a real-time description or analysis of the website “ or “Without specific information, I can't provide details about the website's content, purpose, or any other features it may have. It's always a good idea to visit the website directly to gather accurate and up-to-date information.” This made me ask a question how is ChatGPT trained? Where does the data come from?Once I manually copied information from the website and asked ChatGPT to generate a new response. It expanded on dry data and formulated a nice description of the website content.Image 1: ChatGPT cannot figure out what is the content of the websiteFigure 2: ChatGPT expanded the descriptionWhen I asked for descriptions of cities, landmarks, or public figures ChatGPT did provide sufficient information in full sentences with rich vocabulary. When asked to regenerate responses it provided fresh and even better-formulated descriptions. Again, not knowing where the data for AI come from, I depended on what I already knew about the locations to evaluate the accuracy of the response. It made me think about the famous quote: “Trust but verify”. So, compare results from multiple other sources to get the results that you can trust. Asked about liking a city, this is what I got: “As an AI language model, I don't have personal opinions or emotions, so I don't have the ability to like or dislike anything. However, I can provide information.” Not quite a chatty, opinionated friend, at least not yet.What is your experience using ChatGPT as a Writer?I think this is where the AI can be very helpful as it can be a thesaurus, spell-checker, and grammar checker all at once. It can re-write sentences; from just a rough draft it can expand descriptions and literally be your personal assistant during the writing process. You can see this in the screenshot example. As a bilingual person I often wonder how to express ideas in Polish for my friends in Poland. I discovered that translations of English text to Polish are very good. Grammar is correct, vocabulary is rich enough and sentences are full and mostly sound natural. Much better than what I had experienced in the past using Google Translate, when translated text needed a real human translator to be understood by a Polish-only speaking person (my parents). Of course, there are some flaws, such as the assumption of the male gender as an author. In Polish all nouns are assigned one of three genders: feminine (yes, ladies first), masculine and neutral. This is where corrections were needed. Additionally, since an example to be translated was a chapter of the software guide, it used many English terms in Polish grammatical form. My English teacher would faint at such a transgression, as we were always taught to use native expressions in place of foreign adoptions. But since technology vocabulary originated in English, so the rest of the world must just deal with it. I can live with that. I will depend on ChatGPT as a writer from now on. Definitely thumbs up!What about the perspective of a software user?Well, this is where the results vary, and it simply depends on what you are looking for. I tested a question about authoring Adobe InDesign documents for PDF accessibility and compliance with Section 508 requirements in the USA. ChatGPT provided a very detailed, step-by-step description of how to proceed, but in responses regenerated multiple times it missed the most advanced method when automated alt-text tags can be generated from image metadata using Object Styles. So again, AI helped, but I needed to know already what I could possibly do. Great help from a writer’s perspective, but not so good for someone who is exploring more advanced software functions.It is exciting to explore new platforms and technology. Like any new frontier, it brings excitement but also fear. And again, I am reminded that we as humans have not changed at all. Our toys changed, and we became more sophisticated and powerful, but we continue to need guidance on how to use yet another newly found power and knowledge. History is not a strong enough deterrent from misuse.SummaryIn conclusion, the interview with Urszula sheds light on the versatile applications of ChatGPT in the roles of a researcher, writer, and software engineer. Urszula highlights the efficiency and creativity enabled by ChatGPT, allowing her to tackle complex research problems, generate high-quality content, and even assist in software development tasks. Through her experiences, we gain insights into the immense potential of ChatGPT as a powerful tool for augmenting productivity and innovation across various domains. As the technology continues to evolve, researchers and professionals can leverage ChatGPT to unlock new possibilities and achieve greater efficiency in their work.Author BioUrszula is an expert graphic designer, software instructor, and consultant. As an instructor, she taught thousands of Adobe software users in government agencies and private corporations. Her easy-going and effective presentation style of complex features earned her many loyal clients. Her consulting work related to PDF included creating templates, editing files, and providing recommendations on the document production process. The final goal was to ensure that each publication met the highest publishing and accessibility standards, which was achieved successfully. Urszula also designed training curriculum and reference materials on proper document construction prior to conversion to PDF in a relevant authoring software, such as MS Word, Adobe InDesign, and FrameMaker.Author of the book: Adobe Acrobat Ninja
Read more
  • 0
  • 0
  • 1850

article-image-help-chatgpt-improve-with-knowledge-graphs
Maxime Labonne
17 Jun 2023
9 min read
Save for later

Help ChatGPT Improve with Knowledge Graphs

Maxime Labonne
17 Jun 2023
9 min read
ChatGPT has shown impressive capabilities in processing and generating human-like text. However, it is not without its imperfections. A primary concern is the model's propensity to produce either inaccurate or obsolete answers, often called "hallucinations."The New York Times recently highlighted this issue in their article, "Here's What Happens When Your Lawyer Uses ChatGPT." It presents a lawsuit where a lawyer leaned heavily on ChatGPT to assist in preparing a court filing for a client suing an airline. The model generated fictional court decisions to back its arguments, which didn't go unnoticed. This incident underscores the need for solutions to ground AI models like ChatGPT and improve their performance.To address this, we propose an approach that focuses on augmenting ChatGPT using a knowledge graph. This method aims to provide a structured context, ensuring the model outputs are accurate but also relevant and up-to-date. By bridging the gap between the unstructured textual world of ChatGPT and the structured clarity of knowledge graphs, we strive to enhance the effectiveness and reliability of AI language models.All the code used in this article is available on Google Colab and on GitHub.What is a knowledge graph?A knowledge graph is a structured format of knowledge representation, usually composed of entities and relationships. In a typical knowledge graph, entities are the nodes, and the relationships between them are the edges. The graph-based representation allows complex relationships to be modeled in a way that's intuitive and closer to human understanding. Here is a simple illustration of a knowledge graph: Source: Wikipedia. CC BY-SA 4.0 Google has been using knowledge graphs since 2012 to provide additional contextual information and sources. The structured representation of data offers a new dimension of context to the AI model, grounding it in validated knowledge.Applying Knowledge Graphs to Improve ChatGPTA crucial limitation of ChatGPT is its lack of real-time information updates. Since the model was last trained using data up until 2021, it doesn't have access to events, data, or context after that year. This leads to ChatGPT having outdated or incomplete information about events, technological advancements, or other critical happenings post-2021.Let's illustrate this limitation by asking ChatGPT about a recent event, When did Apple announce the Vision Pro?. Given the model's knowledge cutoff in 2021, we would expect it to be unaware of this announcement, which happened in 2023.!pip install -q openai langchain import os import openai os.environ['OPENAI_API_KEY'] = "your OpenAI key" openai.api_key = os.environ['OPENAI_API_KEY'] question = "When did apple announced the Vision Pro?" completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", temperature=0, messages=[{"role": "user", "content": question}]) print(completion["choices"][0]["message"]["content"]) As an AI language model, I do not have access to current events or real-time information. However, as of my last training data, Apple has not announced any product called "Vision Pro." It is possible that this product does not exist or has not been announced yet. As expected, ChatGPT is unable to provide the correct answer due to its training data limitations. This clearly highlights the need for constant updates to the model's knowledge base, which can be addressed by integrating it with a continuously updated knowledge graph.By implementing such a knowledge graph, we can ensure that ChatGPT can provide accurate, current, and reliable information, effectively addressing the "hallucination" issues as well as the knowledge cutoff limitations.Sentence-Level Knowledge GraphsTo demonstrate this, we'll use the LangChain library, a powerful tool designed for building frameworks around large language models. The library includes a component called GraphIndexCreator, which can parse a sentence and create a knowledge graph. This component is currently limited and cannot process long corpus of text, but it serves as a perfect starting point for our experiment.Let's start with a straightforward sentence: "Apple announced the Vision Pro in 2023."from langchain.llms import OpenAI from langchain.indexes import GraphIndexCreator from langchain.chains import GraphQAChain from langchain.prompts import PromptTemplate text = "Apple announced the Vision Pro in 2023." index_creator = GraphIndexCreator(llm=OpenAI(temperature=0)) graph = index_creator.from_text(text) graph.get_triples()[('Apple', 'Vision Pro', 'announced'), ('Vision Pro', '2023', 'was announced in')] By feeding this sentence into the GraphIndexCreator, it creates a knowledge graph by identifying the sentence's entities and relationships, forming triplets of information in the format of (source node, relation, and target node). However, the GraphIndexCreator might get confused with the relations and target nodes due to the inherent complexity of natural language.Even though it's a tiny graph based on a single sentence, we can represent it visually using popular Python libraries such as matplotlib and networkx.import networkx as nx import matplotlib.pyplot as plt # Create graph G = nx.DiGraph() G.add_edges_from((source, target, {'relation': relation}) for source, relation, target in graph.get_triples()) # Plot the graph plt.figure(figsize=(8,5), dpi=300) pos = nx.spring_layout(G, k=3, seed=0) nx.draw_networkx_nodes(G, pos, node_size=2000) nx.draw_networkx_edges(G, pos, edge_color='gray') nx.draw_networkx_labels(G, pos, font_size=12) edge_labels = nx.get_edge_attributes(G, 'relation') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=10) # Display the plot plt.axis('off') plt.show() Image 2: Visual Pro Graph Now, let's enhance ChatGPT using the knowledge graph. We will use another component of the LangChain library, GraphQAChain, to this end.Initializing the GraphQAChain, we input the same question we asked earlier, "When did Apple announce the Vision Pro?". This time, ChatGPT leverages the knowledge graph we've just built.chain = GraphQAChain.from_llm(OpenAI(temperature=0), graph=graph, verbose=True) chain.run(question)> Entering new GraphQAChain chain...Entities Extracted: Apple, Vision ProFull Context:Apple announced Vision ProVision Pro was announced in 2023> Finished chain. Apple announced Vision Pro in 2023.This time, ChatGPT was able to output the correct information! The good thing is that we don't need any parser to build our knowledge graphs and can use existing ones. In the next experiment, let's try to use a bigger graph and see if it's still as performant.Bigger Knowledge GraphsIn this experiment, we manually create this more complex graph by supplying a list of triplets to the GraphIndexCreator object using the add_triple() method. Each triplet represents a distinct piece of knowledge related to Apple, such as the products it has created or where it is located.from langchain.graphs.networkx_graph import KnowledgeTriple # Knowledge graph kg = [ ('Apple', 'is', 'Company'), ('Apple', 'created', 'iMac'), ('Apple', 'created', 'iPhone'), ('Apple', 'created', 'Apple Watch'), ('Apple', 'created', 'Vision Pro'), ('Apple', 'developed', 'macOS'), ('Apple', 'developed', 'iOS'), ('Apple', 'developed', 'watchOS'), ('Apple', 'is located in', 'USA'), ('Steve Jobs', 'co-founded', 'Apple'), ('Steve Wozniak', 'co-founded', 'Apple'), ('Tim Cook', 'is the CEO of', 'Apple'), ('iOS', 'runs on', 'iPhone'), ('macOS', 'runs on', 'iMac'), ('watchOS', 'runs on', 'Apple Watch'), ('Apple', 'was founded in', '1976'), ('Apple', 'owns', 'App Store'), ('App Store', 'sells', 'iOS apps'), ('iPhone', 'announced in', '2007'), ('iMac', 'announced in', '1998'), ('Apple Watch', 'announced in', '2014'), ('Vision Pro', 'announced in', '2023'), ] graph = index_creator.from_text('') for (node1, relation, node2) in kg: graph.add_triple(KnowledgeTriple(node1, relation, node2))Although we could include many more triplets (real-world knowledge graphs often encompass millions of nodes), the size of our graph for this demonstration is sufficient. When visualized, this more extensive knowledge graph exhibits greater complexity and a richer depiction of information.# Create directed graph G = nx.DiGraph() for node1, relation, node2 in kg: G.add_edge(node1, node2, label=relation) # Plot the graph plt.figure(figsize=(25, 25), dpi=300) pos = nx.spring_layout(G, k=2, iterations=50, seed=0) nx.draw_networkx_nodes(G, pos, node_size=5000) nx.draw_networkx_edges(G, pos, edge_color='gray', edgelist=G.edges(), width=2) nx.draw_networkx_labels(G, pos, font_size=12) edge_labels = nx.get_edge_attributes(G, 'label') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=12) # Display the plot plt.axis('off') plt.show()Image 4: Larger GraphWith this larger graph, we once again ask ChatGPT the question: "When did Apple announce the Vision Pro?" Leveraging the GraphQAChain object, ChatGPT processes the information embedded in the knowledge graph.chain = GraphQAChain.from_llm(OpenAI(temperature=0), graph=graph, verbose=True) chain.run(question)> Entering new GraphQAChain chain...Entities Extracted: Apple, Vision ProFull Context:Apple is CompanyApple created iMacApple created iPhoneApple created Apple WatchApple created Vision ProApple developed macOSApple developed iOSApple developed watchOSApple is located in USAApple was founded in 1976Apple owns App StoreVision Pro announced in 2023> Finished chain. Apple announced the Vision Pro in 2023.ChatGPT successfully extracts the correct information from the more expansive knowledge graph. This result demonstrates that our model can not only scale to larger graphs but can also efficiently navigate a more extensive knowledge base.The possibilities for implementing larger and more diverse knowledge graphs are practically endless. They can be populated with data from various sources, such as legal documents, code documentation, scientific literature, and more, enhancing the AI's understanding and response accuracy across multiple domains. The integration of ChatGPT and knowledge graphs thus holds immense promise for future AI development.ConclusionAs seen in our experiments, knowledge graphs can significantly aid in grounding and improving ChatGPT's outputs. A key challenge with large knowledge graphs is finding connections between distant nodes, a problem often referred to as graph completion. Successfully addressing this issue would allow ChatGPT to make insightful connections and propose new ideas based on the information available in the knowledge graph.However, the process of integrating knowledge graphs into language models like ChatGPT is still an evolving field. To further explore the various applications and delve into the details of implementing knowledge graphs, consider the book "Hands-On Graph Neural Networks Using Python", which provides a comprehensive guide on this subject. Through this type of research and experimentation, we can continuously improve AI's ability to understand and generate text, moving us closer to more reliable and grounded AI models.Author BioMaxime Labonne is a senior applied researcher at J.P. Morgan with a Ph.D. in machine learning and cyber security from the Polytechnic Institute of Paris.During his Ph.D., Maxime worked on developing machine learning algorithms for anomaly detection in computer networks. He then joined the AI Connectivity Lab at Airbus, where he applied his expertise in machine learning to improve the security and performance of computer networks. He then joined J.P. Morgan, where he develops techniques to solve a variety of challenging problems in finance and other domains.In addition to his research work, Maxime is passionate about sharing his knowledge and experience with others through Twitter (@maximelabonne) and his personal blog.
Read more
  • 0
  • 0
  • 6478

article-image-the-little-known-benefits-of-creating-architecture-design-with-chatgpt
Sagar Lad
15 Jun 2023
5 min read
Save for later

The Little-Known Benefits of Creating Architecture Design with ChatGPT

Sagar Lad
15 Jun 2023
5 min read
Software architecture acts as a blueprint for the system, using abstraction to control the system's complexity and establish inter-component communication. In the ever-evolving landscape of software architecture, a groundbreaking innovation has emerged, reshaping the way developers design and optimize their systems. Enter ChatGPT, an advanced language model that has revolutionized the field with its remarkable capabilities. With its deep understanding of natural language, ChatGPT is unlocking new horizons in software architecture. From streamlining development processes to enhancing user interactions, this article delves into the transformative potential of ChatGPT, exploring how it is reshaping the very foundations of software architecture as we know it.In this piece, we'll examine the value of software architecture and how chatGPT may help us build it.  Architecture Design with ChatGPTThe entire design of the software, its elements, and its behavior are represented by the software system architect. In a nutshell, it is a visual representation of how software applications are made by connecting their many components. The following are examples of software architecture activities: Implementation Details: It could be architectural artifacts, source code, documentation, repository, etc.Implementation Design decisions: It includes options for technology (cloud or on-premises), architectural style (monolithic or distributed), storage (AWS S3, Azure Blob, ADLS Gen2, etc.), ingestion pattern (batch or real-time streaming pattern), and more.Infrastructure Considerations: Deployment Choices, Component Configurations, etc.Let’s understand in detail about the process of software architecture.Requirement Gathering: Any project should begin with functional and non-functional requirements since they will determine how to create the software architecture and how to prepare the finished product in accordance with the needs of the stakeholders.Create a Helicopter view of the solution: Using the mind map, provide a high-level overview of the system's constituent parts. It is a useful method for capturing your requirements as a diagram.Refine functional and non-functional requirements: Examine the non-functional needs in terms of performance, security, cost-effectiveness, etc. once you have thoroughly refined the functional requirements to comprehend the overall functioning of the program.Design each component in detail: Start with creating the platform's infrastructure and creating the application components while taking into account the functional and non-functional needs.Create a phase-wise approach for the implementation: Once the infrastructure and application implementation design considerations are clear, begin preparing deliverables for a phased rollout. It should include the state of architecture as it is today, architecture in transition, and architecture in the future. Make a visual representation of the application and infrastructure, taking into account networking, security, and interconnection issues.Below are the best practices that can be followed while designing the software architecture for any application:Design your application considering the best and worst-case scenarioDesign your application which should be able to scale up and scale downCreate loosely coupled architecture design for the smooth functioning of the system Create a multi-thread processing to speed up the processing for batch and real-time streaming implementationDesign your application with 7 layers of security implementationMake a choice to store your dataNow, Let’s use ChatGPT to create a software architecture for an application. Our goal is to create a data mesh architecture for the retail industry using the azure technology. The major requirement is also to define and capture data architecture requirements.Image 1 - Part 1, Data mesh responseImage 2 - Part 2, Data mesh responseImage 3- Part 3, Data mesh responseImage 4- Part 4, Data mesh response ChatGPT first offers suggestions for a group of Azure services to be used to implement the batch and real-time streaming patterns after receiving input from the user. The principles for implementing a data mesh architecture are then provided, including domain-driven data ownership, data-driven products, self-service data infrastructure, and data governance, including data discovery and monitoring.Let’s check with chatGPT on how the networking setup should be done for these Azure services:Image 5: Part 1, Networking responseImage 6: Part 2 Networking response Image 7: Part 3 Networking response  The configuration of a VNET, subnet, NSG rules, Azure firewall, VNET peering, VPN gateway, and the private link is advised by chatGPT. These Azure networking components can be used to manage the services' interconnection. Another major requirement to implement data mesh architecture is also to check how domain-specific data will be managed and operationalized for the data mesh architecture. Image 8: Part 1,  Domain-specific Data ManagementImage 9: Part 2,  Domain-specific Data ManagementImage 10: Part 3,  Domain-specific Data ManagementThe goal of chatGPT's proposals is to produce domain-specific cleansed data that end users can utilize directly to extract value from the data. Since these data domain stores are being built by domain experts, they are also in charge of managing, supporting, and operationalizing the data as needed.ConclusionIn this post, we looked in detail at the overall process of software architecture design as well as its sequential process. The best techniques for creating the software architecture for any application were also demonstrated. Later, we used chatGPT to develop a data mesh architecture implementation, complete with networking setup and operationalization, for a retail domain.Author BioSagar Lad is a Cloud Data Solution Architect with a leading organization and has deep expertise in designing and building Enterprise-grade Intelligent Azure Data and Analytics Solutions. He is a published author, content writer, Microsoft Certified Trainer, and C# Corner MVP.Link - Medium , Amazon , LinkedIn  
Read more
  • 0
  • 0
  • 5737
article-image-implementing-azure-ad-protection-with-chatgpt
Steve Miles
15 Jun 2023
8 min read
Save for later

Implementing Azure AD Protection with ChatGPT

Steve Miles
15 Jun 2023
8 min read
IntroductionCybersecurity professionals face numerous challenges daily, from threat detection to incident response. The advent of AI-powered language models, also called Generative AI such as ChatGPT or Google's Bard, has revolutionized how experts approach their tasks. In this tutorial, we will explore how ChatGPT can assist cybersecurity professionals in performing various tasks efficiently and effectively. From analyzing logs and conducting risk assessments to developing incident response strategies, ChatGPT's capabilities can be harnessed to streamline workflows and enhance productivity. In this blog, let's dive into the practical applications and benefits of integrating Generative AI into (cyber)security operations.In this article, we will cover a tutorial on implementing Azure AD Protection with ChatGPT and also cover certain other areas of cybersecurity where GPT can be beneficial.Implementing Azure AD Identity Protection with ChatGPTAzure AD Identity Protection helps organizations safeguard their Azure Active Directory (Azure AD) identities by detecting and mitigating identity-related risks. In this section, we will explore how ChatGPT can assist in implementing Azure AD Identity Protection through code examples using Python and the Microsoft Graph API.1. Set up the EnvironmentBefore we begin, ensure that you have the following prerequisites in place:Python is installed on your machine.The requests library is installed. You can install it using the following command: pip install requests Azure AD application registered with the appropriate permissions to access Azure AD Identity Protection.2. Acquire Access TokenTo interact with the Microsoft Graph API, we must acquire an access token. Use the following Python code to obtain the access token:```python import requests # Azure AD application details tenant_id = 'YOUR_TENANT_ID' client_id = 'YOUR_CLIENT_ID' client_secret = 'YOUR_CLIENT_SECRET' # Microsoft Graph token endpoint token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token' # Request access token payload = {    'grant_type': 'client_credentials',    'client_id': client_id,    'client_secret': client_secret,    'scope': 'https://graph.microsoft.com/.default' } response = requests.post(token_url, data=payload) if response.status_code == 200:    access_token = response.json()['access_token'] else:    print('Error: Failed to obtain access token') ```Make sure to replace the placeholders with your Azure AD application details.3. Query Azure AD Identity Protection Data with ChatGPTNow that we have the access token, we can leverage ChatGPT to query Azure AD Identity Protection data. Use the following code example to interact with the model and retrieve identity protection insights:```python import openai openai.api_key = 'YOUR_OPENAI_API_KEY' def query_model(question):    response = openai.Completion.create(        engine='text-davinci-003',        prompt=question,        max_tokens=100,        temperature=0.5,        n=1,        stop=None,        temperature=0.5,    )    if response.choices:        return response.choices[0].text.strip()    else:        return None # Example question for querying Azure AD Identity Protection data question = "What are the recent risky sign-ins detected by Azure AD Identity Protection?" # Microsoft Graph API endpoint for risky sign-ins graph_api_url = 'https://graph.microsoft.com/v1.0/identityProtection/riskyUsers' # Send API request with the access token headers = {    'Authorization': f'Bearer {access_token}',    'Content-Type': 'application/json' } response = requests.get(graph_api_url, headers=headers) if response.status_code == 200:    risky_sign_ins = response.json()    # Process the response as needed    # ...    # Query the AI model for insights or recommendations    insights = query_model(question)    if insights:        print("Identity Protection Insights:")        print(insights)    else:        print("Error: Failed to obtain insights from the AI model") else:    print("Error: Failed to retrieve risky sign-ins data from Azure AD Identity Protection") ```Ensure you have appropriate permissions and update the `graph_api_url` with the relevant endpoint for the Azure AD Identity Protection data you want to retrieve.4. Interpret and Utilize InsightsOnce you obtain insights from the AI model, interpret, and utilize them to improve your identity protection practices. This could involve taking proactive measures to mitigate risks, investigating suspicious activities, or implementing additional security measures based on the recommendations provided.Remember to adapt the code examples based on your specific requirements and refer to the Microsoft Graph API documentation for available endpoints and data structures. https://learn.microsoft.com/en-us/graph/Other application areas1. Analyzing Log FilesOne of the most important aspects of cybersecurity is analyzing log files for suspicious activity and potential security breaches. Chat can help businesses automate this process. By importing log files into the model, ChatGPT can quickly identify patterns, anomalies, and potentially malicious activities. This analysis allows cybersecurity professionals to focus on the most important issues, saving valuable time and effort. In addition, ChatGPT's ability to create human-readable summaries of log data simplifies the interpretation and communication of findings for stakeholders.2. Conducting Risk AssessmentsConducting a comprehensive risk assessment is essential to understanding an organization's security posture. ChatGPT can help in this process by using its powerful capabilities to provide context and insights. By interacting with the model, organizations can ask specific questions about potential vulnerabilities, attacks, or best practices related to their risk assessments. ChatGPT's feedback provides knowledge of the organization's security environment and offers real value actionable insights that help businesses identify and prioritize risks and remediation tasks.3. Developing Incident Response StrategiesTime is of the essence in a cybersecurity incident. Generative AI can be an invaluable tool for developing effective incident response mechanisms. By leveraging its natural language processing capabilities, businesses can use ChatGPT to brainstorm and optimize response processes. The model can provide recommendations based on historical data, industry standards, and best practices, helping to create robust and efficient incident response systems. Generative AI can understand and generate human-like responses, making it an ideal virtual security analyst for cybersecurity professionals in high-pressure and time-sensitive situations.4. Automating Routine TasksCybersecurity professionals are often faced with increasing volume and velocity of repetitive and time-consuming tasks, such as vulnerability assessments, log analysis, and updating firewall rules. Generative AI can help automate these routine tasks, freeing experts to focus on complex real-value organizational security challenges. By integrating ChatGPT with existing automation frameworks, organizations can create chatbot-like interfaces that interact with the model to perform pre-defined actions. This approach increases productivity and reduces the risk of human error associated with manual processing.5. Enhancing Threat Intelligence AnalysisEffective threat reporting is essential for proactive cybersecurity defenses. Generative AI can enhance threat intelligence data analysis by extracting insights from a vast repository of security information. By asking about emerging threats, known vulnerabilities, or attack techniques, administrators can gain a deeper understanding of the ongoing threat landscape. ChatGPT's ability to understand complex security issues enhances the accuracy and relevance of threat intelligence reports, contributing to timely decision-making.ConclusionIn conclusion, it is easier and more efficient to implement Azure AD in conjunction with ChatGPT. As the cybersecurity landscape continues to evolve, businesses must embrace AI-powered solutions to stay ahead of malicious actors. Generative AI provides valuable support for various cybersecurity tasks, including log analysis, risk assessment, incident response planning, workflow automation, and threat intelligence analysis capabilities, enabling cybersecurity professionals to streamline their workflow, increase productivity, and make more informed decisions. While it is important to exercise proper judgment and credentials when implementing AI models, integrating Generative AI  such as ChatGPT into the cybersecurity industry offers significant opportunities for businesses to manage their tasks faster, more accurately, and more efficiently.Author BioSteve Miles (SMiles) is the CTO responsible for the tools and technologies selection for the cloud practice of a multi-billion turnover IT distributor based in the UK and Ireland. He is also a multi-cloud and hybrid technology strategist with 20+ years of telco, co-location, hosted data center, hybrid, and multi-cloud infrastructure experience. Steve is an Alibaba Cloud MVP (Most Valuable Professional), as well as being a Microsoft Azure MVP (Most Valuable Professional), and MCT (Microsoft Certified Trainer). Published freelance author for Microsoft technologies and certification guides, as well as an editorial and technical reviewer. Amongst many hybrid/cloud-based certifications, he is Alibaba Cloud Certified, with 20+ Cloud/Hybrid based Microsoft certifications with 14 of those being in Azure.His roles have included network security architect, global solutions architect, public cloud security solutions architect, and Azure practice technical lead. He currently works for a leading multi-cloud distributor based in the UK and Dublin in a cloud and hybrid technology leadership role.His first Microsoft certification was on Windows NT. He is an MCP, MCITP, MCSA, and MCSE for Windows Server and many other Microsoft products. He also holds multiple Microsoft Fundamentals, Associate, Expert, and Specialty certifications in Azure Security, Identity, Network, M365, and D365. He also holds multiple security and networking vendor certifications, as well as PRINCE2 and ITIL, and is associated with industry bodies such as the CIF, ISCA, and IISP.Author of the book: Azure Security Cookbook 
Read more
  • 0
  • 0
  • 5008

article-image-adding-a-chatbot-to-your-portfolio-website-with-chatgpt
Maaike van Putten
13 Jun 2023
10 min read
Save for later

Adding a Chatbot to your Portfolio Website with ChatGPT

Maaike van Putten
13 Jun 2023
10 min read
This article is the second part of a series of articles, please refer to Part 1 for learning how to create a simple portfolio website using ChatGPT in a few stepsIn my last blog, we created a basic personal portfolio app for Olivia with ChatGPT. We’ll use this as the starting point for our next adventure. We’re going to be adding a simple chatbot to our website and configuring it to deal with certain questions. Of course, we could do this ourselves, but let’s see how we can utilize ChatGPT to accomplish this task faster. We’re going to do so with just four prompts! Let’s start with the end result, so you know what we’re working towards:Image 1: End result of the project In the right bottom corner, you see a pop-up that says Ask me anything. Well, you can’t ask it anything, but it can answer the following common questions:Where can I contact you?Can I contact you through Twitter?Can I contact you through LinkedIn?Where can I see your projects? Of course, we can elaborate and do even more with it. We actually wanted to use a free API for this, and we were stuck with CDN options due to the nature of our project. Luckily, we have a digital friend who has some options for us. Let’s see how this started.Deciding which service to use (with ChatGPT)It’s best to be quite descriptive when prompting. This is the first prompt that was used to start implementing the chatbot:I have an existing portfolio site, using HTML/CSS/JS. I'm not using any package managers, so any requirements will have to use a CDN. I want to add a chatbot to my site using a Natural Language AI. If it is possible I'd want the API I'll use to be free. Can you give me some options as to how I can achieve this? ChatGPT had some ideas: Certainly! There are several options available for adding a chatbot with Natural Language AI to your existing portfolio site using HTML/CSS/JS and integrating it through a CDN. Here are a few options that offer free plans: 1. IBM Watson Assistant: IBM Watson Assistant is a powerful NLP service that allows you to build chat bots. You can integrate it into your website using the Watson Assistant API. IBM offers a free tier that provides a limited number of API requests per month. You can find more information and documentation on the IBM Watson Assistant website. 2. Dialogflow (formerly API.AI): Dialogflow, now part of Google Cloud, offers a free tier that allows you to create conversational agents and integrate them into your website. Dialogflow provides a JavaScript library that you can use to communicate with the API. You can find documentation and examples on the Dialogflow website. 3. Wit.ai: Wit.ai, which is also owned by Facebook, provides a free NLP service for building chatbots. You can integrate it into your website using the Wit.ai API. Wit.ai offers a JavaScript SDK that you can use to interact with the API. You can find more information on the Wit.ai website. 4. Microsoft Azure Bot Service: Microsoft Azure Bot Service offers a free tier that allows you to create and deploy chatbots. You can use the Bot Service REST API to communicate with your bot from your website. Microsoft provides documentation and examples on its Azure Bot Service website. Remember to review the terms and limitations of the free plans for each service to ensure they meet your requirements. Additionally, be aware that some services may have usage limitations or require you to upgrade to a paid plan for higher usage levels or advanced features. Choose the option that best suits your needs, and refer to the respective documentation for implementation details specific to each service. After this, it was research time. This actually took a little while. IBM wasn’t properly explored, because the sign-up failed due to the Dutch valid phone number not passing validation. Azure seemed great, but a bit too advanced for what we needed right now. The chatbot service chosen was Wit.ai. On there we can sign up, get an access token and specify how to deal with certain inputs. After figuring that out and making a little code start ourselves. It was time to start adjusting the code with ChatGPT. Prompting for codeEnter the following prompt, to begin with: Alright, I set up a wit.ai project, and it seems to work. Now I have the following snippet:   <section id="chat-bot">    <h2>Ask me anything!</h2>    <input id="chat-prompt" type="text">  </section> I'd like to create a chatbot with this. I can write the responses myself, but can you for now create some JavaScript code that sends an HTTP request to the wit.ai server and parses the result? For now, just print it to the console. It gave us a great place to start and some additional implementation guidelines. We’ve only included the code snippet here:// Function to send the user's message to Wit.ai and parse the response async function sendMessage(message) { // Replace 'YOUR_WITAI_ACCESS_TOKEN' with your actual Wit.ai access token const accessToken = 'YOUR_WITAI_ACCESS_TOKEN'; const apiUrl = `https://api.wit.ai/message?v=20210525&q=${encodeURIComponent(message)}`; try {    const response = await fetch(apiUrl, {      headers: {        Authorization: `Bearer ${accessToken}`      }    });    if (response.ok) {      const data = await response.json();      console.log('Wit.ai Response:', data);      // Process the data and handle the response as needed      // For example, extract intents, entities, or generate appropriate responses    } else {      console.log('Request to Wit.ai failed with status:', response.status);    } } catch (error) {    console.log('An error occurred while communicating with Wit.ai:', error); } } // Event listener for handling user input const inputElement = document.getElementById('chat-prompt'); inputElement.addEventListener('keydown', async (event) => { if (event.key === 'Enter') {    const message = event.target.value.trim();    if (message) {      console.log('User Input:', message);      await sendMessage(message);      event.target.value = ''; // Clear the input field    } } }); It also instructed us to take the following steps:Replace YOUR_WITAI_ACCESS_TOKEN with our actual access tokenPress enter after typing your question and it then logs the response to the console Make sure to put the JavaScript code in the <script> tag This is what it looked like:Image 2: practical output after the first few prompts This was already quite good, but of course, we don’t want the response in the console, but displayed in the chat window. And the same goes for our previous questions, it should become a chat. Let’s see if we can move toward that.Making it into an actual conversationIt’s always a good idea to be specific in your prompt. You can see the following prompt does quite a bit of the heavy lifting and explains clearly what type of work is needed from ChatGPT. This helps to achieve the result: I've modified the HTML a little bit:   <section id="chat-bot">    <ol id="chat-history"></ol>    <h2>Ask me anything!</h2>    <input id="chat-prompt" type="text">  </section> Can you write some logic which can populate the `chat-history` element? I need 3 things: - A history as a JavaScript object- A function which can generate the content from the history- A function which can add the question, and the response, to the history in JavaScript For now just print the top intent and all the entities. This did quite a bit of the work already. You can see the result below, the history and the answers of the two questions asked appear on top of the input box.Image 3: Answers and history appearing on top of the Input box                        It’s no secret that I’m not a UX or design expert, but even I can see that this is not ideal. So let’s see if we can improve the design.Asking ChatGPT to Style the ChatbotLet’s see if we can improve the design. Normally chatbots are not on the top left, but the bottom right. Also, it would be nice if the history could go inside the box. Of course, we want to use the same orange as for the rest of our portfolio. Here’s the prompt: Can you generate some CSS to style the element? I'd like the following: - The chat should be at the bottom right of the page.- The chat should not impact the rest of the page.- Each question and response should have a chat bubble.- The theme color is #f37041.This gave us the CSS and some context as output. Here’s the CSS:#chat-bot { position: fixed; bottom: 20px; right: 20px; z-index: 9999; background-color: #f37041; color: #fff; font-family: Arial, sans-serif; border-radius: 5px; padding: 10px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3); } #chat-history { list-style: none; margin: 0; padding: 0; max-height: 200px; overflow-y: auto; } .question, .response { display: inline-block; max-width: 80%; padding: 8px; border-radius: 10px; margin-bottom: 5px; } .question { background-color: #fff; color: #333; text-align: right; } .response { background-color: #f37041; color: #fff; text-align: left; } #chat-prompt { width: 100%; padding: 8px; margin-top: 10px; border: none; border-radius: 5px; } #chat-prompt:focus { outline: none; } #chat-prompt::placeholder { color: #ccc; } And this did quite the trick. Here’s what it looks like now: Image4: The final output If you’d like to see all the responses and the versions of the personal portfolio after each step, you can check out this GitHub repo: https://github.com/BrightBoost/portfolio-with-ai-prompt-chatgptSummaryIn conclusion, integrating a basic chatbot into your personal portfolio website can significantly enhance user engagement and provide a unique interactive experience. By leveraging GPT prompts, you can effortlessly develop a conversational AI agent that understands and responds to user queries. Adding this functionality not only showcases your technical skills but also demonstrates your ability to create dynamic and user-centric web experiences. So go ahead, implement a chatbot and elevate your portfolio website to the next level. Happy prompting!Author Bio Maaike van Putten is an experienced software developer and Pluralsight, LinkedIn Learning, Udemy, and Bright Boost instructor. She has a passion for software development and helping others get to the next level in their career.LinkedInTraining courses   
Read more
  • 0
  • 0
  • 9140

article-image-demystifying-and-getting-started-with-github-copilot
Rod Anami
13 Jun 2023
6 min read
Save for later

Demystifying and Getting Started with GitHub Copilot

Rod Anami
13 Jun 2023
6 min read
Suddenly, in a blink of an eye, we all started to talk about AI, with particular attention to Generative AI, which produces assets, including code. Not long ago, OpenAI released ChatGPT, which received the spotlight from the media and even interest from people outside IT because of its capacity to sustain a dialog with a human and bring very specialized knowledge to answer questions. Before we continue, as a disclaimer, AI did not generate this very article. In my previous post, I discussed that site reliability engineers (SREs) and other professionals used AI capabilities long before ChatGPT. Today I want to talk about an exciting application of AI to aid software engineers, developers, and SREs in coding with AI-powered pair programming. GitHub Copilot is one notorious example and is sold as an "AI pair programmer." It generates code based on the comments around the code's intention, and it's been gaining traction among the developer's ranks. By the end of this post, you will understand what's Copilot and how to start using it.Does it mean I don't need any development skills anymore?The short answer is not really. Unless the problem you're trying to resolve with code is simple enough to require a few functionalities, you must have solid software development abilities to complete the work, even with Copilot in the game. Copilot is an emerging coding productivity tool, not a no-code or low-code solution. Also, would you sell software that you wouldn't be able to explain how it works? Worse, would you buy software that no one knows how it works?How does it work?GitHub Copilot utilizes OpenAI Codex under the hood. Like ChatGPT, Codex is a descendant of the GPT-3 (third-generation Generative Pre-trained Transformer), a neural network machine learning model trained with data from the Internet and capable of generating any natural language text. On top of that, they used billions of code lines from public repositories to teach Codex. In essence, it can read natural language and forge lines of code in many languages, including "JavaScript, Go, Perl, PHP, Ruby, Swift and TypeScript, and even Shell," but it has more proficiency in Python.Codex possesses four proven coding capacities:Generation: it generates lines of code based on a description in natural languageTranspiration: transforms code written in one language to another one that has a similar level of abstractionExplanation: explains what a block of code does in detailRefactoring: improves the efficiency of a code block without modifying its original intentWith Copilot, it's possible to generate a new block of code by inserting a programming language comment with the description of the code logic. For example, if I type this comment in a JavaScript file:// A function that takes in a string and returns a string with the first letter capitalizedIt may suggest the following code snippet:function capitalizeFirstLetter(string) {        return string.charAt(0).toUpperCase() + string.slice(1);}Another usage is through code recommendations. For instance, it may suggest lines of code to complete an unfinished function or procedure.Will it spy on me?Not at all. According to the GitHub's privacy statement, "neither your Prompts nor Suggestions will be shared or used as suggested code for other users of GitHub Copilot." Of course, publishing your code and the comments used to generate code through Copilot on a public repository may defeat this data privacy.Will it generate the perfect code?No, it will construct a reasonable with minimum accuracy solution, but it does not necessarily mean the generated code perfectly fits your project requirements. You will need to validate if the Copilot recommendations make sense in the context of your project. Also, there's no guarantee the code suggestions are flawless or follow strict security and quality policies.Now that you have a basic understanding of Copilot let's enable it on your laptop. You will need a GitHub account and an integrated development environment (IDE) tool installed on your machine.Enable Copilot for your GitHub personal accountYou can sign up for free at this link if you don't have a GitHub personal account. I'm assuming you have one ready for the rest of the below instructions.Image 1: Copilot pageThe first task is enabling the Copilot feature for your GitHub account; you can do that by selecting one of the pricing plans here. When I wrote this article, there was a free trial option. Next, you need to indicate whether or not you want the code suggestions coming from public code and if Copilot can use your snippets to improve the model (re-train it).Install the Copilot module on your preferred IDEAfter you enable it for your GitHub account, the second task is to install Copilot into your preferred IDE. I'm using Microsoft Visual Studio Code (VS Code), but they provide a package for many other IDEs; you can see the list and specific installation procedure here. Also, if you want, you can download and install VS Code from this official website.Image 2: Copilot extensionFor the VS Code tool, the installation process is straightforward: Open VS Code and click on Extensions in the left navigation panel.Look for the "copilot" term and select the GitHub Copilot extensionUse your GitHub credentials if you don't have any VS Code extension for GitHub yetInstall it and make sure it's enabled globally.Start to experiment with Copilot for realAfter you have the Copilot extension, it's time to test it. Just open a project folder or create a new one.Then create a new file; you can name it after copilot-test.js. If you don't have the JavaScript extension, it will prompt you to install it. Let's craft a comment that will trigger Copilot to generate code. Enter the following statement:// A function that reads a JSON file and returns the number of fields in the JSON objectThen, hit the CTRL+Enter to see possible solutions in a separate window. By the way, you can see all the keyboard shortcuts in this document for VS Code. It can bring up to 10 possible recommendations. Check the one that matches your style and click on the "Accept Solution" link at the end of the section.ConclusionAlthough it may not be the full-fledged AI-fueled programmer we see in the movies, GitHub Copilot helps developers with the initial algorithms and basic coding patterns. It might benefit individual developers and entire companies if seen as a software development productivity tool instead of a mythic autonomous programmer bot.I hope you enjoyed this blog post, and if you liked it, please connect to me on LinkedIn or follow me on Twitter @ranami. Also, my book Becoming a Rockstar SRE is out.
Read more
  • 0
  • 0
  • 14284
article-image-chatgpt-as-an-assistant-for-plc-programmers
M.T White
13 Jun 2023
10 min read
Save for later

ChatGPT as an Assistant for PLC Programmers

M.T White
13 Jun 2023
10 min read
ChatGPT has been making the rounds recently in the world of programming.  In short, there is a lot of hoopla about whether or not it will replace programmers, how well it writes code, how well it troubleshoots issues, and more importantly how programmers can leverage it to automate code production. One area where ChatGPT can be of particular use is in the field of automation.  As all automation programmers know, the automation industry is very fast-paced.  This means that being able to quickly produce quality code is vital to the success of not only the programmer but the company as a whole.  However, it is often the case that some of the simplest code that a developer will need to produce is often the most time-consuming to write.  Two areas that come to mind are large case statements and sorting algorithms.  As such, the following article is going to explore how ChatGPT can be used to produce code that would otherwise be monotonous or time-consuming to write.  More specifically, the following is going to explore how ChatGPT can be used to generate the necessary code for a case statement that displays a motor’s health and how it can be used to select and generate the code for a sorting algorithm to sort part sizes. A CASE Statement to Detect Motor HealthA very daunting and time-consuming task that all automation programmers will perform regularly is creating large case statements.  It is not uncommon for automation programmers to have to build things like state machines that have 10s or even 100s of different cases.  As anyone who has built these before knows, building structures like these is time-consuming and monotonous at best.  For example, suppose a developer is working on a function block that will display a custom message about a motor error in an HMI.  Assume in this example the developer needs a code block that can handle the input/output exchange for the following table,Input valueString Message1Cable Error2Motor Overheated3Under CurrentDepending on the experience level of the developer a simple case statement program that can handle the requirements would take about five minutes.  However, when there are more case statements, for example, 30 or 40 inputs, the timeframe for completion could drastically increase.  Simply put, since there are more cases there will be more code to write.  In turn, this means that it will take the developer more time to type out the code and there will be a higher probability of introducing a bug or bugs in the code due to human error.  On the other hand, to quickly generate a quality code block that can meet these requirements all one would need to do is enter the following into ChatGPT:write an IEC 61131-3 code block that will set a message variable to "cable error" when the input is 1, "motor overheated" when the input is 2, and "under current" when the input is 3This statement will output the following:FUNCTION_BLOCK SetMessage VAR_INPUT    Input: INT; // Input value END_VAR VAR_OUTPUT    Message: STRING(50); // Output message END_VAR METHOD SetMessage VAR    TempMessage: STRING(50); // Temporary message variable END_VAR CASE Input OF    1:        TempMessage := 'Cable error';    2:        TempMessage := 'Motor overheated';    3:        TempMessage := 'Under current';    ELSE        TempMessage := 'Invalid input'; // Optional: default message for other input values END_CASE Message := TempMessage; // Assign the temporary message to the output message END_METHOD From the time it took to input and run the query on ChatGPT to the final code output was about one minute.  The code that was generated is quality code that looks like it was produced by an experienced programmer, it is documented, and above all else works.  The code even has an optional else statement to catch invalid inputs.  Overall, the autogenerated code is no less than what would be expected from a human developer.  With that, let’s explore how ChatGPT can be used to generate a more complex piece of software.   An Efficient Sorting Algorithm to Sort Parts by SizeIt is not uncommon for developers to be tasked with finding the smallest/largest or lightest/heaviest part produced on a production run.  For a task like this, it is common to store all the sizes, weights, or whatever it may be in an array and at one point or another sort the array to find the greatest and least size.  Depending on the size of the array, or in the case of this scenario, the number of part sizes to sort, having an efficient array is vital.  For this task, an efficient sorting algorithm will need to be picked and the code will need to be implemented. Assuming the PLC programmer is knowledgeable of sorting algorithms and Big O notations selecting an algorithm may only take a few minutes.  However, for a PLC programmer that is not versed in these topics, such as a person that is perhaps and mechanical engineer or a technician of some type, this task will probably require a Google search which ideally will take about five minutes.  Regardless, of whether the programmer is experienced or not with the algorithm it will take roughly 10 to 20 minutes for the person to type in the code.  As such, on a good day, it would take roughly 10 to 25 minutes for someone to implement a sorting algorithm. On the other hand, if a person used ChatGPT all they would have to do is type in the following query:write an IEC 61131-3 Structured Text sorting algorithm that can sort the elements in an array with 100 entries with the best possible Big O timeWhich will generate the following:FUNCTION_BLOCK QuickSort VAR_INPUT    arr: ARRAY[1..100] OF INT; END_VAR METHOD SortArray : BOOL    SortPartition(arr, 1, 100);    SortArray := TRUE; END_METHOD METHOD SortPartition(arr: ARRAY[1..100] OF INT; low: INT; high: INT) VAR    pivot: INT;    partitionIndex: INT; END_VAR    IF low < high THEN        pivot := Partition(arr, low, high, low); // Choosing pivot as the first element        SortPartition(arr, low, pivot - 1);        SortPartition(arr, pivot + 1, high);    END_IF; END_METHOD METHOD Partition(arr: ARRAY[1..100] OF INT; low: INT; high: INT; pivotIndex: INT) : INT VAR    pivotValue: INT;    i: INT;    partitionIndex: INT;    temp: INT; END_VAR    // Swap pivot element to the end    temp := arr[high];    arr[high] := arr[pivotIndex];    arr[pivotIndex] := temp;    pivotValue := arr[high];    partitionIndex := low;    FOR i := low TO high - 1 DO        IF arr[i] <= pivotValue THEN            // Swap elements            temp := arr[i];            arr[i] := arr[partitionIndex];            arr[partitionIndex] := temp;            partitionIndex := partitionIndex + 1;        END_IF;    END_FOR;    // Move pivot element to its correct position    temp := arr[partitionIndex];    arr[partitionIndex] := arr[high];    arr[high] := temp;    Partition := partitionIndex; END_METHOD END_FUNCTION_BLOCKAll of this code was generated in about one minute.  As can be seen, ChatGPT generated roughly 60 lines of code not counting the code that utilizes the example.  The only overhead that would be required by the programmer is to create the necessary files and paste the code in.  In terms of efficiency, ChatGPT rendered the Quicksort algorithm which has a Big O of n*log(n).  So, in the end, the programmer is probably looking at around five minutes' worth of work to implement an efficient algorithm that would otherwise take up to half an hour by hand.The Key to using ChatGPTAs can be seen, the key to using ChatGPT as a programming assistant is simply learning to talk to it.  Unlike programming languages that have a unique syntax, ChatGPT can interpret normal, human language.  However, to get the most out of ChatGPT the programmer needs to learn to ask detailed questions. The general rule of thumb is the more detailed a statement is the more detailed the solution will be.  As was seen, in the examples, all the code was produced with a single sentence.  Depending on the resolution needed, a simple query can produce great results, but it should be noted that if specs like specific ports, and so on need to be addressed the user should specify those.  Though novel now, it is likely that the art of talking to these systems will soon appear to generate optimal code with a query. SummaryIn all, ChatGPT can be used as a tool to help speed up the development process.  As was explored with the motor health code block and the sorting algorithm, ChatGPT can turn a simple phrase into workable code that would take a human a considerable amount of time to type out.  In short, even if a PLC programmer is knowledgeable of both programming principles, algorithms, and other computer science concepts they will always be bottlenecked by having to implement the code if they cannot simply cut and paste it from another source. When used in a way that was explored, ChatGPT is a great productivity tool.  It can be used to greatly reduce the amount of time needed to implement and if necessary find a solution.  Overall, ChatGPT needs guidance to arrive at a proper solution and the person driving the AI needs to be competent enough to implement the solution.  However, when in the right hands ChatGPT and similar AI systems can greatly improve development time.Author BioM.T. White has been programming since the age of 12. His fascination with robotics flourished when he was a child programming microcontrollers such as Arduino. M.T. currently holds an undergraduate degree in mathematics, and a master's degree in software engineering, and is currently working on an MBA in IT project management. M.T. is currently working as a software developer for a major US defense contractor and is an adjunct CIS instructor at ECPI University. His background mostly stems from the automation industry where he programmed PLCs and HMIs for many different types of applications. M.T. has programmed many different brands of PLCs over the years and has developed HMIs using many different tools.Author of the book: Mastering PLC Programming
Read more
  • 0
  • 0
  • 2524

article-image-effective-text-generation-editing-and-translation-with-chatgpt
Valentina Alto
13 Jun 2023
7 min read
Save for later

Effective Text Generation, Editing and Translation with ChatGPT

Valentina Alto
13 Jun 2023
7 min read
This article is an excerpt from the book, Modern Generative AI with ChatGPT and OpenAI Models, by Valentina Alto. This book will help harness the power of AI with innovative, real-world applications, and unprecedented productivity boosts, powered by the latest advancements in AI technology like ChatGPT and OpenAI.In the world of natural language processing, ChatGPT stands as a powerful tool for various text-related tasks. From generating creative and coherent text to providing translations and editing assistance, ChatGPT offers a wide range of functionalities. In this article, we will explore how to harness the capabilities of ChatGPT to accomplish tasks such as generating engaging content, translating text between languages, and receiving helpful suggestions for editing. With practical examples and step-by-step instructions, we will unlock the potential of ChatGPT as a versatile text companion for developers and content creators alike.As a language model, ChatGPT is particularly suited for generating text based on users’ instructions. For example, you   could ask ChatGPT to generate emails, drafts, or templates that target a specific audience:Figure 1: Example of an email generated by ChatGPTAnother example might be asking ChatGPT to create a pitch structure for a presentation you have to prepare: Figure 2 – Slideshow agenda and structure generated by ChatGPTYou can also generate blog posts or articles about trending topics this way. Here is an example:Figure 3 – blog post with relevant tags and SEO  by ChatGPTWe can even get ChatGPT to reduce the size of the post to make it fit for a tweet. Here is how we can do this: Figure 4 – ChatGPT shrinks an article into a Twitter postFinally, ChatGPT can also generate video or theatre scripts, including the scenography and the suggested editing. The following figure shows an example of a theatre dialog between a person and ChatGPT:  Figure 5– Theatre dialog with scenography generated by ChatGPTI only provided a truncated version to keep you in suspense regarding the ending…Improving writing skills and translationSometimes, rather than generating new content, you might want to revisit an existing piece of text. It this be for style improvement purposes, audience changes, language translation, and so on.Let’s look at some examples. Imagine that I drafted an email to invite a customer of mine to a webinar. I wrote two short sentences. Here, I want ChatGPT to improve the form and style of this email since the target audience will be executive-level:Figure 6 – Example of an email revisited by ChatGPT to target an executive audienceNow, let’s ask the same thing but with a different target audience: Figure 6 – Example of the same email with a different audience, generated by ChatGPTChatGPT can also give you some feedback about your writing style and structure.Imagine, for example, that you wrote a script with scenography for your YouTube channel. You included the speech as well as images, clips, and video editing activities. You also know that your typical audience is between 15 and 25 years old. You want feedback on your script and ask for this from ChatGPT: Figure 7 – Example of ChatGPT providing feedback on a video script As you can see, not only was ChatGPT able to give me feedback about the writing style, but also it suggested how I could improve the scenography of the whole video, by including more visuals.Again, imagine you wrote an introduction for an essay titled The History of Natural Language Processing and you want some feedback about the writing style and its consistency with the title: Figure 8 – Example of ChatGPT giving feedback on an introduction for an essayLet’s also ask ChatGPT to make concrete examples of the attention-grabbing anecdote it talked about in its response: Figure 9 – Example of ChatGPT elaborating on something it mentioned I’m also interested in knowing whether my introduction was consistent with the title or whether I’m taking the wrong direction:Figure 10 – ChatGPT provides feedback about the consistency of the introduction with the titleI was impressed by this last one. ChatGPT was smart enough to see that there was no specific mention of the history of NLP in my introduction. Nevertheless, it sets up the expectation about that topic to be treated later on. This means that ChatGPT also has expertise in terms of how an essay should be structured and it was very precise in applying its judgment, knowing that it was just an introduction.It is also impressive to note how the model can give different feedback, depending on the context. With the video script, ChatGPT’s feedback took into account that the final consumption of that content would have been on screen. On the other hand, the essay’s introduction lives in a more formal and academic context, with a specific structure, that ChatGPT was able to capture once more.Last but not least, ChatGPT is also an excellent tool for translation. It knows at least 95 languages (if you have doubts about whether your language is supported, you can always ask ChatGPT directly). Here, however, there is a consideration that might arise: what is the added value of ChatGPT for translation when we already have cutting-edge tools such as Google Translate?To answer this question, we have to consider some key differentiators and how we can leverage ChatGPT’s embedded translations capabilities:ChatGPT can capture the intent. This means that you could also bypass the translation phase since it is something that ChatGPT can do in the backend. For example, if you write a prompt to produce a social media post in French, you could write that prompt in any language you want – ChatGPT will automatically detect it (without the need to specify it in advance) and understand your intent:Figure 11 – Example of ChatGPT generating an output in a language that is different from the inputChatGPT can capture the more refined meaning of particular slang or idioms. This allows for a translation that is not literal so that it can preserve the underlying meaning. Namely, let’s consider the British expression It’s not my cup of tea, to indicate something that is not the type of thing you like. Let’s ask both ChatGPT and Google Translate to translate it into Italian: Figure 12 – Comparison between ChatGPT and Google Translate while translating from English into ItalianAs you can see, ChatGPT can provide several Italian idioms that are equivalent to the original one, also in their slang format. On the other hand, Google Translate performed a literal translation, leaving behind the real meaning of the idiom. As with any other task, you can always provide context to ChatGPT. So, if you want your translation to have a specific slang or style, you can always specify it in the prompt. Or, even funnier, you can ask ChatGPT to translate your prompt with a sarcastic touch:  Figure 5.20 – Example of ChatGPT translating a prompt with a sarcastic touch.The original content from: OpenAI’s Wikipedia page: https://it.wikipedia.org/wiki/OpenAISummaryIn conclusion, ChatGPT is able not only to generate new text but also to manipulate existing material to tailor it to your needs. It has also proven to be very precise at translating between languages, also keeping the jargon and language-specific expressions intact.Author BioValentina Alto graduated in 2021 in Data Science. Since 2020 she has been working in Microsoft as Azure Solution Specialist and, since 2022, she focused on Data&AI workloads within the Manufacturing and Pharmaceutical industry. She has been working on customers’ projects closely with system integrators to deploy cloud architecture with a focus on datalake house and DWH, data integration and engineering, IoT and real-time analytics, Azure Machine Learning, Azure cognitive services (including Azure OpenAI Service), and PowerBI for dashboarding. She holds a BSc in Finance and an MSc degree in Data Science from Bocconi University, Milan, Italy. Since her academic journey she has been writing Tech articles about Statistics, Machine Learning, Deep Learning and AI on various publications. She has also written a book about the fundamentals of Machine Learning with Python. LinkedIn  Medium 
Read more
  • 0
  • 0
  • 10101
Modal Close icon
Modal Close icon