Prompt Engineering
Técnicas esenciales para trabajar
con modelos de lenguaje de IA
UNGS - Matemática para Economistas III
Lic. Mateo Suster
Agenda
What is NLP?
Definition of NLP
Machine Learning - Supervised learning
What is a model?
Relationship between NLP and Artificial intelligence
NLP use cases
Machine translation
Google Translate is an example of widely available NLP technology about machine translation. Effective translation has to capture accurately the meaning and tone of the input language and translate it to text with the same meaning and desired impact in the output language.
Sentiment analysis
Sentiment analysis can analyze language used in social media posts, responses, reviews, and more to extract attitudes and emotions in response to products, promotions, and events.
Information companies can use it in product designs, advertising campaigns, and more.
Text generation
Text generation leverages knowledge in computational linguistics and artificial intelligence to automatically generate natural language texts, which can satisfy certain communicative requirements.
Other tasks…
How the models works?
AI chat
What is an NLP model?
Model
Output:
[The quick brown fox jumps over the lazy dog]
8 | 57 | 17 | 1 | 2 | 12 | 5 | 6 | 4 |
6 | 8 | 7 | 58 | 19 | 81 | 75 | 13 | 63 |
3 | 2 | 4 | 8 | 9 | 12 | 51 | 7 | 81 |
Random?
Tokenization
Word embeddings (I)
Word embeddings and contextualization
Contextualization
Generation (I)
Generation (II)
Prompt Engineering
¿Qué es el Prompt Engineering?
La ingeniería de prompts es una nueva disciplina para desarrollar y optimizar prompts para usar de manera eficiente los modelos de lenguaje (LM) en una amplia variedad de aplicaciones.
Las habilidades de ingeniería de prompts ayudan a comprender mejor las capacidades y limitaciones de los grandes modelos de lenguaje (LLM) y, por lo tanto, a lograr mejores resultados en nuestros objetivos.
El objetivo final es crear entradas (prompts) que guíen a los modelos de lenguaje hacia respuestas específicas y de alta calidad de los modelos de lenguaje, ayudando a mejorar la precisión, relevancia y creatividad de las respuestas del modelo.
Ejemplo de prompt
How we learn prompt engineering
Write an initial prompt, then improve it step by step while learning new techniques.
Instruction prompting
Role assignment
Roles
Cuando usás LLMs, los prompts generalmente se componen de los siguientes elementos:
Estrategias para un prompt efectivo
Be clear and direct
The first line of your prompt is the most important part of your entire request…
Escribe instrucciones claras
Be specific
Two Types of Guidelines
When to Use Each Approach
Combining Both Approaches
In professional prompting, you'll often see both techniques used together.
Use Process Steps For Complex Problems
Add step-by-step instructions when you're dealing with:
Always Use Output Guidelines
You should include quality guidelines in almost every prompt you write. They're your safety net for getting consistent, useful results.
Structure with XML tags
Use XML tags to separate distinct portions of the prompt. XML tags are most useful when:
Even for shorter content, XML tags can help serve as delimiters that make your prompt structure more obvious to the model.
Providing structure
Custom Tag Names
You don't need to use official XML tags. Create descriptive names that make sense for your content:
The more specific and descriptive your tag names, the better the model can understand the purpose of each section.
Divide tareas complejas en subtareas más simples
Dale tiempo al modelo para "pensar"
Usa herramientas o fuentes externas
Providing examples
The challenge here is sarcasm. A tweet like "Yeah, sure, that was the best movie I've seen since 'Plan 9 from Outer Space'" appears positive on the surface, but it's actually sarcastic and negative (Plan 9 is famously one of the worst movies ever made).
Adding Examples to Handle Corner Cases
Few Shot-Based Prompting
What is Zero-Shot Prompting?
One-Shot Prompting
Few-Shot Prompting
Chain-of-Thought (CoT) Prompting
Técnica que mejora las capacidades de razonamiento de los grandes modelos de lenguaje (LLM). Lo logra al incorporar pasos lógicos —o una "cadena de pensamiento"— dentro de la indicación misma.
Prueba los cambios sistemáticamente
Síntesis de un buen prompt
Un buen "prompt" para un usuario contiene los siguientes elementos:
Errores Comunes en la Ingeniería de Prompts
Prompt Engineering es un proceso iterativo.
Casi nunca se acierta el prompt a la primera…..
Playground
Playground y configuraciones extras
Para personalizar completamente las capacidades de un LLM, no siempre es necesario desarrollar un script para acceder a todas las funcionalidades de la API. Algunos chatbots, como ChatGPT o Google AI Studio, ofrecen un entorno de pruebas (o "playground") que permite a los usuarios configurar diversas características directamente.
Temperatura, Top-P y Longitud Máxima
Temperatura (Temperature): La temperatura regula la imprevisibilidad de la salida de un modelo de lenguaje. Valores más bajos (por ejemplo, T = 0) producen respuestas enfocadas y predecibles; mientras que valores más altos fomentan la aleatoriedad y la creatividad. Toma valores en el rango [0,1].�
Top-P: Limita la salida a los tokens más probables dentro de una probabilidad acumulativa (por ejemplo, 0.9). Valores más bajos producen resultados más enfocados, mientras que valores más altos permiten una mayor diversidad. Puede combinarse con la temperatura para un control más preciso sobre la aleatoriedad y la creatividad. Toma valores en el rango [0,1].�
Longitud Máxima (Max Length): La longitud máxima es el número total de tokens que el LLM tiene permitido generar. Toma valores distintos según el modelo.
Recursos
Appendix
Pasos en Prompt Engineering
Parts of the prompt
The Prompt
Roles
Model
User
Use markers
XML tags
Character sequences
Message types
System
User
Bot / Assistant
Add context
Facts
History
General Knowledge
Add instructions
What not to do
What to do
How to do
Examples
The Query
❶
❷
❸
❹
❺
GPT Example Prompt
ChatGPT Cheat Sheet