Analyzing Articles in Collaboration with ChatGPT
ChatGPT Article Analysis

Analyzing Articles in Collaboration with ChatGPT

In the realm of article analysis, numerous API providers cater to a wide range of article types. For the purpose of this article, we showcase the utilization of the esteemed https://newsapi.org/ API. Our appreciation goes out to their remarkable service, although it is worth noting that alternative providers could have been equally employed.

The primary objective of this article is to underscore the significance of leveraging an API service to access articles, thereby enabling the dissemination of articles on diverse topics to your esteemed audience. These topics can encompass a variety of choices, including both freely chosen subjects and those specifically tailored to your products, services, or related interests.

When presenting the article's title, author, URL, and description, it becomes highly valuable to offer an analysis of the subject matter prior to delving into the core content of the article itself. This is precisely where ChatGPT emerges as an indispensable tool, offering its invaluable services.

In order to optimize costs for both ChatGPT and the news service, a prudent approach involves running the analysis once a day and updating the content accordingly. Thus, the news API is utilized only once a day, while ChatGPT performs its insightful analysis on select articles within the same timeframe.

Given that the number of articles for analysis could potentially surpass 300, it is judicious to focus the analysis on a subset of articles. Selecting the first 10, 50, 100, or all articles, if cost permits, ensures efficient resource allocation.

To store the articles and their corresponding summaries for the day, an Azure Storage Container and files serve as the optimal solution. Upon program execution, the system first checks if it is a new day. If affirmative, it proceeds to execute the program afresh, obtaining the latest articles and generating ChatGPT's analysis for a predetermined number of articles.

To facilitate the reading of articles, an Azure MVC Web App has been developed, featuring a user-friendly page and menu. While articles covering ChatGPT, AI, and Google Bard domains have been prepared, this example solely focuses on articles related to ChatGPT.

Towards the end of this discourse, a demonstration of code implementation is presented. It is imperative to note that while the code may appear straightforward and seemingly rudimentary, its purpose lies in elucidating the underlying concept rather than serving as a testament to exceptional coding skills—an accomplishment I would undoubtedly fail to achieve.

A noteworthy tip on the horizon is the imminent ability to leverage multiple AI providers, thereby enriching the analysis process and augmenting its allure.

However, a word of caution is in order. It is crucial to meticulously test your code and formulate questions posed to the AI in a manner that ensures the reception of valid and trustworthy answers. Moreover, by implementing a semi-recursive loop (not demonstrated in the example code), AI itself can be employed to verify the authenticity and validity of the answers obtained.

In summary, our exploration of the integration of article analysis with ChatGPT underscores its immense potential. By continuously refining the underlying technologies, embracing the advancements on the horizon, and heeding the call for meticulous testing, we have the opportunity to revolutionize how users interact with news content. Through the collaborative efforts of humans and AI, we empower users with the ability to access, comprehend, and navigate the vast realm of news, all while ensuring the delivery of reliable, valuable, and enlightening insights.

The content is ordered as:

1.??????The Intro (as is done above).

2.??????The architecture.

3.??????The MVC Website page picture, showing the articles and analysis.

4.??????Use Cases.

5.??????Advice on road ahead and improvements

6.??????Summary.

7.??????The code.


The Architecture

Geen alternatieve tekst opgegeven voor deze afbeelding
The architecture to grab, analyse, store and view articles


The Azure MVC Web App to view articles

Could potentially be many articles (not shown)

Geen alternatieve tekst opgegeven voor deze afbeelding

Possible Use Cases for this functionality

Here is a list of possible use cases where an application that reads articles from a News API and utilizes ChatGPT to create an analysis per article can be useful:

  1. News Aggregator and Summarizer: The application can aggregate articles from various sources, provide summaries of each article, and generate analysis using ChatGPT. This allows users to quickly browse through multiple articles, grasp the main points, and understand the analysis without reading each article in full.
  2. Personalized News Digest: Based on user preferences or browsing history, the application can curate a personalized news digest by selecting relevant articles and providing analysis summaries. Users can stay updated on topics of interest while saving time by not having to read every article in detail.
  3. Trend Analysis and Insights: By analyzing a large number of articles, the application can identify emerging trends, popular topics, or key discussions in real-time. This can be useful for marketers, researchers, or businesses looking to gain insights into public sentiment, industry trends, or consumer behavior.
  4. Opinion Mining and Sentiment Analysis: Using ChatGPT's analysis capabilities, the application can extract sentiment, opinions, or attitudes expressed in news articles. This helps individuals or organizations understand public perception, track sentiment shifts, and make informed decisions based on the sentiment analysis.
  5. Research and Content Discovery: Researchers, scholars, or students can benefit from the application by using the analysis summaries to discover relevant articles and literature in their field of study. The application can help narrow down the focus and provide a quick overview of each article's content and relevance.
  6. Competitive Intelligence: Businesses can leverage the application to monitor news articles related to their competitors, industry trends, or market developments. The analysis generated by ChatGPT can provide insights into competitor strategies, new product launches, or market opportunities.
  7. News Filtering and Filtering: The application can allow users to filter news articles based on specific criteria such as sentiment, relevance, or topic. Users can customize their news feed to receive articles that align with their preferences and interests.
  8. Event Monitoring and Crisis Management: During critical events or crises, the application can analyze news articles to identify emerging situations, monitor public response, and track the spread of information. This assists in crisis management, enabling timely responses and informed decision-making.
  9. Financial News Analysis: Investors or financial professionals can utilize the application to analyze news articles related to specific stocks, markets, or economic indicators. The analysis summaries can provide insights into market sentiment, potential impacts, or investment opportunities.
  10. Media Monitoring and Brand Reputation: Companies can monitor news articles mentioning their brand or specific keywords to gauge public sentiment and assess their brand reputation. The application can provide analysis summaries that highlight key mentions, sentiments, or trends.
  11. Political Analysis and Policy Monitoring: Political analysts, policymakers, or government agencies can use the application to analyze news articles related to political events, policies, or public opinion. The analysis summaries can aid in understanding public sentiment, tracking policy impacts, or assessing media coverage.
  12. Fake News Detection: By analyzing the content of news articles and cross-referencing with other sources, the application can help detect potential instances of fake news or misinformation. The analysis generated by ChatGPT can assist users in identifying reliable sources and validating information. WARNING: While this represents a potentially significant use case, it requires extensive analysis to determine how fake news will be identified, who will carry out this task, and what safeguards will be in place throughout the process. Regrettably, the current situation is marked by a concerning trend where news labeled as fake often turns out to be valid, while genuine news is falsely portrayed as fake. The chaotic state of the global political landscape further complicates the identification of fake news.
  13. Language Learning and Education: Language learners can benefit from the application by reading news articles and accessing analysis summaries. The summaries provide language learners with an understanding of the article's main points and help improve reading comprehension skills.
  14. Content Recommendation for Websites: Website owners or content platforms can use the application to enhance user experience by providing analysis summaries for recommended articles. This encourages user engagement, increases time spent on the website, and improves content discoverability.
  15. Social Media Analysis: The application can analyze news articles shared on social media platforms, extract key insights, and generate analysis summaries. This helps users understand the context of shared articles and facilitates discussions around trending topics.

These use cases highlight the versatility and potential applications of an application that combines a News API with ChatGPT's analysis capabilities. The specific implementation can be tailored to the needs of the target audience and domain.


Road ahead and advice for improvements of this functionality

To improve the functionality for the described use cases, here is some advice on the road ahead:

  1. Enhance Natural Language Processing (NLP) Capabilities: Invest in ongoing research and development to improve the NLP capabilities of ChatGPT. This includes fine-tuning the model for better understanding of context, semantics, and nuanced analysis. Regular updates and advancements in NLP techniques should be incorporated to ensure accurate and reliable analysis.
  2. Expand Data Sources and APIs: While utilizing the News API is a good starting point, consider expanding the available data sources and APIs to gather articles from a wider range of publishers and domains. This provides a more comprehensive coverage of news topics, allowing users to access a diverse set of articles for analysis.
  3. Implement Entity Recognition and Topic Extraction: Incorporate entity recognition and topic extraction techniques to identify key entities, such as people, organizations, or locations, mentioned in the articles. This enables better categorization, filtering, and personalized recommendations based on specific topics of interest.
  4. Fine-tune Analysis for Different Domains: Customize the analysis generated by ChatGPT based on different domains or industries. Develop domain-specific language models to provide more accurate and relevant insights tailored to the needs of specific user groups, such as finance, healthcare, technology, or sports.
  5. Improve Summarization Techniques: Enhance the summarization capabilities of the application to generate concise and informative summaries of articles. Explore techniques such as extractive or abstractive summarization, considering the importance of including key information while maintaining readability.
  6. Integrate Multi-modal Analysis: Incorporate multi-modal analysis by including images, videos, or audio content associated with the articles. This enables a more comprehensive analysis and a richer user experience, particularly for news articles that heavily rely on visual or auditory elements.
  7. Enable Real-time Analysis: Develop mechanisms to provide real-time analysis of breaking news or time-sensitive events. Implement streaming capabilities to continuously monitor and analyze news articles as they become available, ensuring up-to-date insights for users.
  8. Refine Sentiment Analysis and Opinion Mining: Continuously improve sentiment analysis and opinion mining algorithms to accurately capture and interpret sentiment expressed in articles. Consider nuances such as sarcasm, irony, or context-dependent sentiment to provide a more nuanced analysis.
  9. Integrate User Feedback and Validation: Implement feedback mechanisms to gather user input and validate the accuracy and reliability of the analysis generated by ChatGPT. User feedback can help identify potential biases, improve the quality of analysis, and enhance user trust in the system.
  10. Develop Visualization Tools: Create intuitive and visually appealing dashboards or visualization tools to present the analysis summaries in a user-friendly manner. Visual representations of trends, sentiment distributions, or topic clusters can aid users in quickly interpreting the analysis.
  11. Embrace Ethical Considerations: Ensure ethical usage of AI technologies by addressing potential biases, maintaining user privacy, and providing transparency in the analysis process. Implement safeguards against the dissemination of misinformation and prioritize responsible AI practices.
  12. Continuous Evaluation and Improvement: Regularly evaluate the performance and effectiveness of the application by conducting user surveys, A/B testing, or benchmarking against other analysis tools. Actively incorporate user feedback and iterate on the system to address any limitations or areas of improvement.
  13. Collaborate with AI Researchers and Experts: Foster collaboration with AI researchers, experts, and the wider AI community to stay updated with the latest advancements, exchange knowledge, and benefit from shared experiences. Engage in academic or industry partnerships to leverage expertise and push the boundaries of AI-powered news analysis.
  14. Scalability and Performance Optimization: Optimize the application's infrastructure, data pipelines, and computational resources to handle large-scale data processing efficiently. Ensure the system is scalable to accommodate increasing user demand and the growing volume of news articles.
  15. User-Centric Design and User Experience (UX): Prioritize user-centric design principles to create a seamless and intuitive user experience. Conduct user research, usability testing, and incorporate user feedback to refine the interface, navigation, and overall usability of the application.

By following these guidelines, you can advance the functionality of the application, enhance the analysis capabilities, and provide users with valuable insights and a satisfying experience in accessing and understanding news articles.


Summary

In conclusion, the application that leverages a News API and ChatGPT's analysis capabilities offers a wide range of possibilities and benefits across various domains. By integrating these technologies, users can access article summaries and extensive analysis to make informed decisions, stay updated on topics of interest, and gain valuable insights from a vast amount of news content.

To further improve this functionality, it is crucial to focus on enhancing natural language processing capabilities, expanding data sources and APIs, and implementing entity recognition and topic extraction techniques. Fine-tuning the analysis for different domains, improving summarization techniques, and integrating multi-modal analysis will provide users with more accurate and comprehensive insights.

Real-time analysis, refined sentiment analysis, and opinion mining contribute to timely and nuanced understanding of news articles. By integrating user feedback and validation mechanisms, the application can continuously improve its accuracy and user trust. Visualization tools and ethical considerations should also be prioritized to present the analysis in an accessible and responsible manner.

Continuous evaluation, collaboration with AI researchers, and scalability optimization ensure the application's performance and adaptability in handling large-scale data processing. User-centric design and a seamless user experience further enhance the application's usability and effectiveness.

In summary, the combination of a News API and ChatGPT's analysis capabilities opens up numerous opportunities, such as news aggregation, personalized recommendations, trend analysis, sentiment tracking, and educational support. With ongoing improvements and a focus on user needs, this application can revolutionize the way users consume, understand, and engage with news content, empowering them to make well-informed decisions in an increasingly complex information landscape.

The Code

using NewsAPI
using NewsAPI.Models;
using NewsAPI.Constants;
using System;
using System.Net;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using static System.Net.Mime.MediaTypeNames;
using System.Globalization;
using OpenAI_API.Completions;


//-----------------------------------------------
// Author: Jaap Zwart
//
// Master in writing stupid code.
// Purpose of this stupid code:
// 1. Show how to read News articles from API
// 2. Show how to feed article info to ChatGPT
// 3. Show how to save info to Azure storage
// 4. Show how to read info from Azure storage
//
// Please ignore redundant code.
// Remember: it's dummy as dumb can be.
//-----------------------------------------------
namespace MyApplication
{
? ? class Program
? ? {
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? int addDays = -1; // We wanna get or save and clean storage data?
? ? ? ? ? ? DateTime currentDateTime = DateTime.Now;
? ? ? ? ? ? DateTime currentDate = currentDateTime.Date;
? ? ? ? ? ? string dateOnlyString = currentDate.AddDays(addDays).ToString().Replace(" 12:00:00 AM", "");



? ? ? ? ? ? // Get date and see if we need to update the content of the files.
? ? ? ? ? ? string getDate = ReadFirstLineFromFileInBlob("newscheckdate.txt");
? ? ? ? ? ? Console.WriteLine("From cloud:" + getDate);
? ? ? ? ? ? Console.WriteLine("From local:" + dateOnlyString);
? ? ? ? ? ? string SameD = "";
? ? ? ? ? ? if (dateOnlyString.Equals(getDate))
? ? ? ? ? ? ? ? SameD = "Same";
? ? ? ? ? ? else
? ? ? ? ? ? ? ? SameD = "Not Same";



? ? ? ? ? ? Console.WriteLine("DATE:" + getDate + "<>Found:" + SameD);
? ? ? ? ? ? string dd = DateTime.Now.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Second.ToString() +
? ? ? ? ? ? ? ? ? ? DateTime.Now.Minute.ToString() + "_new";



? ? ? ? ? ? // Meat of the method, do the article preparation.
? ? ? ? ? ? DoArticles("ChatGPT", SameD, currentDate, addDays);
? ? ? ? ? ? //DoArticles("AI", SameD, currentDate, addDays);
? ? ? ? ? ? //DoArticles("Google Bard", SameD, currentDate, addDays);



? ? ? ? ? ? // Reset date if not the same.
? ? ? ? ? ? if (SameD.Equals("Same"))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? 
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? // Update date in cloud
? ? ? ? ? ? ? ? ClearFileContentsInBlob("newscheckdate.txt");
? ? ? ? ? ? ? ? AppendTextToFileInBlob(dateOnlyString, "newscheckdate.txt");
? ? ? ? ? ? }
? ? ? ? ? ? Console.WriteLine("READY!");
? ? ? ? ? ? Console.ReadLine();
? ? ? ? }



? ? ? ? private static async void DoArticles(string whatS, string sameD, DateTime cDate, int aDays)
? ? ? ? {



? ? ? ? ? ? string SameD = sameD;
? ? ? ? ? ? DateTime currentDate = cDate;
? ? ? ? ? ? int addDays = aDays;



? ? ? ? ? ? // init with your API key
? ? ? ? ? ? var newsApiClient = new NewsApiClient("<YOUR KEY>");
? ? ? ? ? ? var articlesResponse = newsApiClient.GetEverything(new EverythingRequest
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Q = whatS,
? ? ? ? ? ? ? ? SortBy = SortBys.Popularity,
? ? ? ? ? ? ? ? Language = Languages.EN,
? ? ? ? ? ? ? ? From = currentDate.AddDays(addDays)
? ? ? ? ? ? });



? ? ? ? ? ? 



? ? ? ? ? ? string getBlob = "";
? ? ? ? ? ? if (SameD.Equals("Same"))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? 
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? 
? ? ? ? ? ? ? ? // When we have new day, clear Azure Storage files.
? ? ? ? ? ? ? ? ClearFileContentsInBlob("newsarticlesAI" + whatS.Replace(" ", "") + ".txt");
? ? ? ? ? ? ? ? ClearFileContentsInBlob("newsarticlesAI" + whatS.Replace(" ", "") + "Summary.txt");
? ? ? ? ? ? }





? ? ? ? ? ? if (articlesResponse.Status == Statuses.Ok)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if (SameD.Equals("Same")) // Get existing articles
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? getBlob = ReadBlobContent("newsarticlesAI" + whatS.Replace(" ", "") + ".txt").Result;
? ? ? ? ? ? ? ? ? ? Console.WriteLine(getBlob);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else // Create new articles
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? // total results found
? ? ? ? ? ? ? ? ? ? Console.WriteLine(articlesResponse.TotalResults);


? ? ? ? ? ? ? ? ? ? // Forr when you wanna do some fancy stuff when doing analysis for all articles and get the last ones with mod.
? ? ? ? ? ? ? ? ? ? int number = articlesResponse.TotalResults;
? ? ? ? ? ? ? ? ? ? int remainder = number % 5;
? ? ? ? ? ? ? ? ? ? 
? ? ? ? ? ? ? ? ? ? if (number >= 5)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? remainder = number % 5;
? ? ? ? ? ? ? ? ? ? ? ? int countCycle = number / 5;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? remainder = number;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? int i = 1;



? ? ? ? ? ? ? ? ? ? // Setting the stage. Vars, files and lift off....
? ? ? ? ? ? ? ? ? ? string getArticleForChatGPT = "";
? ? ? ? ? ? ? ? ? ? string getSummariesFromChatGPT = "";
? ? ? ? ? ? ? ? ? ? string getArticle = "<h1>" + whatS + "</h1>";
? ? ? ? ? ? ? ? ? ? AppendTextToFileInBlob(getArticle, "newsarticlesAI" + whatS.Replace(" ", "") + ".txt");
? ? ? ? ? ? ? ? ? ? AppendTextToFileInBlob(getArticle, "newsarticlesAI" + whatS.Replace(" ", "") + "Summary.txt");
? ? ? ? ? ? ? ? ? ? foreach (var article in articlesResponse.Articles)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? getArticle = "";
? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ? // title
? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine(whatS + ">>>>" + article.Title);
? ? ? ? ? ? ? ? ? ? ? ? getArticle = "<h3>" + article.Title + "</h3><br>";
? ? ? ? ? ? ? ? ? ? ? ? getArticleForChatGPT += article.Title + '\n';



? ? ? ? ? ? ? ? ? ? ? ? // author
? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine(whatS + ">>>>" + article.Author);
? ? ? ? ? ? ? ? ? ? ? ? getArticle += "<i>" + article.Author + "</i><br>";
? ? ? ? ? ? ? ? ? ? ? ? 
? ? ? ? ? ? ? ? ? ? ? ? // description
? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine(whatS + ">>>>" + article.Description);
? ? ? ? ? ? ? ? ? ? ? ? getArticle += article.Description + "<br>";
? ? ? ? ? ? ? ? ? ? ? ? getArticleForChatGPT += article.Title + '\n';
? ? ? ? ? ? ? ? ? ? ? ? // url
? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine(whatS + ">>>>" + article.Url);
? ? ? ? ? ? ? ? ? ? ? ? getArticle += "<a href='" + article.Url + "'>" + article.Title + "</a>" + "<br>";
? ? ? ? ? ? ? ? ? ? ? ? 
? ? ? ? ? ? ? ? ? ? ? ? // published at
? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine(whatS + ">>>>" + article.PublishedAt);
? ? ? ? ? ? ? ? ? ? ? ? getArticle += article.PublishedAt + "<br>";
? ? ? ? ? ? ? ? ? ? ? ? getArticle += "<hr>";



? ? ? ? ? ? ? ? ? ? ? ? AppendTextToFileInBlob(getArticle, "newsarticlesAI" + whatS.Replace(" ", "") + ".txt");
? ? ? ? ? ? ? ? ? ? ? ? 



? ? ? ? ? ? ? ? ? ? ? ? // Only do summaries for the first ...
? ? ? ? ? ? ? ? ? ? ? ? i += 1;
? ? ? ? ? ? ? ? ? ? ? ? if(i <= 10)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("MAKING SUMMARY");
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
? ? ? ? ? ? ? ? ? ? ? ? ? ? string makeQuestionChatGPT = "Give an extensive analysis on: " + getArticleForChatGPT;
? ? ? ? ? ? ? ? ? ? ? ? ? ? getSummariesFromChatGPT = await GetChatGPT(makeQuestionChatGPT);
? ? ? ? ? ? ? ? ? ? ? ? ? ? AppendTextToFileInBlob(getArticle, "newsarticlesAI" + whatS.Replace(" ", "") + "Summary.txt");
? ? ? ? ? ? ? ? ? ? ? ? ? ? AppendTextToFileInBlob(getSummariesFromChatGPT + "<hr>", "newsarticlesAI" + whatS.Replace(" ", "") + "Summary.txt");
? ? ? ? ? ? ? ? ? ? ? ? ? ? Console.WriteLine(getSummariesFromChatGPT);
? ? ? ? ? ? ? ? ? ? ? ? ? ? getArticleForChatGPT = "";
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? 
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
? ? ? ? ? ? Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
? ? ? ? ? ? Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
? ? ? ? }
? ? ? ? private async static Task<string> GetChatGPT(string textToAsk)
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? var openAI = new OpenAI_API.OpenAIAPI("<YOUR KEY>");





? ? ? ? ? ? ? ? CompletionRequest completion = new CompletionRequest();
? ? ? ? ? ? ? ? completion.Prompt = textToAsk;
? ? ? ? ? ? ? ? completion.MaxTokens = 4000;
? ? ? ? ? ? ? ? //completion.Model = "text-davinci-003"; // Set the model ID for GPT-3.5-turbo
? ? ? ? ? ? ? ? var result = await openAI.Completions.CreateCompletionAsync(completion);
? ? ? ? ? ? ? ? string answer = "";
? ? ? ? ? ? ? ? if (result != null)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? foreach (var item in result.Completions)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? answer += item.Text;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? return answer;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? ? ? return "No results from BlackBeltBible AI.";
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return ex.Message;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ?
? ? ? ? public static async Task<string> ReadBlobContent(string fileName)
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? string connS = "DefaultEndpointsProtocol=https;AccountName=<YOUR ACCOUNT NAME>;AccountKey=<YOUR ACCOUNT KEY>;EndpointSuffix=core.windows.net";
? ? ? ? ? ? ? ? CloudStorageAccount account = CloudStorageAccount.Parse(connS);
? ? ? ? ? ? ? ? var blobClient = account.CreateCloudBlobClient();



? ? ? ? ? ? ? ? var blobContainer = blobClient.GetContainerReference("newschannel");
? ? ? ? ? ? ? ? await blobContainer.CreateIfNotExistsAsync();



? ? ? ? ? ? ? ? CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileName);



? ? ? ? ? ? ? ? // Download the blob content asynchronously
? ? ? ? ? ? ? ? string blobContent = await blockBlob.DownloadTextAsync();



? ? ? ? ? ? ? ? return blobContent;
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return ex.Message;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ?
? ? ? ? public static string AppendTextToFileInBlob(string textToAppend, string fileName)
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? // Initialise client in a different place if you like
? ? ? ? ? ? ? ? string connS = "DefaultEndpointsProtocol=https;AccountName=<YOUR ACCOUNT NAME>;AccountKey=<YOUR ACCOUNT KEY>;EndpointSuffix=core.windows.net";
? ? ? ? ? ? ? ? CloudStorageAccount account = CloudStorageAccount.Parse(connS);
? ? ? ? ? ? ? ? var blobClient = account.CreateCloudBlobClient();



? ? ? ? ? ? ? ? // Make sure container is there
? ? ? ? ? ? ? ? var blobContainer = blobClient.GetContainerReference("newschannel");
? ? ? ? ? ? ? ? blobContainer.CreateIfNotExistsAsync();



? ? ? ? ? ? ? ? // Get the existing content of the file
? ? ? ? ? ? ? ? CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileName);
? ? ? ? ? ? ? ? string existingContent = blockBlob.DownloadTextAsync().GetAwaiter().GetResult();



? ? ? ? ? ? ? ? // Append the new text to the existing content
? ? ? ? ? ? ? ? string updatedContent = existingContent + textToAppend;



? ? ? ? ? ? ? ? // Upload the updated content back to the file
? ? ? ? ? ? ? ? blockBlob.UploadTextAsync(updatedContent).GetAwaiter().GetResult();



? ? ? ? ? ? ? ? return "Success";
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return ex.Message;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? public static string ClearFileContentsInBlob(string fileName)
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? string connS = "DefaultEndpointsProtocol=https;AccountName=<YOUR ACOUNT NAME>;AccountKey=<YOUR ACCOUNT KEY>;EndpointSuffix=core.windows.net";
? ? ? ? ? ? ? ? CloudStorageAccount account = CloudStorageAccount.Parse(connS);
? ? ? ? ? ? ? ? var blobClient = account.CreateCloudBlobClient();



? ? ? ? ? ? ? ? var blobContainer = blobClient.GetContainerReference("newschannel");
? ? ? ? ? ? ? ? blobContainer.CreateIfNotExistsAsync();



? ? ? ? ? ? ? ? CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileName);



? ? ? ? ? ? ? ? // Delete the existing blob
? ? ? ? ? ? ? ? blockBlob.DeleteIfExistsAsync();



? ? ? ? ? ? ? ? // Create a new empty blob with the same name
? ? ? ? ? ? ? ? blockBlob.UploadTextAsync("");



? ? ? ? ? ? ? ? return "Success";
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return ex.Message;
? ? ? ? ? ? }
? ? ? ? }



? ? ? ? public static string ReadFirstLineFromFileInBlob(string fileName)
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? // Initialise client in a different place if you like
? ? ? ? ? ? ? ? string connS = "DefaultEndpointsProtocol=https;AccountName=<YOUR ACCOUNT NAME>>;AccountKey=<YOUR ACCOUNT KEY>>;EndpointSuffix=core.windows.net";
? ? ? ? ? ? ? ? CloudStorageAccount account = CloudStorageAccount.Parse(connS);
? ? ? ? ? ? ? ? var blobClient = account.CreateCloudBlobClient();



? ? ? ? ? ? ? ? // Make sure container is there
? ? ? ? ? ? ? ? var blobContainer = blobClient.GetContainerReference("newschannel");
? ? ? ? ? ? ? ? blobContainer.CreateIfNotExistsAsync();



? ? ? ? ? ? ? ? // Get the content of the file
? ? ? ? ? ? ? ? CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileName);
? ? ? ? ? ? ? ? string fileContent = blockBlob.DownloadTextAsync().GetAwaiter().GetResult();



? ? ? ? ? ? ? ? // Extract the first line from the content
? ? ? ? ? ? ? ? string firstLine = fileContent.Split(Environment.NewLine)[0];



? ? ? ? ? ? ? ? return firstLine;
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return ex.Message;
? ? ? ? ? ? }
? ? ? ? }



? ? }
};        

Code to read blob in Azure MVC Web app for the View. Controller Code.

?
  public ActionResult ChatGPT(
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? HttpContext.Session["Action"] = "AnswersAINewsArticles";


? ? ? ? ? ? ? ? string SameD = "Same";
? ? ? ? ? ? ? ? HttpContext.Session["AllTheAnswers"] = "";


? ? ? ? ? ? ? ? if (SameD.Equals("Same")) // Get existing articles
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? var getBlob = readFileFromBlob("newsarticlesAIChatGPTSummary.txt");
? ? ? ? ? ? ? ? ? ? HttpContext.Session["AllTheAnswers"] += getBlob;
? ? ? ? ? ? ? ? }


? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? HttpContext.Session["AllTheAnswers"] = ex.Message;
? ? ? ? ? ? }
? ? ? ? ? ? ViewBag.BookChapters = HttpContext.Session["AllTheAnswers"].ToString();
? ? ? ? ? ? return View();
? ? ? ? })        

Azure MVC Web App View Code

@{
? ? ViewBag.Title = "Home Page";
}
<table>
? ? <tr>
? ? ? ? <td>
? ? ? ? ? ? <div style="text-align: justify;">
? ? ? ? ? ? ? ? <font size="3">
? ? ? ? ? ? ? ? ? ? @Html.Raw(ViewBag.BookChapters)
? ? ? ? ? ? ? ? </font>
? ? ? ? ? ? </div>
? ? ? ? </td>
? ? </tr>


</table>        

要查看或添加评论,请登录

社区洞察

其他会员也浏览了