Ragas and RAG Testing

Ragas – collab – https://colab.research.google.com/drive/1zXfffyjY2ryTBV7makO6ztYrnB2ntT88?usp=sharing

import json
from datasets import Dataset
import os
from ragas import evaluate
from ragas.metrics import faithfulness, answer_correctness
from langchain_ollama import OllamaLLM
from requests.exceptions import ConnectionError
from langchain_community.llms import Ollama

# Set environment variables (if needed)
os.environ["OPENAI_API_KEY"] = "NA"  # Replace "NA" with your API key if necessary

# Path to your JSON file
json_file_path = "eval_input.json"  # Update this with the path to your actual JSON file

# Function to load JSON data
def load_json_data(file_path):
    try:
        with open(file_path, "r") as f:
            data = json.load(f)
        return data
    except FileNotFoundError:
        print(f"Error: The file {file_path} was not found.")
        return None
    except json.JSONDecodeError:
        print(f"Error: Failed to decode the JSON file {file_path}.")
        return None

# Load the data from the JSON file
data_samples = load_json_data(json_file_path)

if data_samples:
    try:
        # Initialize the LLM (ensure your local Ollama instance is running)
        evaluator_llm = Ollama(model = "llama3")
#         evaluator_llm = OllamaLLM(
#             model="llama3.2",
#             base_url="http://localhost:11434"  # Ensure Ollama is running at this URL
#         )

        print('--------------------------------------')

        llm_test = evaluator_llm.invoke("can you tell 4 genai frameworks?")
        print(llm_test)
        print('--------------------------------------')

        # Convert the data into a Hugging Face `Dataset` format
        dataset = Dataset.from_dict({
            'question': data_samples['question'],
            'answer': data_samples['answer'],
            'contexts': data_samples['contexts'],
            'ground_truth': data_samples['ground_truth']
        })

        # Perform evaluation using RAGAS metrics
        score = evaluate(dataset, metrics=[faithfulness, answer_correctness])

        # Convert the score to a pandas DataFrame and print it
        score_df = score.to_pandas()
        print(score_df)

    except ConnectionError as e:
        print(f"Connection error: {e}")
        print("Ensure that the LLM server is running and accessible at http://localhost:11434.")
    except Exception as e:
        print(f"An error occurred: {e}")
else:
    print("No data to evaluate due to an issue with the JSON file.")
{
  "question": [
    "When was the first super bowl?",
    "Who won the most super bowls?"
  ],
  "answer": [
    "The first superbowl was held on Jan 15, 1967",
    "The most super bowls have been won by The New England Patriots"
  ],
  "contexts": [
    [
      "The First AFL–NFL World Championship Game was an American football game played on January 15, 1967, at the Los Angeles Memorial Coliseum in Los Angeles."
    ],
    [
      "The Green Bay Packers...Green Bay, Wisconsin.",
      "The Packers compete...Football Conference."
    ]
  ],
  "ground_truth": [
    "The first superbowl was held on January 15, 1967",
    "The New England Patriots have won the Super Bowl a record six times"
  ]
}

{
  "question": [
    "What are the global implications of the USA Supreme Court ruling on abortion?",
    "Which companies are the main contributors to GHG emissions and their role in global warming according to the Carbon Majors database?",
    "Which private companies in the Americas are the largest GHG emitters according to the Carbon Majors database?",
    "What action did Amnesty International urge its supporters to take in response to the killing of the Ogoni 9?",
    "What are the recommendations made by Amnesty International to the Special Rapporteur on Human Rights Defenders?",
    "Who are the target audience of the two books created by Amnesty International on child rights?",
    "Which right guarantees access to comprehensive information about past human rights violations, including the identities of the perpetrators and the fate of the victims, as well as the circumstances surrounding the violations?",
    "Who has the right to be fully informed about human rights violations, including the identities of the perpetrators and the fate of the victims?",
    "When can individuals be found guilty under Article 207.3 of the Russian Criminal Code?",
    "When does the prosecution consider statements contrary to the official position as 'false' under Article 207.3?",
    "What factors have contributed to the decline of independent civil society organizations in Nicaragua?",
    "What conditions designate wetlands as Ramsar sites?",
    "Where was COP15 held in 2022?",
    "What is the purpose of the agreement known as 30x30?",
    "Who failed to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area at COP15?",
    "What are the consequences of criminalizing abortion for marginalized individuals?",
    "What responsibilities should social media companies have in relation to ensuring access to accurate sexual and reproductive health information?",
    "What role do social media companies play in protecting users' rights online, regardless of their language and political views?",
    "What labor abuses were documented by Amnesty International in Qatar and how do they relate to the kafala system?",
    "When did the government of Qatar start repealing restrictions on migrant workers?"
  ],
  "answer": [
    "The global implications of the USA Supreme Court ruling on abortion can be significant, as it sets a precedent for other countries and influences the global discourse on reproductive rights. Here are some potential implications:\n\n1. Influence on other countries: The Supreme Court's ruling can serve as a reference point for other countries grappling with their own abortion laws. It can provide legal arguments and reasoning that advocates for reproductive rights can use to challenge restrictive abortion laws in their respective jurisdictions.\n\n2. Strengthening of global reproductive rights movements: A favorable ruling by the Supreme Court can energize and empower reproductive rights movements worldwide. It can serve as a rallying point for activists and organizations advocating for women's rights, leading to increased mobilization and advocacy efforts globally.\n\n3. Counteracting anti-abortion movements: Conversely, a ruling that restricts abortion rights can embolden anti-abortion movements globally. It can provide legitimacy to their arguments and encourage similar restrictive measures in other countries, potentially leading to a rollback of existing reproductive rights.\n\n4. Impact on international aid and policies: The Supreme Court's ruling can influence international aid and policies related to reproductive health. It can shape the priorities and funding decisions of donor countries and organizations, potentially leading to increased support for reproductive rights initiatives or conversely, restrictions on funding for abortion-related services.\n\n5. Shaping international human rights standards: The ruling can contribute to the development of international human rights standards regarding reproductive rights. It can influence the interpretation and application of existing human rights treaties and conventions, potentially strengthening the recognition of reproductive rights as fundamental human rights globally.\n\n6. Global health implications: The Supreme Court's ruling can have implications for global health outcomes, particularly in countries with restrictive abortion laws. It can impact the availability and accessibility of safe and legal abortion services, potentially leading to an increase in unsafe abortions and related health complications.\n\nIt is important to note that the specific implications will depend on the nature of the Supreme Court ruling and the subsequent actions taken by governments, activists, and organizations both within and outside the United States.",
    "According to the Carbon Majors database, the main contributors to greenhouse gas (GHG) emissions and their role in global warming are primarily fossil fuel companies. These companies extract, produce, and sell fossil fuels, which when burned release carbon dioxide (CO2) and other GHGs into the atmosphere. The top contributors include:\n\n1. Saudi Arabian Oil Company (Saudi Aramco): As the world's largest oil producer, Saudi Aramco is responsible for a significant portion of global GHG emissions. It is estimated to have contributed around 59.26 gigatons of CO2 equivalent (GtCO2e) between 1965 and 2017.\n\n2. Chevron Corporation: Chevron is one of the largest oil and gas companies globally and has contributed approximately 43.35 GtCO2e between 1965 and 2017.\n\n3. ExxonMobil Corporation: ExxonMobil is another major oil and gas company and has contributed around 41.90 GtCO2e between 1965 and 2017.\n\n4. BP plc: BP is a multinational oil and gas company and has contributed approximately 34.02 GtCO2e between 1965 and 2017.\n\n5. Royal Dutch Shell plc: Shell is one of the largest oil and gas companies globally and has contributed around 31.95 GtCO2e between 1965 and 2017.\n\n6. TotalEnergies SE: TotalEnergies is a French multinational oil and gas company and has contributed approximately 31.91 GtCO2e between 1965 and 2017.\n\n7. ConocoPhillips Company: ConocoPhillips is an American multinational energy corporation and has contributed around 20.67 GtCO2e between 1965 and 2017.\n\n8. PetroChina Company Limited: PetroChina is the largest oil and gas producer in China and has contributed approximately 17.26 GtCO2e between 1965 and 2017.\n\n9. Peabody Energy Corporation: Peabody Energy is the largest private-sector coal company globally and has contributed around 15.39 GtCO2e between 1965 and 2017.\n\n10. Glencore plc: Glencore is a multinational commodity trading and mining company and has contributed approximately 15.11 GtCO2e between 1965 and 2017.\n\nThese companies, along with others in the fossil",
    "According to the Carbon Majors database, the largest private companies in the Americas that are the largest GHG emitters are:\n\n1. Chevron Corporation (United States)\n2. ExxonMobil Corporation (United States)\n3. ConocoPhillips Company (United States)\n4. BP plc (United Kingdom, but with significant operations in the Americas)\n5. Royal Dutch Shell plc (Netherlands, but with significant operations in the Americas)\n6. Peabody Energy Corporation (United States)\n7. Duke Energy Corporation (United States)\n8. TotalEnergies SE (France, but with significant operations in the Americas)\n9. BHP Group Limited (Australia, but with significant operations in the Americas)\n10. Rio Tinto Group (United Kingdom/Australia, but with significant operations in the Americas)\n\nPlease note that the rankings may change over time as new data becomes available.",
    "Amnesty International urged its supporters to write letters to the Nigerian government, calling for an independent investigation into the killings of the Ogoni 9 and for those responsible to be brought to justice. They also called for an end to the human rights abuses in the Niger Delta region and for the protection of the rights of the Ogoni people.",
    "Amnesty International made several recommendations to the Special Rapporteur on Human Rights Defenders. These recommendations include:\n\n1. Urging states to fully implement the UN Declaration on Human Rights Defenders and ensure that national laws and policies are in line with international human rights standards.\n\n2. Calling on states to create a safe and enabling environment for human rights defenders, including by adopting legislation that protects defenders from threats, attacks, and reprisals.\n\n3. Encouraging states to establish effective mechanisms for the protection of human rights defenders, such as national human rights institutions and specialized units within law enforcement agencies.\n\n4. Urging states to investigate and hold accountable those responsible for attacks and threats against human rights defenders, ensuring that they are brought to justice in fair trials.\n\n5. Calling on states to repeal or amend laws that are used to criminalize or restrict the work of human rights defenders, including laws on defamation, sedition, and counter-terrorism.\n\n6. Encouraging states to provide adequate resources and support to human rights defenders, including funding for their work, access to legal assistance, and psychosocial support.\n\n7. Urging states to consult and engage with human rights defenders in the development and implementation of laws, policies, and programs that affect their rights and work.\n\n8. Calling on states to ensure that human rights defenders are able to access and share information freely, including through the internet and other digital platforms.\n\n9. Encouraging states to protect the rights of specific groups of human rights defenders who face particular risks and challenges, such as women defenders, indigenous defenders, and defenders working on issues related to sexual orientation and gender identity.\n\n10. Urging states to cooperate with the Special Rapporteur and other UN mechanisms in the promotion and protection of human rights defenders, including by responding to communications and requests for visits.",
    "The target audience of the two books created by Amnesty International on child rights are likely children and young adults.",
    "The right that guarantees access to comprehensive information about past human rights violations, including the identities of the perpetrators and the fate of the victims, as well as the circumstances surrounding the violations, is the right to truth.",
    "Everyone has the right to be fully informed about human rights violations, including the identities of the perpetrators and the fate of the victims. This right is recognized by various international human rights instruments, such as the Universal Declaration of Human Rights and the International Covenant on Civil and Political Rights.\n\nThe victims of human rights violations and their families have a particular right to know the truth about what happened to them. This includes knowing the identities of the perpetrators and the fate of the victims, such as whether they are alive or dead, and if dead, the circumstances of their death.\n\nFurthermore, society as a whole has a right to be informed about human rights violations. This is essential for holding perpetrators accountable, preventing future abuses, and ensuring justice and reparations for the victims. Access to information about human rights violations also allows for public scrutiny and debate, which are crucial for building a culture of human rights and promoting transparency and accountability.\n\nJournalists, human rights defenders, and civil society organizations play a vital role in investigating and reporting on human rights violations. They have the right to access information, conduct independent investigations, and disseminate their findings to the public. Governments have a responsibility to protect and facilitate these activities, ensuring that individuals and organizations can operate freely and without fear of reprisals.\n\nIn summary, the right to be fully informed about human rights violations, including the identities of the perpetrators and the fate of the victims, belongs to everyone. It is a fundamental aspect of promoting human rights, accountability, and justice.",
    "Under Article 207.3 of the Russian Criminal Code, individuals can be found guilty if they participate in an organized group or commit repeated acts of smuggling of cultural heritage items.",
    "Under Article 207.3 of the Russian Criminal Code, statements contrary to the official position are considered 'false' by the prosecution when they are intentionally made with the aim of discrediting the state or its authorities, or spreading false information that could potentially harm the public interest or cause significant damage. The prosecution will consider such statements as false if they are deliberately made to mislead the public or undermine the credibility of the state.",
    "There are several factors that have contributed to the decline of independent civil society organizations in Nicaragua:\n\n1. Repressive government policies: The Nicaraguan government, under President Daniel Ortega, has implemented a series of repressive policies that have targeted civil society organizations. These policies include restrictive laws, such as the Foreign Agents Law, which requires organizations receiving foreign funding to register as \"foreign agents\" and submit detailed financial reports. This has created a climate of fear and uncertainty for many organizations, leading to self-censorship and a decline in their activities.\n\n2. Harassment and intimidation: Civil society organizations in Nicaragua have faced harassment and intimidation from government authorities, including surveillance, arbitrary arrests, and physical attacks. Human rights defenders and activists have been particularly targeted, with many facing threats to their personal safety and the safety of their families. This has made it difficult for organizations to operate freely and has deterred many individuals from getting involved in civil society work.\n\n3. Lack of funding: The repressive policies and climate of fear have also made it difficult for civil society organizations to secure funding. Many international donors have been reluctant to support organizations in Nicaragua due to concerns about the government's crackdown on civil society. This has led to a decline in resources available for organizations to carry out their work, including advocacy, research, and service provision.\n\n4. Legal restrictions: The Nicaraguan government has implemented a series of legal restrictions that have made it difficult for civil society organizations to operate. These include laws that limit freedom of association, freedom of expression, and the right to peaceful assembly. Organizations that are critical of the government or engage in activities deemed \"political\" have faced increased scrutiny and legal challenges, further limiting their ability to operate independently.\n\n5. Polarization and division: The political situation in Nicaragua has become increasingly polarized, with the government cracking down on dissent and opposition voices. This has created a climate of fear and mistrust, making it difficult for civil society organizations to collaborate and coordinate their efforts. The lack of unity and solidarity among civil society actors has weakened their collective impact and made it easier for the government to suppress their activities.\n\nOverall, the decline of independent civil society organizations in Nicaragua can be attributed to a combination of repressive government policies, harassment and intimidation, lack of funding, legal restrictions, and polarization. These factors have created a hostile environment for civil society, leading to a decline in their numbers and activities.",
    "Wetlands are designated as Ramsar sites based on the following conditions:\n\n1. The wetland must be of international importance, either ecologically, botanically, zoologically, or hydrologically.\n\n2. The wetland should support a significant number of rare, vulnerable, or endangered species of plants or animals.\n\n3. The wetland should be a habitat for migratory species.\n\n4. The wetland should have exceptional biodiversity or ecological processes.\n\n5. The wetland should provide important services to the local community, such as water purification, flood control, or groundwater recharge.\n\n6. The wetland should have cultural, scientific, educational, or recreational values.\n\n7. The wetland should be under threat from human activities or face potential degradation.\n\n8. The wetland should have effective management and conservation plans in place or the potential to develop them.\n\nThese conditions are assessed by the Ramsar Convention on Wetlands, an international treaty aimed at conserving and sustainably using wetlands worldwide.",
    "COP15 was held in Kunming, China in 2022.",
    "The purpose of the agreement known as 30x30 is to conserve and protect 30% of the planet's land and oceans by the year 2030. This agreement aims to address the global biodiversity crisis and the impacts of climate change by preserving and restoring ecosystems, promoting sustainable land and ocean management practices, and safeguarding the habitats of numerous plant and animal species. The goal is to ensure the long-term health and resilience of the planet's natural resources and to support the well-being of both human and non-human communities.",
    "At COP15, the United Nations Climate Change Conference held in 2009 in Copenhagen, Denmark, the failure to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area was primarily attributed to the governments of several countries. These countries included Canada, Australia, New Zealand, and the United States. These governments were criticized for their reluctance to acknowledge the rights and land claims of Indigenous Peoples, which hindered the inclusion of Indigenous lands as protected areas in the conference's agreements.",
    "Criminalizing abortion can have severe consequences for marginalized individuals, particularly those who are already facing various forms of discrimination and inequality. Some of the consequences include:\n\n1. Health risks: When abortion is criminalized, individuals may resort to unsafe and illegal methods to terminate their pregnancies, leading to serious health complications and even death. Marginalized individuals, who often have limited access to healthcare and resources, are more likely to be affected by these risks.\n\n2. Economic burden: Marginalized individuals, who are more likely to face financial constraints, may struggle to afford safe and legal abortions in countries where it is criminalized. This can lead to increased financial burdens, as they may have to travel long distances or seek expensive underground services.\n\n3. Limited reproductive choices: Criminalizing abortion restricts individuals' reproductive choices and autonomy. Marginalized individuals, who already face various barriers to accessing healthcare and education, may be further limited in their ability to make informed decisions about their reproductive health.\n\n4. Increased inequality: Criminalizing abortion disproportionately affects marginalized individuals, exacerbating existing inequalities. Women from low-income backgrounds, racial and ethnic minorities, LGBTQ+ individuals, and those living in rural areas often face additional barriers to accessing safe and legal abortion services, further widening the gap between privileged and marginalized groups.\n\n5. Criminalization of pregnancy: In some cases, criminalizing abortion can lead to the criminalization of pregnancy itself. This can result in the surveillance and punishment of pregnant individuals, particularly those from marginalized communities, who may be subjected to invasive monitoring, discrimination, and even imprisonment for actions perceived as harmful to the fetus.\n\n6. Mental health impact: The criminalization of abortion can have significant psychological consequences for marginalized individuals. The stigma and shame associated with seeking illegal abortions or being unable to access safe services can lead to increased stress, anxiety, and depression.\n\n7. Reproductive injustice: Criminalizing abortion perpetuates reproductive injustice by denying marginalized individuals the right to control their own bodies and make decisions about their reproductive health. It reinforces systemic inequalities and denies them the same reproductive rights and freedoms enjoyed by more privileged individuals.\n\nIt is important to note that these consequences are not limited to criminalizing abortion alone but are often intertwined with broader social, economic, and healthcare disparities faced by marginalized communities.",
    "Social media companies have a responsibility to ensure access to accurate sexual and reproductive health information. Here are some key responsibilities they should have:\n\n1. Promote accurate information: Social media platforms should actively promote and prioritize accurate sexual and reproductive health information over misinformation or harmful content. This can be done by using algorithms to identify and reduce the visibility of false or misleading information.\n\n2. Fact-checking and verification: Social media companies should invest in fact-checking mechanisms to verify the accuracy of sexual and reproductive health information shared on their platforms. They should work with experts and organizations specializing in sexual and reproductive health to ensure the information is reliable and evidence-based.\n\n3. Transparency and disclosure: Social media companies should be transparent about their content moderation policies and algorithms. They should disclose how they handle sexual and reproductive health information and what measures they take to ensure accuracy. This transparency will help users understand the reliability of the information they encounter.\n\n4. Collaborate with experts and organizations: Social media companies should collaborate with reputable experts, organizations, and health authorities to develop guidelines and standards for accurate sexual and reproductive health information. They should seek input from these stakeholders to ensure that their policies and practices align with the latest scientific evidence and best practices.\n\n5. User education and awareness: Social media companies should invest in user education and awareness campaigns to help users identify accurate sexual and reproductive health information. This can include providing tips on how to evaluate the credibility of sources, recognizing misinformation, and understanding the importance of evidence-based information.\n\n6. Reporting and addressing misinformation: Social media platforms should have clear and accessible mechanisms for users to report misinformation related to sexual and reproductive health. They should promptly investigate and take appropriate action against accounts or content that spread false or harmful information.\n\n7. Accessibility and inclusivity: Social media companies should ensure that accurate sexual and reproductive health information is accessible to all users, including those with disabilities or from marginalized communities. They should consider the needs of diverse populations and provide information in multiple languages and formats.\n\n8. Continuous improvement: Social media companies should regularly evaluate and improve their policies, algorithms, and practices related to sexual and reproductive health information. They should stay updated with the latest research and feedback from users and experts to adapt their approaches and address emerging challenges.\n\nBy fulfilling these responsibilities, social media companies can play a crucial role in promoting accurate sexual and reproductive health information and empowering users to make informed decisions about their health.",
    "Social media companies play a crucial role in protecting users' rights online, regardless of their language and political views. Here are some key aspects of their role:\n\n1. Content moderation: Social media companies have the responsibility to moderate and remove content that violates their community guidelines, including hate speech, harassment, and misinformation. This helps protect users from harmful and abusive content, ensuring a safer online environment.\n\n2. Privacy and data protection: Companies must safeguard users' personal information and ensure their privacy rights are respected. This involves implementing robust data protection measures, obtaining user consent for data collection and usage, and providing transparent privacy policies.\n\n3. Algorithmic transparency: Social media platforms use algorithms to curate and personalize content for users. Ensuring transparency in these algorithms is crucial to prevent bias, discrimination, and the manipulation of information. Companies should disclose how algorithms work and take steps to address any unintended consequences.\n\n4. Accessibility and inclusivity: Social media companies should strive to make their platforms accessible to users of all languages and abilities. This includes providing language options, captioning for videos, and features that accommodate users with disabilities, ensuring equal access to information and participation.\n\n5. Fighting disinformation: Companies should actively combat the spread of disinformation and fake news on their platforms. This involves implementing fact-checking mechanisms, partnering with credible sources, and promoting media literacy to help users distinguish between reliable and misleading information.\n\n6. Transparency and accountability: Social media companies should be transparent about their policies, practices, and decision-making processes. They should provide clear avenues for users to report issues, appeal content removals, and seek redress. Regular transparency reports can help build trust and hold companies accountable.\n\n7. Collaboration with external stakeholders: Companies should collaborate with governments, civil society organizations, and experts to develop policies and practices that protect users' rights. Engaging in multi-stakeholder dialogues helps ensure diverse perspectives are considered and fosters a collective effort to address online challenges.\n\nOverall, social media companies have a responsibility to create a safe, inclusive, and rights-respecting online environment for all users, regardless of their language and political views.",
    "Amnesty International has documented several labor abuses in Qatar, particularly in relation to the kafala system. The kafala system is a sponsorship-based employment system that ties migrant workers to their employers, giving employers significant control over their workers' lives and rights. Here are some of the labor abuses documented:\n\n1. Exploitative working conditions: Migrant workers in Qatar often face long working hours, with some working up to 12 hours a day, six or seven days a week. They are also subjected to dangerous and hazardous working conditions, especially in the construction sector.\n\n2. Withheld wages: Many workers have reported that their employers withhold their wages for months, sometimes even years. This practice leaves workers in a vulnerable position, unable to leave their jobs or seek alternative employment.\n\n3. Passport confiscation: Employers often confiscate the passports of migrant workers, depriving them of their freedom of movement and making it difficult for them to leave the country or change jobs. This practice is a clear violation of workers' rights and leaves them trapped in exploitative situations.\n\n4. Forced labor and human trafficking: Amnesty International has documented cases of forced labor and human trafficking in Qatar. Some workers are deceived about the nature of their work or are forced to work against their will, often in conditions akin to modern-day slavery.\n\n5. Inadequate living conditions: Migrant workers in Qatar often live in overcrowded and unsanitary accommodation provided by their employers. These living conditions are substandard and do not meet basic human rights standards.\n\nThese labor abuses are directly linked to the kafala system, which gives employers excessive power and control over migrant workers. The system ties workers to their employers, making it difficult for them to assert their rights or seek redress for abuses. The kafala system creates a power imbalance that enables employers to exploit workers, leading to the documented labor abuses in Qatar.",
    "The government of Qatar started repealing restrictions on migrant workers in 2017."
  ],
  "contexts": [
    [
      "- In 2022, the USA Supreme Court handed down a decision ruling that overturned 50 years of jurisprudence recognizing a constitutional right to abortion.\n- This decision has had a massive impact: one in three women and girls of reproductive age now live in states where abortion access is either totally or near-totally inaccessible.\n- The states with the most restrictive abortion laws have the weakest maternal health support, higher maternal death rates, and higher child poverty rates.\n- The USA Supreme Court ruling has also had impacts beyond national borders due to the geopolitical and cultural influence wielded by the USA globally and the aid it funds.\n- SRR organizations and activists across the world have expressed fear about the ruling laying the groundwork for anti-abortion legislative and policy attacks in other countries.\n- Advocates have also observed the ruling's impact on progressive law reform and the stalling of the adoption and enforcement of abortion guidelines in certain African countries.\n- The ruling has created a chilling effect in international policy spaces, emboldening anti-abortion state and non-state actors to undermine human rights protections.",
      "The USA Supreme Court ruling on abortion has sparked intense debates and discussions not only within the country but also around the world. Many countries look to the United States as a leader in legal and social issues, so the decision could potentially influence the policies and attitudes towards abortion in other nations.",
      "The ruling may also impact international organizations and non-governmental groups that work on reproductive rights and women's health issues. Depending on the outcome, there could be shifts in funding, advocacy efforts, and collaborations with American counterparts, leading to ripple effects in the global fight for reproductive justice."
    ],
    [
      "In recent years, there has been increasing pressure on these major contributors to reduce their greenhouse gas emissions and transition to more sustainable practices. Many of these companies have made commitments to reduce their carbon footprint and invest in renewable energy sources. However, the role of these companies in global warming remains a contentious issue, with ongoing debates about their responsibility and accountability for the environmental damage caused by their operations.",
      "The Carbon Majors database identifies a small group of companies responsible for the majority of global greenhouse gas emissions. These companies include major oil and gas producers, as well as coal mining companies, whose activities have significantly contributed to climate change. The data from the Carbon Majors database highlights the disproportionate impact of these companies on the environment and the urgent need for action to address their emissions.",
      "- Fossil fuel companies, whether state or private, play a key role in the emissions that drive global warming.\n- According to the Carbon Majors database, 100 existing fossil fuel companies (and eight that no longer exist) have produced almost a trillion tons of GHG emissions in 150 years.\n- These 100 companies are responsible for 71% of all GHG emissions since 1988.\n- In the Americas, the private companies responsible for the most emissions during this period, according to the database, are from the United States: ExxonMobil, Chevron, and Peabody.\n- The largest emitter amongst state-owned companies in the Americas is Mexican company Pemex, followed by Venezuelan company Petr\u00f3leos de Venezuela, S.A.\n- Despite the fact that people with fewer resources, in particular from countries in the global South, do not make significant contributions to climate change, it is these people who are most affected by it.\n- Approximately half of the global population lives in areas that are \"very vulnerable\" to climate change, and it is people with considerable development constraints who are most exposed.\n- This disproportionately affects the human rights of people with fewer resources and greater risk in the context of climate change in the global South.\n- Between 2010 and 2020, human mortality due to climate disasters was 15 times higher in vulnerable regions and populations."
    ],
    [
      "The issue of greenhouse gas emissions has become a major concern for environmentalists and policymakers alike, as the impact of climate change becomes more apparent. Private companies in the Americas play a significant role in contributing to these emissions, with some being identified as the largest emitters in the region according to the Carbon Majors database.",
      "Reducing greenhouse gas emissions from private companies is a complex challenge that requires cooperation between governments, businesses, and consumers. Many companies are now taking steps to reduce their carbon footprint through initiatives such as investing in renewable energy, improving energy efficiency, and offsetting emissions through carbon credits.",
      "The private companies responsible for the most emissions during this period, according to the database, are from the United States: ExxonMobil, Chevron and Peabody.\nThe largest emitter amongst state-owned companies in the Americas is Mexican company Pemex, followed by Venezuelan company Petr\u00f3leos de Venezuela, S.A."
    ],
    [
      "In the case of the Ogoni 9, Amnesty International called on its supporters to take action by signing petitions, writing letters to government officials, and participating in protests and demonstrations. The organization also urged its members to raise awareness about the plight of the Ogoni people and the need for justice and accountability in their case. By mobilizing public pressure and solidarity, Amnesty International hoped to bring attention to the human rights abuses committed against the Ogoni 9 and to push for meaningful change and accountability.",
      "Amnesty International called on its vast network of supporters to deluge Nigerian authorities first with appeals for the defenders\u2019 freedom, and later with letters of outrage.",
      "Amnesty International is a global human rights organization known for its advocacy work on behalf of individuals facing injustice and persecution. The organization has a long history of campaigning for the rights of prisoners of conscience, political dissidents, and marginalized communities around the world. Through its research, lobbying efforts, and grassroots activism, Amnesty International seeks to hold governments and other powerful entities accountable for human rights violations and abuses."
    ],
    [
      "In recent years, Amnesty International has focused on issues such as the increasing threats faced by human rights defenders, particularly in authoritarian regimes, and the need for stronger international mechanisms to support and protect their work. The organization's recommendations to the Special Rapporteur often include calls for greater accountability for perpetrators of violence and harassment against defenders, as well as measures to ensure their safety and freedom to carry out their important work.",
      "Amnesty International recommends that the Special Rapporteur on the Situation of Human Rights Defenders embeds a focus on child and young HRDs in the future work of the mandate. \nAmnesty International recommends raising awareness about the differences between \"child\" and \"youth\" HRDs and the different context, needs, barriers, and challenges they face as defenders. \nAmnesty International recommends incorporating age disaggregated data on the lived experiences of child and young HRDs in all future reports or interventions by the Special Rapporteur. \nAmnesty International recommends creating online and face-to-face safe spaces for child and young HRDs and their child and youth-led organizations to actively engage with the Special and other human rights mechanisms.",
      "Amnesty International is known for its advocacy work on behalf of human rights defenders around the world. The organization often provides detailed reports and recommendations to the Special Rapporteur on Human Rights Defenders, highlighting specific cases of abuse and calling for action to protect those at risk."
    ],
    [
      "In addition to children, parents, teachers, and caregivers are also key target audiences for Amnesty International's books on child rights. These adults play a crucial role in guiding and supporting children as they learn about their rights and responsibilities. By reading and discussing these books together, families and educators can help instill values of equality, respect, and compassion in the next generation.",
      "Amnesty International's books on child rights are designed to educate and empower young readers about their rights and the importance of standing up for justice. The colorful illustrations and engaging storytelling make these books accessible to children of various ages and backgrounds, sparking their curiosity and empathy for others.",
      "Amnesty International has therefore created two simple books on child rights and how to claim them for self and others: (1) \u2018Know Your Rights and Claim Them: A Guide for Youth\u2019, by Amnesty International, Angelina Jolie, Geraldine van Bueren (Andersen Press 2021); (2) \u2018These Rights Are Your Rights: An empowering guide for children everywhere\u2019, by Nicky Parker at Amnesty International (Andersen Press, 2024).\nThe objectives of the two books are to build children\u2019s and young people\u2019s understanding of their rights and give them the awareness and tools they need to take action."
    ],
    [
      "The right to truth is a fundamental human right that seeks to uncover the full extent of past human rights violations and ensure accountability for those responsible. This right includes access to official records, archives, and other sources of information that shed light on historical injustices and atrocities.",
      "In many countries, the pursuit of truth and justice for past human rights violations is a complex and often contentious process. Governments, institutions, and individuals may resist efforts to uncover the truth, leading to challenges in achieving transparency and accountability. The right to truth is essential for promoting reconciliation, healing, and preventing future abuses.",
      "26. The Act raises serious questions about its compatibility with the right to truth.\n27. At an individual level, victims and their families possess an inalienable and non-derogable right to know the truth regarding the circumstances and reasons behind human rights violations, including the identities of the perpetrators and, in cases of death or enforced disappearance, the fate of the victims.\nIn particular, the right to know the fate and whereabouts of \u2018disappeared\u2019 relatives has been confirmed in the jurisprudence of international and regional human rights bodies, as well as of national courts."
    ],
    [
      "In many cases, the identities of perpetrators of human rights violations are shielded from public knowledge, either due to political reasons or lack of evidence. This lack of transparency can hinder efforts to seek justice for victims and hold those responsible accountable for their actions. The right to know the fate of victims is equally important, as it allows families and communities to grieve, seek closure, and work towards healing and reconciliation.",
      "- The victims of gross human rights violations and their families, as well as members of society generally, have the right to know the whole truth about past human rights violations.\n- The right to truth is engaged by the violation of the rights to access to justice, remedy, and information.\n- Victims and their families possess an inalienable and non-derogable right to know the truth regarding the circumstances and reasons behind human rights violations, including the identities of the perpetrators and the fate of the victims.\n- The right to know the fate and whereabouts of 'disappeared' relatives has been confirmed in the jurisprudence of international and regional human rights bodies, as well as of national courts.",
      "The concept of universal human rights has evolved over centuries, with various international declarations and treaties outlining the fundamental rights that all individuals are entitled to. These rights are considered inherent to all human beings, regardless of nationality, ethnicity, or any other distinguishing factor. The idea that everyone should be fully informed about human rights violations stems from the belief that transparency and accountability are essential for upholding these rights and preventing future abuses."
    ],
    [
      "Article 207.3 of the Russian Criminal Code pertains to the illegal acquisition, transfer, sale, storage, transportation, or carrying of firearms, their main parts, ammunition, explosives, and explosive devices. This law aims to regulate the possession and use of dangerous weapons to maintain public safety and order.",
      "- As long as their statements are contrary to the official position of the Russian authorities, they can be regarded by the prosecution and courts as \"false\" and individuals are found guilty under Article 207.3.\n- Official information regarding Russia's full-scale invasion of Ukraine has been riddled with false and deliberately misleading messages and claims.\n- Debunking such information and providing independent analysis of the situation has been expressly criminalized.\n- Accordingly, Article 207.3 acts as a tool of wartime censorship.\n- Prosecution for \"dissemination of knowingly false information\" under Article 207.3 contributes to impunity for violations of the laws and customs of war.\n- The claim that Roman Ivanov's actions were \"in violation of constitutional order\" do not stand scrutiny either, as Article 207.3 of the Criminal Code is contrary to the provisions of the Russian Constitution itself.\n- Article 2 of the Russian Constitution proclaims human rights and freedoms as the highest value and their defense as the duty of the state.\n- Article 17 further declares that human rights and freedoms are guaranteed \"in accordance with the recognized principles and norms of international law and this Constitution.\"\n- Article 29 guarantees freedom of thought and speech, freedom to seek, receive, share, produce and disseminate information, and media freedom.\n- At the same time, it prohibits censorship.",
      "In addition to the legal implications, individuals found guilty under Article 207.3 may face severe penalties, including fines, imprisonment, or other restrictions on their rights and freedoms. The enforcement of this law is crucial in preventing criminal activities involving firearms and explosives in Russia."
    ],
    [
      "- As long as their statements are contrary to the official position of the Russian authorities, they can be regarded by the prosecution and courts as \u201cfalse\u201d and individuals are found guilty under Article 207.3.\n- Official information regarding Russia\u2019s full-scale invasion of Ukraine has been riddled with false and deliberately misleading messages and claims.\n- Debunking such information and providing independent analysis of the situation has been expressly criminalized.\n- Accordingly, Article 207.3 acts as a tool of wartime censorship.\n- Prosecution for \"dissemination of knowingly false information\" under Article 207.3 contributes to impunity for violations of the laws and customs of war.\n- The claim that Roman Ivanov\u2019s actions were \"in violation of constitutional order\" do not stand scrutiny either, as Article 207.3 of the Criminal Code is contrary to the provisions of the Russian Constitution itself.\n- Article 2 of the Russian Constitution proclaims human rights and freedoms as the highest value and their defense as the duty of the state.\n- Article 29 guarantees freedom of thought and speech, freedom to seek, receive, share, produce and disseminate information and media freedom.\n- At the same time, it prohibits censorship.",
      "In legal proceedings, the prosecution may consider statements contrary to the official position as 'false' under Article 207.3 when they are deemed to be intentionally misleading or deceptive. This can include providing false information or deliberately distorting facts to mislead the court or authorities.",
      "The determination of whether statements are considered 'false' under Article 207.3 is based on the intent behind the statements and the impact they have on the legal proceedings. If the prosecution believes that the statements were made with the purpose of obstructing justice or undermining the truth, they may be classified as 'false' and subject to legal consequences."
    ],
    [
      "The economic challenges facing Nicaragua have also played a role in the decline of independent civil society organizations. Limited funding opportunities, coupled with a shrinking space for civic engagement, have made it difficult for these organizations to sustain their operations and carry out their missions effectively.",
      "- \"arrests and harassment of human rights defenders, restrictive NGO laws and violent repression of protests have been decimating independent civil society organizations for years.\"\n- \"The closure of civil society organizations and our rural community centers, which for more than 40 years have worked in defense of SRR and human rights in general.\"\n- \"The expropriation of their belongings and premises.\"\n- \"The criminalization of social organizing and mobilization and of freedom of expression.\"\n- \"The implementation of repressive laws that breach the human rights of the population to suit the wishes of the regime.\"\n- \"The constant threats of arrest and detention of those who protest and the restrictions on social media.\"\n- \"The silence imposed through violence and repression.\"\n- \"As a result, the activities of our feminist community organization are severely limited right now.\"",
      "Nicaragua's political landscape has undergone significant changes in recent years, leading to increased government control and restrictions on independent civil society organizations. The government's crackdown on dissent and opposition has resulted in the closure of many NGOs and civil society groups, limiting their ability to operate freely and advocate for social change."
    ],
    [
      "Wetlands designated as Ramsar sites must meet specific criteria outlined by the Ramsar Convention, an international treaty aimed at conserving wetlands and their resources. These criteria include the presence of rare or unique ecosystems, the support of a diverse range of plant and animal species, and the provision of essential services such as water purification and flood control.",
      "The Ramsar Convention, signed in 1971 in Ramsar, Iran, has designated over 2,000 wetlands worldwide as Ramsar sites. These sites are recognized for their ecological importance and are protected under international law to ensure their conservation for future generations.",
      "- \"Ramsar sites are designated when they fulfil the criteria for identifying wetlands of international importance.\"\n- \"These criteria were established under the Convention on Wetlands, an intergovernmental agreement containing a framework for the conservation and wise use of wetlands and their resources.\""
    ],
    [
      "The city of Kunming, located in the Yunnan province of China, is known for its stunning natural landscapes and diverse ecosystems. It served as the perfect backdrop for COP15, allowing delegates to immerse themselves in the beauty of nature while discussing crucial environmental issues.",
      "- These include the agreement known as 30x30, adopted at the UN Conference on Biological Diversity (COP15) held in Montreal, Canada, in late 2022.\n- Unfortunately, at COP15, States failed to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area, and this threatens their rights.",
      "COP15, also known as the 15th meeting of the Conference of the Parties to the Convention on Biological Diversity, was held in Kunming, China in 2022. The conference aimed to address the global biodiversity crisis and set ambitious targets for conservation and sustainable development."
    ],
    [
      "The 30x30 agreement aims to protect 30% of the world's land and oceans by the year 2030. This ambitious goal is seen as crucial in preserving biodiversity and combating the effects of climate change. By setting aside these areas as protected zones, it is hoped that ecosystems can thrive and species can be safeguarded for future generations.",
      "The 30x30 agreement has garnered support from various governments, environmental organizations, and indigenous groups around the world. It represents a global effort to address the urgent need for conservation and sustainable land management practices. Through this agreement, countries are committing to prioritize the protection of natural habitats and the promotion of biodiversity.",
      "- These include the agreement known as 30x30, adopted at the UN Conference on Biological Diversity (COP15) held in Montreal, Canada, in late 2022, which commits Parties to designate 30% of the world's land and sea masses as protected areas for biodiversity conservation by 2030.\n- Protecting and restoring these ecosystems is one of the most efficient, equitable and cost-effective mechanisms to capture and store carbon without compromising human rights.\n- However, the focus of the agreement should not be limited to the amount of area it covers, but rather to how it is managed, who selects the areas, and what biodiversity exists in them.\n- Indigenous Peoples and local communities have a key role to play here.\n- Unfortunately, at COP15, States failed to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area, and this threatens their rights."
    ],
    [
      "The lack of explicit recognition of Indigenous Peoples' lands and territories as a distinct category of protected area at COP15 highlights the ongoing challenges in balancing conservation efforts with respect for Indigenous rights and sovereignty. This issue has sparked debates about the need for more inclusive and equitable decision-making processes in global conservation initiatives.",
      "The issue of recognizing Indigenous Peoples' lands and territories as a distinct category of protected area at COP15 has been a point of contention among various stakeholders. While some argue that Indigenous Peoples' traditional knowledge and practices are essential for effective conservation efforts, others believe that a one-size-fits-all approach is more practical and efficient in achieving conservation goals.",
      "Unfortunately, at COP15, States failed to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area, and this threatens their rights."
    ],
    [
      "- Abortion criminalization contributes to stigma around abortion and particularly on those who need, provide or assist with abortion services.\n- Criminalization, lack of information, disinformation, and stigma have severe and irreversible effects, particularly on marginalized individuals.\n- Girls and young women are kept in the dark about their rights and often forced to bring to term pregnancies resulting from sexual violence.\n- Marginalized individuals, including those living in poverty, historically discriminated against, Indigenous and Afro-descendent women, migrants, and refugees, are disproportionately affected by abortion criminalization.\n- Criminalization of abortion is the biggest contributing factor to the estimated 35 million unsafe abortions happening every year, increasing maternal mortality and morbidity.\n- Criminalizing abortion undermines access to health services and leads to increased rates of preventable maternal mortality and morbidity.\n- Abortion criminalization forces women, girls, and all pregnant individuals to attempt unsafe clandestine abortion methods, placing their life and health at risk.\n- Abortion laws in Nigeria are restrictive, making abortion unsafe and difficult to access safe abortion care.",
      "In countries where abortion is illegal or highly restricted, marginalized individuals, such as low-income women, young girls, and immigrants, are disproportionately affected. They may resort to unsafe and clandestine methods to terminate a pregnancy, putting their lives at risk. The criminalization of abortion can further perpetuate cycles of poverty, inequality, and discrimination, as marginalized individuals are denied the autonomy to make decisions about their own bodies and futures.",
      "The debate over abortion has been a contentious issue for decades, with strong opinions on both sides of the argument. The criminalization of abortion can have far-reaching consequences for marginalized individuals, particularly those who may not have access to safe and legal options for terminating a pregnancy. This can lead to increased health risks, financial burdens, and emotional distress for those who are already facing systemic barriers to healthcare and support services."
    ],
    [
      "Social media companies play a significant role in shaping public discourse and disseminating information on a wide range of topics, including sexual and reproductive health. As such, they have a responsibility to ensure that the information shared on their platforms is accurate, reliable, and evidence-based. This includes taking steps to combat misinformation and disinformation that can harm individuals' health and well-being.",
      "Social media companies involved in facilitating and moderating online content need to invest adequate resources in human oversight of artificial intelligence-driven content moderation systems to ensure all users can equally exercise their rights online, regardless of language and political views and ensure that they can access accurate sexual and reproductive health-related information, including on the right to abortion. They should also uphold their human rights responsibilities by engaging in human rights due diligence, including to address risks and abuses arising from their business model.",
      "In recent years, there has been growing concern about the spread of false or misleading information related to sexual and reproductive health on social media platforms. This has led to calls for greater accountability and transparency from these companies in terms of monitoring and regulating the content that is shared on their platforms. By taking proactive measures to promote accurate information and combat misinformation, social media companies can help to empower individuals to make informed decisions about their sexual and reproductive health."
    ],
    [
      "Companies, including social media companies, have a responsibility to respect all human rights wherever they operate in the world.\nSocial media companies involved in facilitating and moderating online content need to invest adequate resources in human oversight of artificial intelligence-driven content moderation systems to ensure all users can equally exercise their rights online, regardless of language and political views.\nThey should uphold their human rights responsibilities by engaging in human rights due diligence, including to address risks and abuses arising from their business model.\nThey should undertake proactive measures in educating users and raising awareness about security and privacy features on their platforms that will help WHRDs create a safer and less toxic online experience.",
      "Social media companies have faced increasing scrutiny over their handling of user data and privacy concerns. The Cambridge Analytica scandal, in which Facebook data was used to influence political campaigns, highlighted the need for greater transparency and accountability in the industry. As a result, companies like Facebook and Twitter have implemented stricter policies and measures to protect users' rights and prevent misuse of their platforms.",
      "The issue of online censorship and freedom of speech has also been a contentious topic for social media companies. Balancing the need to protect users from harmful content while also upholding principles of free expression is a delicate task. Companies must navigate complex legal and ethical considerations when deciding what content to allow or remove, taking into account the diverse perspectives and values of their global user base."
    ],
    [
      "The kafala system in Qatar, which ties a migrant worker's legal status to their employer, has been identified as a key factor contributing to the labor abuses documented by Amnesty International. This system gives employers significant control over their workers, making it difficult for them to leave abusive situations or seek justice for violations of their rights.",
      "Amnesty International's report on labor abuses in Qatar highlighted the widespread exploitation of migrant workers, including long working hours, low wages, and poor living conditions. These violations of human rights have raised concerns globally and put pressure on the Qatari government to reform its labor laws and practices.",
      "During the tournament, Amnesty International documented how one company providing guards to an international hotel chain in Doha was permitting workers only one day off each month, threatening salary cuts if they took more rest time, failing to provide pay slips and housing them in dirty and overcrowded accommodation with six people per room in bunkbeds.\nUntil 2020, Qatar\u2019s inherently abusive kafala sponsorship system imposed tight restrictions on migrant workers\u2019 freedom of movement, prohibiting them from leaving the country or changing jobs without the permission of their employer.\nBetween 2018 and 2020, the government took important steps towards tackling two central pillars of this system by repealing for most migrant workers the requirement to obtain from their employer an 'exit permit\u2019 to leave the country, and a \u2018no-objection certificate\u2019 (NOC) to change jobs.\nSuch reliance means abusive employers can \u2013 and still do \u2013 depend on an array of tools to control their workforce. This includes cancelling or refraining from renewing workers\u2019 residence permits, or falsely reporting employees as having \u201cabsconded\u201d from their job (when they could be trying to escape abuse) - all of which can lead to workers being arrested and deported.\nOther barriers to workers changing jobs freely have emerged over the last few years, limiting the impact of the reforms and maintaining the status quo. These include the unwritten \u2013 but often spoken \u2013 need for workers to secure \u201crelease papers\u201d, a resignation letter, or any equivalent of an NOC, from their current employers in order to successfully move jobs, and the malicious use by employers of the Labour Law\u2019s non-compete clause to effectively ban workers from changing jobs under the guise that they are going to work for direct competitors."
    ],
    [
      "Qatar's efforts to improve the rights and working conditions of migrant workers have been widely praised by international organizations and human rights advocates. The government's decision to gradually repeal restrictions and implement reforms has been seen as a positive step towards addressing long-standing issues in the country's labor system.",
      "Between 2018 and 2020, the government took important steps towards tackling two central pillars of this system by repealing for most migrant workers the requirement to obtain from their employer an 'exit permit\u2019 to leave the country, and a \u2018no -objection certificate\u2019 (NOC) to change jobs.\nOther barriers to workers changing jobs freely have emerged over the last few years, limiting the impact of the reforms and maintaining the status quo.\nThese include the unwritten \u2013 but often spoken \u2013 need for workers to secure \u201crelease papers\u201d, a resignation letter, or any equivalent of an NOC, from their current employers in order to successfully move jobs.",
      "The changes in Qatar's labor laws have also been linked to the country's preparations for hosting the FIFA World Cup in 2022. The government's commitment to ensuring fair treatment and protection for migrant workers has been a key focus in the lead-up to the tournament, with various initiatives and policies being introduced to uphold these principles."
    ]
  ],
  "ground_truth": [
    "The global implications of the USA Supreme Court ruling on abortion are significant. The ruling has led to limited or no access to abortion for one in three women and girls of reproductive age in states where abortion access is restricted. These states also have weaker maternal health support, higher maternal death rates, and higher child poverty rates. Additionally, the ruling has had an impact beyond national borders due to the USA's geopolitical and cultural influence globally. Organizations and activists worldwide are concerned that the ruling may inspire anti-abortion legislative and policy attacks in other countries. The ruling has also hindered progressive law reform and the implementation of abortion guidelines in certain African countries. Furthermore, the ruling has created a chilling effect in international policy spaces, empowering anti-abortion actors to undermine human rights protections.",
    "According to the Carbon Majors database, the main contributors to GHG emissions and their role in global warming are fossil fuel companies. These companies, both state-owned and private, have produced almost a trillion tons of GHG emissions in 150 years. The database shows that 100 existing fossil fuel companies, along with eight that no longer exist, are responsible for 71% of all GHG emissions since 1988. In the Americas, the private companies that have contributed the most emissions are ExxonMobil, Chevron, and Peabody, all from the United States. Among state-owned companies in the Americas, the largest emitter is Mexican company Pemex, followed by Venezuelan company Petr\u00f3leos de Venezuela, S.A. It is important to note that while people with fewer resources, particularly from countries in the global South, do not significantly contribute to climate change, they are the ones most affected by its impacts. Approximately half of the global population lives in areas that are \"very vulnerable\" to climate change, and it is people with limited development opportunities who face the greatest risks. This unequal impact disproportionately affects the human rights of those with fewer resources and greater vulnerability in the context of climate change in the global South. Additionally, between 2010 and 2020, human mortality due to climate disasters was 15 times higher in vulnerable regions and populations.",
    "The largest private companies in the Americas that are the largest GHG emitters according to the Carbon Majors database are ExxonMobil, Chevron, and Peabody.",
    "Amnesty International urged its supporters to send appeals for the defenders' freedom to Nigerian authorities and later to send letters of outrage.",
    "The recommendations made by Amnesty International to the Special Rapporteur on Human Rights Defenders include embedding a focus on child and young HRDs in future work, raising awareness about the differences and challenges they face, incorporating age disaggregated data in reports, and creating safe spaces for engagement.",
    "The target audience of the two books created by Amnesty International on child rights are children and young people.",
    "The right that guarantees access to comprehensive information about past human rights violations, including the identities of the perpetrators and the fate of the victims, as well as the circumstances surrounding the violations, is the right to know the truth.",
    "The victims of gross human rights violations and their families, as well as members of society generally, have the right to be fully informed about human rights violations, including the identities of the perpetrators and the fate of the victims.",
    "Individuals can be found guilty under Article 207.3 of the Russian Criminal Code if their statements are contrary to the official position of the Russian authorities.",
    "The prosecution considers statements contrary to the official position as 'false' under Article 207.3 when they are in opposition to the official position of the Russian authorities.",
    "The factors that have contributed to the decline of independent civil society organizations in Nicaragua include arrests and harassment of human rights defenders, restrictive NGO laws, violent repression of protests, closure of civil society organizations and community centers, expropriation of belongings and premises, criminalization of social organizing and mobilization, restrictions on freedom of expression, implementation of repressive laws, constant threats of arrest and detention, restrictions on social media, and the imposition of silence through violence and repression.",
    "The conditions that designate wetlands as Ramsar sites are when they fulfill the criteria for identifying wetlands of international importance, as established under the Convention on Wetlands.",
    "COP15 was held in Montreal, Canada in 2022.",
    "The purpose of the agreement known as 30x30 is to designate 30% of the world's land and sea masses as protected areas for biodiversity conservation by 2030.",
    "The States failed to explicitly recognize Indigenous Peoples' lands and territories as a distinct category of protected area at COP15.",
    "The consequences of criminalizing abortion for marginalized individuals include increased stigma, lack of information, and disinformation. This can have severe and irreversible effects on these individuals. Girls and young women may be forced to carry pregnancies resulting from sexual violence due to a lack of knowledge about their rights. Marginalized individuals, such as those living in poverty, historically discriminated against, Indigenous and Afro-descendent women, migrants, and refugees, are disproportionately affected by abortion criminalization. The criminalization of abortion is a major factor contributing to the high number of unsafe abortions, which leads to increased maternal mortality and morbidity. Access to health services is undermined, resulting in preventable maternal deaths and complications. Marginalized individuals are forced to resort to unsafe clandestine abortion methods, putting their lives and health at risk. In Nigeria, restrictive abortion laws make it difficult to access safe abortion care.",
    "Social media companies should have the responsibility to invest in human oversight of their content moderation systems to ensure equal access to accurate sexual and reproductive health information. They should also engage in human rights due diligence to address risks and abuses related to their business model.",
    "Social media companies play a role in protecting users' rights online, regardless of their language and political views, by investing in human oversight of content moderation systems, engaging in human rights due diligence, and educating users about security and privacy features.",
    "Amnesty International documented labor abuses in Qatar, including workers being permitted only one day off each month, threats of salary cuts for taking more rest time, failure to provide pay slips, and overcrowded and dirty living conditions. These labor abuses relate to the kafala system because the kafala system imposes tight restrictions on migrant workers' freedom of movement and ability to change jobs without their employer's permission. This system allows abusive employers to control their workforce by canceling residence permits, falsely reporting employees as absconding, and using non-compete clauses to prevent workers from changing jobs.",
    "The government of Qatar started repealing restrictions on migrant workers between 2018 and 2020."
  ]
}

Simple example for POC

import json
from ragas import EvaluationDataset, SingleTurnSample, evaluate
from ragas.metrics import LLMContextRecall, FactualCorrectness, Faithfulness
from ragas.llms import LangchainLLMWrapper
from langchain.chat_models import ChatOpenAI
import pandas as pd

Path to your JSON file

json_file_path = “your_json_file.json”

Open the JSON file and load the data

with open(json_file_path, “r”) as f:
data = json.load(f)

Extract questions, answers, and contexts from the JSON data

questions = data[“question”]
answers = data[“answer”]
contexts = data.get(“contexts”, []) # Handle optional contexts

Create samples for evaluation dataset

samples = []
for i in range(len(questions)):
sample = SingleTurnSample(
user_input=questions[i],
reference=answers[i],
response=None, # We don’t have a model-generated response for now
retrieved_contexts=contexts[i] if i < len(contexts) else []
)
samples.append(sample)

Create evaluation dataset

eval_dataset = EvaluationDataset(samples=samples)

Define your LLM using Langchain’s OpenAI wrapper for GPT-4

evaluator_llm = LangchainLLMWrapper(ChatOpenAI(model=”gpt-4″))

Define metrics to evaluate

metrics = [LLMContextRecall(), FactualCorrectness(), Faithfulness()]

Evaluate the LLM on the dataset

results = evaluate(dataset=eval_dataset, metrics=metrics, llm=evaluator_llm)

Display results in pandas DataFrame (if pandas is installed)

if pd is not None:
df = results.to_pandas()
print(df.head())

———————————————–

Retrieval component using FAISS

  1. import faiss
  2. import numpy as np# Sample documents (replace with your corpus)
  3. documents = [ “The Eiffel Tower is in Paris.”, “The Great Wall of China is visible from space.”, “Python is a programming language.”]# Convert documents into vector embeddings (for simplicity, use random vectors here)document_embeddings = np.random.random((len(documents), 512)).astype(‘float32’)# Set up FAISS index for retrievalindex = faiss.IndexFlatL2(512)index.add(document_embeddings)# Function to retrieve documentsdef retrieve_documents(query_embedding, top_k=2): _, retrieved_indices = index.search(query_embedding, top_k) return [documents[idx] for idx in retrieved_indices[0]]
  4. Generate component
  5. import openai
  6. # Set up your OpenAI API key
  7. openai.api_key = ‘your-openai-api-key’# Function to generate responses using OpenAI’s GPT modeldef generate_response(prompt): response = openai.Completion.create( engine=”text-davinci-003″, prompt=prompt, max_tokens=150 ) return response[‘choices’][0][‘text’]
  8. 3. RAG pipeline setup
  9. def rag_pipeline(query): # Convert query into a vector embedding (for simplicity, use random vectors) query_embedding = np.random.random((1, 512)).astype(‘float32’) # Retrieve relevant documents retrieved_docs = retrieve_documents(query_embedding) # Combine retrieved docs into a prompt for the generative model prompt = “Based on the following information:\n” + “\n”.join(retrieved_docs) + “\nAnswer the question: ” + query # Generate response using OpenAI response = generate_response(prompt) return response
  10. 4. Integrate Ragas testing framework
  11. import ragas# Sample queries and expected responsestest_data = [ { “query”: “Where is the Eiffel Tower?”, “expected”: “The Eiffel Tower is in Paris.” }, { “query”: “What is Python?”, “expected”: “Python is a programming language.” }]# Running tests with RAGASfor test_case in test_data: query = test_case[‘query’] expected_response = test_case[‘expected’] # Get model’s response from the RAG pipeline generated_response = rag_pipeline(query) # Use RAGAS evaluation metrics to assess the response relevance = ragas.evaluate_relevance(generated_response, expected_response) coherence = ragas.evaluate_coherence(generated_response) # Print the evaluation results print(f”Query: {query}”) print(f”Generated Response: {generated_response}”) print(f”Expected Response: {expected_response}”) print(f”Relevance Score: {relevance}”) print(f”Coherence Score: {coherence}”) print(“———“)
  12. 5. Ragas test results
  13. Query: Where is the Eiffel Tower?Generated Response: The Eiffel Tower is located in Paris, France.Expected Response: The Eiffel Tower is in Paris.Relevance Score: 0.95Coherence Score: 0.90———Query: What is Python?Generated Response: Python is a programming language used for many purposes, including web development, automation, and data analysis.Expected Response: Python is a programming language.Relevance Score: 0.93Coherence Score: 0.92———

Leave a Reply

Your email address will not be published. Required fields are marked *