Skip to content

Instantly share code, notes, and snippets.

@originalankur
Created August 23, 2025 03:25
Show Gist options
  • Save originalankur/f236b6324842beb8bed9537c411932e6 to your computer and use it in GitHub Desktop.
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`
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)
@originalankur
Copy link
Author

response to the above script

{
  "summarization": "The Bretton Woods Agreement, established in 1944 with representatives from 44 Allied nations, created the International Monetary Fund (IMF) and the International Bank for Reconstruction and Development (IBRD) to foster international economic cooperation and stability following World War II. This agreement, led by John Maynard Keynes and Harry Dexter White, established a system of fixed exchange rates linked to the U.S. dollar and gold, contributing to a period of global economic growth and the rebuilding of war-torn nations.",
  "entity_recognition": {
    "people": [
      "John Maynard Keynes",
      "Harry Dexter White"
    ],
    "organizations": [
      "International Monetary Fund (IMF)",
      "International Bank for Reconstruction and Development (IBRD)",
      "World Bank Group"
    ],
    "locations": [
      "Mount Washington Hotel",
      "Bretton Woods, New Hampshire",
      "United States",
      "Europe"
    ],
    "dates": [
      "July 1944",
      "1944",
      "early 1970s"
    ],
    "agreements": [
      "Bretton Woods Agreement"
    ]
  },
  "topic_extraction": [
    "International Monetary Cooperation",
    "Post-War Economic Reconstruction",
    "Fixed Exchange Rates",
    "Global Financial Institutions",
    "Economic Stability",
    "Bretton Woods System",
    "World Bank"
  ],
  "sentiment_analysis_overall_tone": "positive",
  "sentiment_analysis_overall_tone_reasoning": "The article describes the Bretton Woods Agreement as a \"resounding success\" and a \"pivotal and overwhelmingly positive moment,\" highlighting its contribution to global economic growth and stability.",
  "content_transformation": {
    "tweet": "The Bretton Woods Agreement (1944) created the IMF & World Bank, stabilizing the global economy after WWII! \ud83d\udcb0\ud83c\udf0d #BrettonWoods #GlobalEconomy",
    "linkedin_post": "The Bretton Woods Agreement, established in 1944, remains a landmark achievement in international finance. The creation of the IMF and IBRD fundamentally reshaped the global economic landscape, fostering stability and facilitating post-war reconstruction. This agreement continues to influence global financial systems today. #InternationalFinance #EconomicHistory #GlobalEconomy"
  },
  "q_and_a": {
    "question": "What is the significance of the Bretton Woods Agreement today?",
    "answer": "The institutions created by the agreement, the IMF and the World Bank, continue to play a central role in the global economy to this day."
  },
  "fact_extraction": [
    "The Bretton Woods Conference was held in July 1944.",
    "44 Allied nations participated in the conference.",
    "The IMF was established to promote international monetary cooperation.",
    "The IBRD was created to provide loans for post-war reconstruction.",
    "The Bretton Woods system established fixed exchange rates linked to the U.S. dollar.",
    "The U.S. dollar was pegged to the price of gold.",
    "The agreement collapsed in the early 1970s."
  ]
}

Requirements

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment