Thursday, December 12, 2024

How to Summon AI Magic with Python: A Fun Guide to Generative AI APIs

Hey there, tech explorers! Ever wanted to whip up some magical AI-generated text, like having robot Shakespeares at your fingertips? Well, today’s your lucky day! We’re here to break down a piece of Python code that lets you chat with a fancy AI model and generate text like pros. No PhDs required, we promise.

First Things First: The Toolbox

Before we can talk to the AI, we need to grab some tools. Think of it like prepping for a camping trip—you need a tent (the model) and some snacks (the tokenizer).

        
pip install transformers
        
    

This command installs the Transformers library, which is like the Swiss Army knife of AI text generation. It’s brought to you by Hugging Face (no, not the emoji—it’s a company!).

Step 1: Unlock the AI Vault

We’ll need to log in to Hugging Face to get access to their cool models. Think of it as showing your library card before borrowing books.

        
from huggingface_hub import login
login("YOUR HUGGING FACE LOGIN")
        
    

Replace "YOUR HUGGING FACE LOGIN" with your actual login token. It’s how we tell Hugging Face, "Hey, it’s us—let us in!"

Step 2: Meet the Model

Now we load the AI brain. In our case, we’re using Meta’s Llama 3.2, which sounds like a cool llama astronaut but is actually an advanced AI model.

        
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

model_name = "meta-llama/Llama-3.2-1B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")
        
    

- Tokenizer: This breaks down your input text into AI-readable gibberish. - Model: The big brain that generates the text.

Step 3: Give It Something to Work With

Now comes the fun part: asking the AI a question or giving it a task.

        
input_text = "Explain the concept of artificial intelligence in simple terms."
inputs = tokenizer(input_text, return_tensors="pt")
        
    

- input_text: This is your prompt—what you’re asking the AI to do. - tokenizer: It converts your input into numbers the model can understand.

Step 4: Let the Magic Happen

Here’s where the AI flexes its muscles and generates text based on your prompt.

        
outputs = model.generate(
    inputs["input_ids"].to("cuda"), 
    max_length=100, 
    num_return_sequences=1, 
    temperature=0.7, 
    top_p=0.9, 
)
        
    

- inputs["input_ids"].to("cuda"): Sends the work to your GPU if you’ve got one. - max_length: How long you want the AI’s response to be. - temperature: Controls creativity. - top_p: Controls how "risky" the word choices are.

Step 5: Ta-Da! Your Answer

Finally, we take the AI’s response and turn it back into human language.

        
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(generated_text)
        
    

skip_special_tokens=True tells the AI, "Please don’t include random weird symbols in your answer."

So, What’s Happening Under the Hood?

Here’s a quick analogy for how this works:

  • We give the AI a prompt (our input text).
  • The tokenizer translates our words into numbers.
  • The model (our AI brain) uses these numbers to predict the best possible next words.
  • It spits out a response, which the tokenizer translates back into words.

It’s like ordering a coffee at Starbucks: we place the order, the barista makes it, and voilà—our coffee is ready!

Why Should We Care?

Generative AI APIs like this are the backbone of chatbots, creative writing tools, and even marketing copy generators. Whether we’re developers, writers, or just curious, playing with this code is a great way to dip our toes into the AI ocean.

Ready to Try It?

Copy the code, tweak the prompt, and see what kind of magic we can summon. Who knows? We might create the next big AI-powered masterpiece—or at least have some fun along the way.

Now go forth and generate! 🎉

Wednesday, November 27, 2024

Using Generative AI to Create Sustainable Business Plans: A Mini-Course at the University of Sonora

Last week, we had the incredible opportunity to deliver a mini-course at the University of Sonora on how to use generative AI to craft sustainable business plans. The session was designed to empower students and budding entrepreneurs to integrate cutting-edge AI tools, such as ChatGPT, into their business planning processes. This event showcased the practical applications of AI for innovation and sustainability, offering hands-on experience and collaborative learning.

The Course in Action

The course focused on teaching participants how generative AI can assist in every stage of business planning, including:

  • Brainstorming Ideas: Using AI to refine concepts, identify potential gaps, and generate creative alternatives.
  • Market Research: Employing AI for customer analysis, trend identification, and competitive landscape evaluation.
  • Feasibility Assessments: Exploring cost structures, revenue models, and risk mitigation strategies.
  • Customer Feedback Simulation: Generating insights by simulating customer reactions and improving marketing strategies.
  • SWOT Analysis: Leveraging AI to identify internal strengths and weaknesses and external opportunities and threats.

Participants were encouraged to experiment with AI tools to practice crafting mission statements, vision statements, and value propositions tailored to their sustainable business goals.

Collaborators Making a Difference

The course was a collaborative effort between three instructors, each bringing unique expertise to the table:

  • Dr. Saiph Savage
    A computer scientist and expert in human-centered AI, Saiph provided a technical and strategic perspective on how AI can be applied to the future of work and sustainable business practices.
  • Dr. Rafael Morales
    Originally from Mexico City and a PhD in Political Science from UNAM, Rafael brought a nuanced understanding of how to align AI-driven business strategies with government policies. He highlighted opportunities for collaboration between businesses and governments to promote social good.
  • Jesse Nava
    With extensive experience launching ventures for marginalized communities, including startups supporting low-income Hispanics and formerly incarcerated individuals in the U.S., Jesse shared real-world insights into how AI can help create inclusive, impactful business models.

Why Generative AI?

Generative AI, like ChatGPT, offers a unique advantage for entrepreneurs by providing accessible tools to:

  • Refine business ideas and strategies.
  • Perform rapid iterations to improve outcomes.
  • Enhance collaboration and creativity.
  • Develop sustainable and socially conscious plans.

The session emphasized the importance of human-centered design to ensure that AI tools remain inclusive, adaptable, and aligned with ethical practices.

Gratitude and Looking Ahead

We want to thank the University of Sonora and Dr. Alma Brenda Leyva Carreras for the invitation to deliver this course. It was an honor to collaborate with a multidisciplinary group of students and share knowledge at the intersection of AI, business, and sustainability.

As we move forward, we aim to continue these efforts, fostering a deeper understanding of how AI can empower diverse communities and create a brighter, more sustainable future for all.

Thursday, November 07, 2024

Keynote Speaker at the Mexican AI Conference (MICAI)

Caption: My father, me, and Mexican Professor Beto Ochoa-Ruiz (chair of the Mexican AI Conference) at MICAI in Puebla.

It was an incredible honor to be the keynote speaker at the Mexican AI Conference, a prestigious event with over 40 years of history organized by the Mexican Society for Artificial intelligence. I had the privilege of being a keynote speaker and presenting my research on designing worker-centric AI tools, and it was truly inspiring to see such a vibrant and thriving AI community in Mexico.

Conference Highlights

The conference itself was filled with fascinating talks and discussions. I especially enjoyed the presentation by Professor XX from the University of Toronto, who is pioneering AI systems to quantify and understand smell—an area of AI that I had not previously considered but found fascinating.

I also appreciated reconnecting with Professor Ricardo Baeza Yates, a distinguished researcher at Northeastern University. His work in establishing impactful AI labs in both industry and academia has been transformative, particularly in Latin America. His efforts with Yahoo Research have opened new pathways for research and innovation in the region, creating opportunities for countless researchers.

INAOE: A Unique Setting

The conference took place at the National Institute of Astrophysics, Optics, and Electronics (INAOE), a premier research institution in Mexico. Situated in a serene wooded area, INAOE is home to some stunning telescopes, blending cutting-edge technology with natural beauty. This unique setting added a special touch to the conference, enhancing the overall experience.

Caption: An overview of the speakers, participants, and organizers of the conference.

Special Moments with My Father

One of the most memorable aspects of this experience was attending the conference with my father, who has dedicated much of his career to AI and robotics. We drove together from Mexico City to Puebla, where the conference was held, and this journey gave us the unique opportunity to spend rich quality time together. Our conversations ranged from AI to personal reflections, making this trip a deeply meaningful experience for both of us.

Exploring the City of Puebla

Puebla is an impressive city, renowned for its rich history and architectural beauty. During our visit, I was particularly captivated by its churches, which showcase the Churrigueresque style. This ornate style is a fusion of local Indigenous art and Spanish Baroque, characterized by its elaborate decorations and intricate details. It stands as a testament to the cultural confluence that shaped Puebla’s identity.

Final Reflections

Overall, it was a privilege to be part of such a dynamic and supportive AI research community. The Mexican AI Conference not only provided a platform to share my research but also allowed me to engage with brilliant minds and immerse myself in the rich cultural and scientific landscape of Puebla.

Sunday, November 03, 2024

Co-Organizing a Workshop at AAAI HCOMP on Designing AI Tools for the Future of Work

We recently had the honor of co-organizing a workshop at the AAAI Human Computation and Crowdsourcing Conference (HCOMP) in Pittsburgh. This workshop focused on designing AI tools for the future of work and brought together diverse perspectives and innovative ideas.

Keynote Speaker: Sara Kingsley

Caption: Sara Kingsley giving her keynote at our workshop where she explained about her research on designing human centered AI for the future of work. She is especially focused on using red-teaming techniques to conduct online audits around AI in the work place, identify biases around current AI tools, and then designing AI driven interventions to address the challenges.

One of the highlights of our workshop was having Sara Kingsley as our keynote speaker. Sara is a researcher at Carnegie Mellon University and has extensive experience working at Meta and within the US Federal government, specifically in the Secretary of Labor.

In her engaging talk, Sara shared her work using red teaming—a process where experts challenge and test systems to find vulnerabilities or weaknesses—to identify problematic job ads and content related to job advertising. She explained how she applies red teaming to ensure that job ads do not propagate harmful biases or misleading information. This approach allows her to design human-centered AI tools that can create better, more equitable AI-driven futures for workers.

This type of research is critical as it helps to identify and mitigate potential biases and harms in AI systems before they impact real users. We were especially proud to note that Sara recently won the best paper award at HCOMP’24 on this very topic. Congratulations to Sara on this well-deserved recognition! We are proud to have had her as a keynote speaker in our workshop.

Co-Design Activity with Community Partners

Caption: Our research collaborator Jesse Nava in his workforce development programs for former/current prisoners.

Another unique aspect of our workshop was the co-design activity we held with workshop participants and current and former prisoners from California’s Department of Corrections and Rehabilitation. Our community partner, Jesse Nava, joined us via call, making this session truly impactful.

During this co-design activity, participants proposed ideas for generative AI tools that could support the reintegration of former prisoners into the workforce. Jesse provided invaluable feedback on these proposals, sharing his perspective on potential harms, biases, and areas where these tools could be improved to better serve the formally incarcerated population.

This was a unique experience as it allowed us to receive direct feedback from real-world stakeholders who would be directly affected by these AI tools. The opportunity to co-design with such engaged partners highlighted the importance of including diverse voices and lived experiences in the development process.

Closing Thoughts

We concluded the workshop with a sense of excitement and renewed commitment to continue designing the future of generative AI tools together. This collaborative approach is key to creating technologies that are inclusive, fair, and genuinely supportive of the communities they aim to serve.

Thank you to everyone who participated and contributed to making this workshop a success. We look forward to future opportunities to innovate, collaborate, and create impactful AI solutions.

Sunday, August 25, 2024

Driving the Future of Work in Mexico through Artificial Intelligence: My Experience with the Global Partnership on AI (GPAI)

As an expert selected by the Mexican federal government to be part of the Global Partnership on AI (GPAI), I have had the honor of contributing to the working group on "AI for the Future of Work." My participation in this group has been an enriching and transformative experience, especially in the context of how artificial intelligence (AI) can and should positively impact the labor market in Mexico.

During my time with GPAI, I led several key initiatives that emphasize the importance of integrating AI into the workplace. One of the most notable was securing €20,000 to fund internships focused on creating AI for workers, specifically for Mexican students. These internships not only provide development opportunities for our youth but also foster the creation of technology that can improve working conditions in our country.

In these internships, we taught students the importance of developing human-centered artificial intelligence, an approach that prioritizes the well-being and needs of people in the design and implementation of technologies. Students learned to apply these principles while working on concrete projects, such as developing intelligent assistants for the Ministry of Foreign Affairs. These assistants were specifically designed to facilitate passport processing, improving the efficiency and accessibility of these services for Mexican citizens.

Additionally, in collaboration with INFOTEC, several UNAM students were hired as interns to implement artificial intelligence solutions in various government areas. This experience was crucial for students to apply their knowledge in a real-world setting and contribute directly to the modernization of the public sector. Collaborations between government and academia, like this one, are essential for integrating cutting-edge technologies and ensuring that Mexico remains at the forefront of AI use to improve public services.

Another significant contribution was leading the development of a new AI aimed at supporting both workers and the government. This project, developed by talented UNAM students, not only demonstrates the capabilities of our youth but also positions Mexico as a leader in the creation of labor-inclusive technology.

My work with GPAI has also allowed me to lead global studies on the impact of AI in the workplace, publishing scientific articles that have contributed to the international discussion on this crucial topic. Additionally, I have had the privilege of advising senators from the United States and Mexico on how AI can transform work, ensuring that informed decisions are made to benefit workers.

Recommendations for the Mexican Federal Government

Throughout this experience, I have developed some recommendations that I consider essential for Mexico to stay at the forefront of AI integration in the workplace:

  1. Creation of International Training Programs: It is essential that Mexico invests in training our citizens in the latest trends and AI technologies at a global level. This will not only improve our internal capabilities but also strengthen our position on the international stage.
  2. Internships in AI + GovTech: Propose the creation of internship programs that combine AI with GovTech, training future leaders at the intersection of technology and governance. This will allow for a more efficient and modern public administration.
  3. Strengthening the Support Network for Mexicans Abroad: The Ministry of Foreign Affairs should promote scientific and AI connections between Mexican and international universities. These collaborations will not only facilitate the exchange of knowledge but also help our nationals abroad access strong support networks and advanced technological resources.
  4. Promotion of Government-Academia Collaborations: It is crucial to strengthen collaborations between the government and academia to create a robust ecosystem that drives the development of new artificial intelligence technologies in Mexico. These alliances will allow young talent to integrate into projects that modernize and improve public administration, ensuring that technological innovations benefit society as a whole.

My participation in GPAI has not only been an honor but also an opportunity to positively influence the future of work in Mexico. Through these recommendations, I trust that our country can continue moving towards a future where AI is a tool for growth and the well-being of all Mexicans.

Impulsando el Futuro del Trabajo en México a través de la Inteligencia Artificial: Mi Experiencia en el Global Partnership on AI (GPAI)

Como experta seleccionada por el gobierno federal mexicano para formar parte del Global Partnership on AI (GPAI), he tenido el honor de contribuir al grupo de trabajo en "AI for the Future of Work". Mi participación en este grupo ha sido una experiencia enriquecedora y trascendental, especialmente en el contexto de cómo la inteligencia artificial (IA) puede y debe impactar positivamente el mercado laboral en México.

Durante mi tiempo en GPAI, he liderado varias iniciativas clave que subrayan la importancia de integrar la IA en el ámbito laboral. Una de las más destacadas fue la obtención de €20,000 para financiar prácticas profesionales enfocadas en la creación de IA para obreros, dirigidas a estudiantes mexicanos. Estas prácticas no solo brindan oportunidades de desarrollo a nuestros jóvenes, sino que también fomentan la creación de tecnología que puede mejorar las condiciones laborales en nuestro país.

En estas prácticas, enseñamos a los estudiantes sobre la importancia de desarrollar inteligencia artificial centrada en los humanos, un enfoque que prioriza el bienestar y las necesidades de las personas en el diseño y la implementación de tecnologías. Los estudiantes aprendieron a aplicar estos principios mientras trabajaban en proyectos concretos, como el desarrollo de asistentes inteligentes para la Secretaría de Relaciones Exteriores. Estos asistentes fueron diseñados específicamente para facilitar los trámites de pasaporte, mejorando la eficiencia y accesibilidad de estos servicios para los ciudadanos mexicanos.

Además, en colaboración con INFOTEC, se logró que varios estudiantes de la UNAM fueran contratados como internos para implementar soluciones de inteligencia artificial en diversas áreas del gobierno. Esta experiencia fue fundamental para que los estudiantes aplicaran sus conocimientos en un entorno real y contribuyeran directamente a la modernización del sector público. Las colaboraciones entre el gobierno y la academia, como esta, son esenciales para integrar tecnologías novedosas y asegurar que México esté a la vanguardia en el uso de IA para mejorar los servicios públicos.

Otra de las contribuciones significativas fue liderar el desarrollo de una nueva IA destinada a apoyar tanto a los obreros como al gobierno. Este proyecto, desarrollado por estudiantes talentosos de la UNAM, no solo demuestra la capacidad de nuestra juventud, sino que también posiciona a México como un líder en la creación de tecnología laboralmente inclusiva.

Mi trabajo en GPAI también me ha permitido liderar estudios globales sobre el impacto de la IA en el ámbito laboral, publicando artículos científicos que han contribuido a la discusión internacional sobre este tema crucial. Además, he tenido el privilegio de asesorar a senadores de Estados Unidos y México sobre cómo la IA puede transformar el trabajo, asegurando que se tomen decisiones informadas que beneficien a los trabajadores.

Recomendaciones para el Gobierno Federal de México

A lo largo de esta experiencia, he desarrollado algunas recomendaciones que considero esenciales para que México se mantenga a la vanguardia en la integración de la IA en el trabajo:

  1. Creación de Programas de Capacitación Internacional: Es fundamental que México invierta en la formación de nuestros ciudadanos en las últimas tendencias y tecnologías de IA a nivel global. Esto no solo mejorará nuestras capacidades internas, sino que también fortalecerá nuestra posición en el escenario internacional.
  2. Internships en IA + GovTech: Proponer la creación de programas de prácticas profesionales que combinen la IA con el GovTech, capacitando a los futuros líderes en la intersección entre tecnología y gobernanza. Esto permitirá una administración pública más eficiente y adaptada a los tiempos modernos.
  3. Fortalecimiento de la Red de Apoyo a Mexicanos en el Exterior: La Secretaría de Relaciones Exteriores debe impulsar la conexión científica y en IA entre universidades mexicanas e internacionales. Estas colaboraciones no solo facilitarán el intercambio de conocimientos, sino que también ayudarán a nuestros connacionales en el exterior a acceder a redes de apoyo sólidas y recursos tecnológicos avanzados.
  4. Fomento de Colaboraciones Academia-Gobierno: Es crucial fortalecer las colaboraciones entre el gobierno y la academia para crear un ecosistema robusto que impulse el desarrollo de nuevas tecnologías de inteligencia artificial en México. Estas alianzas permitirán que el talento joven se integre en proyectos que modernicen y mejoren la administración pública, garantizando que las innovaciones tecnológicas beneficien a la sociedad en su conjunto.

Mi participación en GPAI no solo ha sido un honor, sino también una oportunidad para influir positivamente en el futuro del trabajo en México. A través de estas recomendaciones, confío en que nuestro país puede seguir avanzando hacia un futuro en el que la IA sea una herramienta para el crecimiento y el bienestar de todos los mexicanos.

Monday, July 29, 2024

My Journey with the OECD's Global Partnership on AI: Shaping the Future of AI Together

I'm thrilled to share my experience as an expert with the Global Partnership on AI (GPAI), an initiative launched by the Organization for Economic Cooperation and Development (OECD). This journey has been both inspiring and impactful, as I work alongside brilliant minds from around the world to tackle some of the biggest challenges and opportunities AI presents.

Why GPAI Was Created

The GPAI was set up to address the rapid advancements in AI, ensuring these technologies are developed ethically and inclusively. It aims to:

  • Promote responsible AI: Ensuring AI is used for good.
  • Enhance international cooperation: Sharing knowledge and best practices globally.
  • Support sustainable development: Using AI to solve global issues like health and education.
  • Encourage innovation: Driving advancements while managing risks.

How GPAI Works

GPAI brings together experts from various countries, chosen by their governments, to collaborate on key areas like:

  • Responsible AI
  • Data Governance
  • The Future of Work
  • Innovation and Commercialization

My Role and Contributions

I’m honored to have been named a GPAI expert by Mexico’s federal government. I’m part of the working group focusing on AI for the future of work. We’re exploring how AI impacts jobs and creating strategies to ensure it benefits workers rather than displaces them.

Mini Internships for Latin America

One of the most rewarding projects I've been involved in is setting up mini internships for students in Latin America, including Mexico and Costa Rica. These internships teach students about human-centered design for the future of work. We’re partnering with Universidad Nacional Autónoma de México (UNAM), Universidad de Colima, and Universidad de Costa Rica.

Students are interviewing workers to understand how they use AI at work. Based on what we learn, we’re developing new AI tools to support them better.

Innovation Workshop in Paris

As part of my GPAI role, I was invited to an innovation workshop in Paris. It was an incredible experience to meet and brainstorm with leading AI experts. The insights and ideas exchanged were invaluable, and I’m excited to bring this knowledge back to our projects in Latin America. In my next blog post, I will provide more details about the Paris innovation workshop and the exciting developments that emerged from it.