Created
August 23, 2025 03:25
-
-
Save originalankur/f236b6324842beb8bed9537c411932e6 to your computer and use it in GitHub Desktop.
News Analyzer - Ensure you have a virtualenv and do `pip install dspy==3.0.2`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from typing import Literal | |
import dspy | |
def configure_ollama_lm(model: str = "ollama/gemma3:4b", | |
base_url: str = "http://localhost:11434"): | |
""" | |
Configures DSPy to use a local Ollama model. | |
""" | |
print("Connecting to local Ollama model...") | |
ollama_lm = dspy.LM(model=model, base_url=base_url) | |
dspy.settings.configure(lm=ollama_lm) | |
class ComprehensiveArticleAnalysis(dspy.Signature): | |
""" | |
Analyzes a news article to extract key information, summarize, analyze sentiment, | |
and transform content into various formats, outputting a structured JSON object. | |
""" | |
article_text: str = dspy.InputField( | |
desc="The full text of the news article to be analyzed." | |
) | |
summarization: str = dspy.OutputField( | |
desc="A concise, one-paragraph summary of the article." | |
) | |
entity_recognition: str = dspy.OutputField( | |
desc="A JSON string representing an object with lists for 'people', \ | |
'organizations', 'locations', 'dates', and 'agreements'." | |
) | |
topic_extraction: list[str] = dspy.OutputField( | |
desc="A list of 5-7 key topics or themes from the article." | |
) | |
sentiment_analysis_overall_tone: Literal["positive", "negative", "neutral"] = dspy.OutputField() | |
sentiment_analysis_overall_tone_reasoning: str = dspy.OutputField( | |
desc="A brief explanation of the sentiment analysis result." | |
) | |
content_transformation: str = dspy.OutputField( | |
desc="A JSON string representing an object with 'tweet' and 'linkedin_post' keys." | |
) | |
q_and_a: str = dspy.OutputField( | |
desc="A JSON string representing a list of objects, where each object has a 'question' and 'answer' key." | |
) | |
fact_extraction: list[str] = dspy.OutputField( | |
desc="A list of key, verifiable claims or facts stated in the article." | |
) | |
def run_article_analysis(article: str): | |
""" | |
Runs the article analysis using the configured DSPy model. | |
""" | |
print("Analyzing the article...") | |
article_analyzer = dspy.Predict(ComprehensiveArticleAnalysis) | |
return article_analyzer(article_text=article) | |
def print_analysis_results(result): | |
""" | |
Prints the entire analysis result as a pretty-formatted JSON object. | |
""" | |
# Build a dictionary from the Prediction object's keys and values. | |
result_dict = {key: getattr(result, key) for key in result.keys()} | |
# Attempt to parse JSON strings in the result for better formatting | |
for key, value in result_dict.items(): | |
if isinstance(value, str): | |
try: | |
# This part is still useful for nested JSON strings | |
parsed = json.loads(value) | |
result_dict[key] = parsed | |
except Exception: | |
pass | |
print(json.dumps(result_dict, indent=2)) | |
if __name__ == "__main__": | |
bretton_woods_article = """ | |
In July 1944, with World War II still raging, delegates from 44 Allied nations gathered at the Mount Washington Hotel in Bretton Woods, New Hampshire, for a conference of monumental importance: the United Nations Monetary and Financial Conference. The world they knew was one of economic chaos. The preceding decades had been marked by the Great Depression, crippling hyperinflation, competitive currency devaluations, and destructive trade protectionism—all of which had contributed to the outbreak of the war. The delegates at Bretton Woods were determined not to repeat these mistakes. | |
Their primary goal was to create a framework for international economic cooperation and stability in the post-war world. Led by two principal figures, John Maynard Keynes of the United Kingdom and Harry Dexter White of the United States, the conference aimed to establish a system that would encourage free trade, ensure exchange rate stability, and provide a source of funds for rebuilding war-torn nations. | |
After three weeks of intensive negotiations, the delegates reached a landmark agreement known as the Bretton Woods Agreement. This accord fundamentally reshaped the international financial system and led to the creation of two crucial global institutions: | |
1. The International Monetary Fund (IMF): Tasked with promoting international monetary cooperation, the IMF would monitor exchange rates and lend reserve currencies to nations experiencing balance of payments deficits. This was designed to prevent the kind of destabilizing currency wars that plagued the 1930s. | |
2. The International Bank for Reconstruction and Development (IBRD): Now part of the World Bank Group, the IBRD was established to provide loans and financial assistance for the reconstruction of post-war Europe and to encourage development in other countries. | |
The core of the Bretton Woods system was a new monetary order. It established a system of fixed exchange rates where member countries pegged their currencies to the U.S. dollar. The U.S. dollar, in turn, was pegged to the price of gold at a fixed rate of $35 per ounce. This made the dollar the world's primary reserve currency and provided a stable, predictable foundation for international trade to flourish. | |
The agreement was a resounding success in its initial decades, ushering in a period of unprecedented global economic growth known as the "Golden Age of Capitalism." By fostering stability and providing the capital needed for reconstruction, the Bretton Woods system helped rebuild Europe and Japan, expanded global trade, and raised living standards across the world. While the system of fixed exchange rates eventually collapsed in the early 1970s, the institutions it created—the IMF and the World Bank—continue to play a central role in the global economy to this day, making the 1944 conference a pivotal and overwhelmingly positive moment in financial history. | |
""" | |
configure_ollama_lm() | |
result = run_article_analysis(bretton_woods_article) | |
print_analysis_results(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
response to the above script
Requirements
pip install dspy==3.0.2