All posts by Rizel Scarlett

How to use GitHub Copilot: Prompts, tips, and use cases

Post Syndicated from Rizel Scarlett original https://github.blog/2023-06-20-how-to-write-better-prompts-for-github-copilot/

Leia este artigo em português

As ferramentas de programação de IA generativa estão transformando a maneira como as pessoas desenvolvedoras abordam as tarefas diárias de programação. Desde a documentação de nossas bases de código até a geração de testes de unidade, essas ferramentas estão ajudando a acelerar nossos fluxos de trabalho. No entanto, assim como acontece com qualquer tecnologia emergente, sempre há uma curva de aprendizado. Como resultado, as pessoas desenvolvedoras — tanto iniciantes quanto experientes — às vezes se sentem frustradas quando os assistentes de programação baseados em IA não geram o resultado desejado. (Familiar com isso?)

Por exemplo, ao pedir ao GitHub Copilot para desenhar uma casquinha de sorvete 🍦usando p5.js, uma biblioteca JavaScript para código criativo, continuamos recebendo sugestões irrelevantes ou, às vezes, nenhuma sugestão. Mas quando aprendemos mais sobre a maneira como o GitHub Copilot processa as informações, percebemos que precisávamos ajustar a maneira como nos comunicamos com elas.

Aqui está um exemplo do GitHub Copilot gerando uma solução irrelevante:

When we wrote this prompt to GitHub Copilot,

Quando ajustamos nosso prompt, conseguimos gerar resultados mais precisos:

When we wrote this prompt to GitHub Copilot,

Somos desenvolvedoras e entusiastas de IA. Eu, Rizel, usei o GitHub Copilot para criar uma extensão de navegador; jogo de pedra, papel e tesoura; e para enviar um Tweet. E eu, Michele, abri uma empresa de AI em 2021. Somos ambas Developer Advocates no GitHub e adoramos compartilhar nossas principais dicas para trabalhar com o GitHub Copilot.

Neste guia do GitHub Copilot, abordaremos:

  • O que exatamente é um prompt e o que é engenharia de prompt também (dica: depende se você está falando com uma pessoa desenvolvedora ou pesquisadora de machine learning)
  • Três práticas recomendadas e três dicas adicionais para criação imediata com o GitHub Copilot
  • Um exemplo em que você pode tentar solicitar ao GitHub Copilot para ajudá-lo a criar uma extensão de navegador

Progresso antes de perfeição

Mesmo com nossa experiência no uso de IA, reconhecemos que todes estão em uma fase de tentativa e erro com a tecnologia de IA generativa. Também conhecemos o desafio de fornecer dicas generalizadas de criação de prompts porque os modelos variam, assim como os problemas individuais nos quais as pessoas desenvolvedoras estão trabalhando. Este não é um guia definitivo. Em vez disso, estamos compartilhando o que aprendemos sobre criação de prompts para acelerar o aprendizado coletivo durante esta nova era de desenvolvimento de software.

O que é um prompt e o que é engenharia de prompt?

Depende de com quem você fala.

No contexto das ferramentas de programação de IA generativa, um prompt pode significar coisas diferentes, dependendo se você está perguntando a pessoas pesquisadoras de Machine Learning (ML) que estão construindo e ajustando essas ferramentas ou pessoas desenvolvedoras que as estão usando em seus IDEs.

Para este guia, definiremos os termos do ponto de vista de uma pessoa desenvolvedora que está usando uma ferramenta de programação AI generativa no IDE. Mas, para dar a você uma visão completa, também adicionamos as definições do pesquisador de ML abaixo em nosso gráfico.

Prompts Engenharia de Prompt Contexto
Pessoa Desenvolvedora Blocos de código, linhas individuais de código ou comentários em linguagem natural que uma pessoa desenvolvedora escreve para gerar uma sugestão específica do GitHub Copilot. Fornecer instruções ou comentários no IDE/strong> para gerar sugestões de código específicas. DDetalhes que são fornecidos por uma pessoa desenvolvedora para especificar a saída desejada de uma ferramenta de programação AI generativa.
Pessoa Pesquisadora de ML Compilação de código de IDE
e contexto
relevante (comentários IDE, código em arquivos abertos, etc.) que são continuamente gerados por algoritmos e enviados para o modelo de uma ferramenta de programação AI generativa
Criação de algoritmos que irão gerar prompts (compilações de código IDE e contexto) para um grande modelo de linguagem Detalhes (como dados de seus arquivos abertos e código que você escreveu antes e depois do cursor) que os algoritmos enviam para um modelo de linguagem grande (LLM) como informações adicionais sobre o código

3 melhores práticas para construção de prompt com GitHub Copilot

1. Defina o cenário com um objetivo de alto nível 🖼

Isso é mais útil se você tiver um arquivo em branco ou uma base de código vazia. Em outras palavras, se o GitHub Copilot não tiver contexto do que você deseja criar ou realizar, definir o cenário para a programação em par AI pode ser realmente útil. Isso ajuda a preparar o GitHub Copilot com uma descrição geral do que você deseja gerar – antes de entrar nos detalhes.

Ao solicitar o GitHub Copilot, pense no processo como uma conversa com alguém: como devo detalhar o problema para que possamos resolvê-lo juntes? Como eu abordaria a programação em par com essa pessoa?

Por exemplo, ao construir um editor de markdown em Next.jst, poderíamos escrever um comentário como este:


/*
Crie um editor de markdown básico em Next.jcom as seguintes habilidades:
- Use react hooks
- Crie um estado para markdown com texto default "digite markdown aqui"
- Uma área de texto onde pessoas usuárias podem escrever markdown a
- Mostre uma demostração ao vivo do markdown enquando a pessoas digitaS
- Suporte para sintaxe básica de markdown como cabeçalhos, negrito, itálico
- Use React markdown npm package 
- O texto markdown e resultado em HTML devem ser salvos no estado do componente e atualizado em tempo real 
*/

Isso solicitará que o GitHub Copilot gere o código a seguir e produza um editor de markdown muito simples, sem estilo, mas funcional, em menos de 30 segundos. Podemos usar o tempo restante para estilizar o componente:

We used this prompt to build a markdown editor in Next.jst using GitHub Copilot:
- Use react hooks
- Create state for markdown with default text

Observação: esse nível de detalhe ajuda a criar um resultado mais desejado, mas os resultados ainda podem ser não determinísticos. Por exemplo, no comentário, solicitamos ao GitHub Copilot que criasse um texto padrão que diz “digite markdown aqui”, mas, em vez disso, gerou “visualização de markdown” como as palavras padrão.

2. Faça sua pergunta simples e específica. Procure receber uma saída curta do GitHub Copilot.🗨

Depois de comunicar seu objetivo principal ao Copilot, articule a lógica e as etapas que ele precisa seguir para atingir esse objetivo. O GitHub Copilot entende melhor seu objetivo quando você detalha as coisas. (Imagine que você está escrevendo uma receita. Você dividiria o processo de cozimento em etapas discretas – não escreveria um parágrafo descrevendo o prato que deseja fazer.)

Deixe o GitHub Copilot gerar o código após cada etapa, em vez de pedir que ele gere vários códigos de uma só vez.

Aqui está um exemplo de nós fornecendo ao GitHub Copilot instruções passo a passo para reverter uma função:

We prompted GitHub Copilot to reverse a sentence by writing six prompts one at a time. This allowed GitHub Copilot to generate a suggestion for one prompt before moving onto the text. It also gave us the chance to tweak the suggested code before moving onto the next step. The six prompts we used were: First, let's make the first letter of the sentence lower case if it's not an 'I.' Next, let's split the sentence into an array of words. Then, let's take out the punctuation marks from the sentence. Now, let's remove the punctuation marks from the sentence. Let's reverse the sentence and join it back together. Finally, let's make the first letter of the sentence capital and add the punctuation marks.

3. De alguns exemplos para o GitHub Copilot. ✍

Aprender com exemplos não é útil apenas para humanos, mas também para seu programador Copilot. Por exemplo, queríamos extrair os nomes do array de dados abaixo e armazená-los em um novo array:


const data = [
  [
    { name: 'John', age: 25 },
    { name: 'Jane', age: 30 }
  ],
  [
    { name: 'Bob', age: 40 }
  ]
];

Quando você não mostra um exemplo para o GitHub Copilot …


// Map por um array de arrays de objetos para transformar dados
const data = [
  [
    { name: 'John', age: 25 },
    { name: 'Jane', age: 30 }
  ],
  [
    { name: 'Bob', age: 40 }
  ]
];

Isso gerou um uso incorreto do map:


const mappedData = data.map(x => [x.name](http://x.name/));

console.log(mappedData);

// Results: [undefined, undefined]

Em contraste, quando mostramos um exemplo …


// Map por um array de arrays de objetos
// Exemplo: Extraia nomes  array data
// Resultado desejado: ['John', 'Jane', 'Bob']
const data = [
  [{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }],
  [{ name: 'Bob', age: 40 }]
];

Recebemos o resultado desejado.


const mappedData = data.flatMap(sublist => sublist.map(person => person.name));

console.log(mappedData);
// Results: ['John', 'Jane', 'Bob']

Leia mais sobre abordagens comuns para treinamento de IA, como aprendizado de disparo zero, disparo único e poucos disparos.

Três dicas adicionais para criação imediata com o GitHub Copilot

Aqui estão três dicas adicionais para ajudar a orientar sua conversa com o GitHub Copilot.

1. Experimente com seus prompts.

Assim como a conversa é mais uma arte do que uma ciência, o mesmo acontece com a criação imediata. Portanto, se você não receber o que deseja na primeira tentativa, reformule seu prompt seguindo as práticas recomendadas acima.

Por exemplo, o prompt abaixo é vago. Ele não fornece nenhum contexto ou limites para o GitHub Copilot gerar sugestões relevantes.


# Escreva algum código para grades.py

Repetimos o prompt para sermos mais específicos, mas ainda não obtivemos o resultado exato que procurávamos. Este é um bom lembrete de que adicionar especificidade ao seu prompt é mais difícil do que parece. É difícil saber, desde o início, quais detalhes você deve incluir sobre seu objetivo para gerar as sugestões mais úteis do GitHub Copilot. É por isso que encorajamos a experimentação.
A versão do prompt abaixo é mais específica que a anterior, mas não define claramente os requisitos de entrada e saída.


# Implemente uma função em grades.py para calcular a nota média

Experimentamos o prompt mais uma vez definindo limites e delineando o que queríamos que a função fizesse. Também reformulamos o comentário para que a função fosse mais clara (dando ao GitHub Copilot uma intenção clara de verificação).

Desta vez, obtivemos os resultados que procurávamos.


# Implemente a função calculate_average_grade em grades.py que recebe uma lista de notas como entrada e retorna a nota média como um número de ponto flutuante

2. Mantenha algumas abas abertas.

Não temos um número exato de abas que você deve manter abertas para ajudar o GitHub Copilot a contextualizar seu código, mas, com base em nossa experiência, descobrimos que uma ou duas são úteis.

O GitHub Copilot usa uma técnica chamada de abas vizinhas que permite que a ferramenta programadora em par AI contextualize seu código processando todos os arquivos abertos em seu IDE em vez de apenas um único arquivo em que você está trabalhando. No entanto, não é garantido que o GitHub Copilot considere todos os arquivos abertos como contexto necessário para o seu código.

3. Use boas práticas de programação.

Isso inclui fornecer nomes e funções de variáveis ​​descritivas e seguir estilos e padrões de codificação consistentes. Descobrimos que trabalhar com o GitHub Copilot nos encoraja a seguir boas práticas de programação que aprendemos ao longo de nossas carreiras.

Por exemplo, aqui usamos um nome de função descritivo e seguimos os padrões da base de código para alavancar casos de cobra.


def authenticate_user(username, password):

Como resultado, GitHub Copilot gera uma sugestão de código relevante:


def authenticate_user(username, password):
    # Code for authenticating the user
    if is_valid_user(username, password):
        generate_session_token(username)
        return True
    else:
        return False

Compare isso com o exemplo abaixo, onde introduzimos um estilo de programação inconsistente e nomeamos mal nossa função.


def rndpwd(l):

Em vez de sugerir código, o GitHub Copilot gerou um comentário que dizia: “O código vai aqui”.


def rndpwd(l):
    # Code goes here

Fique esperto

Os LLMs por trás das ferramentas de programação de IA generativas são projetados para encontrar e extrapolar padrões de seus dados de treinamento, aplicar esses padrões à linguagem existente e, em seguida, produzir código que siga esses padrões. Dada a escala desses modelos, eles podem gerar uma sequência de código que ainda nem existe. Assim como você revisaria o código de um colega, você deve sempre avaliar, analisar e validar o código gerado por IA.

Um exemplo de prática 👩🏽‍💻

Tente solicitar ao GitHub Copilot para criar uma extensão de navegador.

Para começar, você precisará ter o GitHub Copilot instalado e aberto em seu IDE. Também temos acesso a uma prévia do bate-papo do GitHub Copilot, que é o que usamos quando tiver dúvidas sobre o nosso código. Se você não tem bate-papo no GitHub Copilot, inscreva-se na lista de espera. Até então, você pode emparelhar o GitHub Copilot com o ChatGPT.

Guias de criação de IA mais generativos (em inglês)

<0l>

  • Um guia para iniciantes sobre engenharia de prompt com o GitHub Copilot
  • Engenharia de alerta para IA
  • Como o GitHub Copilot está melhorando a compreensão do seu código

  • Lee este articulo en español

    Las herramientas de codificación con IA generativa están transformando la forma en que los desarrolladores abordan las tareas de codificación diarias. Desde documentar nuestras bases de código hasta generar pruebas unitarias, estas herramientas están ayudando a acelerar nuestros flujos de trabajo. Sin embargo, como con cualquier tecnología emergente, siempre hay una curva de aprendizaje. Como resultado, los desarrolladores, tanto principiantes como experimentados, a veces se sienten frustrados cuando los asistentes de codificación impulsados por IA no generan el resultado que quieren. (¿Te suena familiar?)

    Por ejemplo, al pedirle a GitHub Copilot que dibuje un cono de helado 🍦 usando p5.js, una biblioteca de JavaScript para codificación creativa, seguimos recibiendo sugerencias irrelevantes, o a veces ninguna sugerencia en absoluto. Pero cuando aprendimos más sobre la forma en que GitHub Copilot procesa la información, nos dimos cuenta de que teníamos que ajustar la forma en que nos comunicábamos.

    Aquí hay un ejemplo de GitHub Copilot generando una solución irrelevante:

    When we wrote this prompt to GitHub Copilot,

    Cuando ajustamos nuestra instrucción, pudimos generar resultados más precisos:

    When we wrote this prompt to GitHub Copilot,

    Somos tanto desarrolladoras como entusiastas de la IA. Yo, Rizel, he utilizado GitHub Copilot para construir una extensión de navegador; un juego de piedra, papel o tijera; y para enviar un tweet. Y yo, Michelle, lancé una compañía de IA en 2016. Ambas somos DevRel en GitHub y nos encanta compartir nuestros mejores consejos para trabajar con GitHub Copilot.

    En esta guía para GitHub Copilot, cubriremos:

    • Qué es exactamente un “prompt” y qué es la ingeniería de prompts (pista: depende de si estás hablando con un desarrollador o con un investigador de aprendizaje automático)
    • Tres mejores prácticas y tres consejos adicionales para la creación de prompts con GitHub Copilot
    • Un ejemplo donde puedes probar a GitHub Copilot para que te ayude en la construcción de una extensión de navegador

    Progreso sobre perfección

    Incluso con nuestra experiencia usando IA, reconocemos que todos están en una fase de prueba y error con la tecnología de IA generativa. También conocemos el desafío de proporcionar consejos generales de elaboración de prompts porque los modelos varían, al igual que los problemas individuales en los que los desarrolladores están trabajando. Esta no es una guía definitiva. En su lugar, estamos compartiendo lo que hemos aprendido sobre la elaboración de prompts para acelerar el aprendizaje colectivo durante esta nueva era del desarrollo de software.

    ¿Qué es un “prompt” y qué es la ingeniería de prompt?

    Depende de con quién hables.

    En el contexto de las herramientas de codificación de IA generativa, un prompt puede significar diferentes cosas, dependiendo de si está preguntando a los investigadores de aprendizaje automático (ML) que están construyendo y ajustando estas herramientas, o a los desarrolladores que las están usando en sus IDE.

    Para esta guía, definiremos los términos desde el punto de vista de un desarrollador que utiliza una herramienta de codificación de IA generativa en el IDE. Pero para brindarle una imagen completa, también agregamos las definiciones de investigador de ML a continuación.

    Prompts Ingenieria de Prompt Contexto
    Desarrollador Bloques de código, líneas individuales de código, o comentarios en lenguaje natural que un desarrollador escribe para generar una sugerencia específica de GitHub Copilot. Proporcionar instrucciones o comentarios en el IDE para generar sugerencias de código específicas Detalles que proporciona un desarrollador para especificar la prompt deseada de una herramienta de codificación generativa de IA
    Investigador de ML Compilación de código de IDE y contexto relevante (comentarios de IDE, código en archivos abiertos, etc.) que se genera continuamente por algoritmos y se envíaal modelo de una herramienta de codificación generativa de IA Creación de algoritmos que generarán prompts (compilaciones de código de IDE y contexto) para un modelo de lenguaje de gran tamaño Detalles (como datos de tus archivos abiertos y código que has escrito antes y después del curso) que los algoritmos envían a un modelo de lenguaje de gran tamaño (LLM) como información adicional sobre el código

    3 mejores prácticas para la elaboración de prompts con GitHub Copilot

    1. Establecer el escenario con un objetivo de alto nivel. 🖼

    Esto es más útil si tienes un archivo en blanco o una base de código vacía. En otras palabras, si GitHub Copilot no tiene ningún contexto de lo que quieres construir o lograr, establecer el escenario para el programador par de IA puede ser realmente útil. Ayuda a preparar a GitHub Copilot con una descripción general de lo que quieres que genere, antes de que te sumerjas en los detalles.

    Al hacer prompts, GitHub Copilot, piensa en el proceso como si estuvieras teniendo una conversación con alguien: ¿Cómo debería desglosar el problema para que podamos resolverlo juntos? ¿Cómo abordaría la programación en pareja con esta persona?

    Por ejemplo, al construir un editor de markdown en Next.js, podríamos escribir un comentario como este:

    
    //
    Crea un editor de markdown básico en Next.js con las siguientes características:
    - Utiliza hooks de React
    - Crea un estado para markdown con texto predeterminado "escribe markdown aquí"
    - Un área de texto donde los usuarios pueden escribir markdown
    - Muestra una vista previa en vivo del texto de markdown mientras escribo
    - Soporte para la sintaxis básica de markdown como encabezados, negrita, cursiva
    - Utiliza el paquete npm de React markdown
    - El texto de markdown y el HTML resultante deben guardarse en el estado del componente y actualizarse en tiempo real 
    */
    

    Esto hará que GitHub Copilot genere el siguiente código y produzca un muy editor de rebajas simple, sin estilo pero funcional en menos de 30 segundos. Podemos usar el tiempo restante para diseñar el componente:

    We used this prompt to build a markdown editor in Next.jst using GitHub Copilot:
- Use react hooks
- Create state for markdown with default text

    Nota: Este nivel de detalle te ayuda a crear una prompt más deseada, pero los resultados aún pueden ser no deterministas. Por ejemplo, en el comentario, solicitamos a GitHub Copilot que cree un texto predeterminado que diga “escribe markdown aquí”, pero en cambio generó “vista previa de markdown” como las palabras predeterminadas.

    2. Haz tu solicitud simple y específica. Apunta a recibir una prompt corta de GitHub Copilot. 🗨

    Una vez que comunicas tu objetivo principal al programador par AI, articula la lógica y los pasos que debe seguir para alcanzar ese objetivo. GitHub Copilot comprende mejor tu objetivo cuando desglosas las cosas. (Imagina que estás escribiendo una receta. Desglosarías el proceso de cocción en pasos discretos, no escribirías un párrafo describiendo el plato que quieres hacer.)
    Deja que GitHub Copilot genere el código después de cada paso, en lugar de pedirle que genere un montón de código de una sola vez.
    Aquí tienes un ejemplo de cómo proporcionamos a GitHub Copilot instrucciones paso a paso para invertir una función:

    We prompted GitHub Copilot to reverse a sentence by writing six prompts one at a time. This allowed GitHub Copilot to generate a suggestion for one prompt before moving onto the text. It also gave us the chance to tweak the suggested code before moving onto the next step. The six prompts we used were: First, let's make the first letter of the sentence lower case if it's not an 'I.' Next, let's split the sentence into an array of words. Then, let's take out the punctuation marks from the sentence. Now, let's remove the punctuation marks from the sentence. Let's reverse the sentence and join it back together. Finally, let's make the first letter of the sentence capital and add the punctuation marks.

    3. Proporciona a GitHub Copilot uno o dos ejemplos. ✍

    Aprender de ejemplos no solo es útil para los humanos, sino también para tu programador par AI. Por ejemplo, queríamos extraer los nombres del siguiente arreglo de datos y almacenarlos en un nuevo arreglo:

    
    const data = [
      [
        { name: 'John', age: 25 },
        { name: 'Jane', age: 30 }
      ],
      [
        { name: 'Bob', age: 40 }
      ]
    ];
    

    Cuando no le mostramos un ejemplo a GitHub Copilot …

    
    // Mapee a través de una matriz de matrices de objetos para transformar datos
    const data = [
      [
        { name: 'John', age: 25 },
        { name: 'Jane', age: 30 }
      ],
      [
        { name: 'Bob', age: 40 }
      ]
    ];
    

    Generó un uso incorrecto del mapa:

    
    const mappedData = data.map(x => [x.name](http://x.name/));
    
    console.log(mappedData);
    
    // Results: [undefined, undefined]
    

    Por el contrario, cuando proporcionamos un ejemplo…

    
    // Recorrer un array de arrays de objetos
    // Ejemplo: Extraer los nombres del array de datos
    // Resultado deseado: ['John', 'Jane', 'Bob']
    const data = [
      [{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }],
      [{ name: 'Bob', age: 40 }]
    ];
    

    Recibimos nuestro resultado deseado.

    
    const mappedData = data.flatMap(sublist => sublist.map(person => person.name));
    
    console.log(mappedData);
    // Results: ['John', 'Jane', 'Bob'] 
    

    Lee más acerca de los enfoques comunes para el entrenamiento de IA, como el aprendizaje de zero-shot, one-shot, and few-shot learning.

    Tres consejos adicionales para la elaboración de prompts con GitHub Copilot

    Aquí tienes tres consejos adicionales para ayudarte a guiar tu conversación con GitHub Copilot.

    1. Experimenta con tus prompts.

    Al igual que la conversación es más un arte que una ciencia, también lo es la elaboración de prompts. Así que, si no recibes lo que quieres en el primer intento, reformula tu prompts siguiendo las mejores prácticas mencionadas anteriormente.

    Por ejemplo, la prompts de abajo es vaga. No proporciona ningún contexto ni límites para que GitHub Copilot genere sugerencias relevantes.

    
    # Escribe algo de código para grades.py
    

    Iteramos en el prompt para ser más específicos, pero aún no obtuvimos el resultado exacto que estábamos buscando. Este es un buen recordatorio de que añadir especificidad a tu prompt es más difícil de lo que parece. Es difícil saber, desde el principio, qué detalles debes incluir sobre tu objetivo para generar las sugerencias más útiles de GitHub Copilot. Por eso animamos a la experimentación.

    La versión del promopt de abajo es más específica que la de arriba, pero no define claramente los requisitos de entrada y salida.

    
    # Implementar una función en grades.py para calcular la nota media
    

    Experimentamos una vez más con el promopt estableciendo límites y delineando lo que queríamos que hiciera la función. También reformulamos el comentario para que la función fuera más clara (dándole a GitHub Copilot una intención clara contra la que verificar).

    Esta vez, obtuvimos los resultados que estábamos buscando.

    
    # Implementa la función calculate_average_grade en grades.py que toma una lista de calificaciones como entrada y devuelve la calificación media como un número flotante.
    

    2. Mantén un par de pestañas relevantes abiertas.

    No tenemos un número exacto de pestañas que debas mantener abiertas para ayudar a GitHub Copilot a contextualizar tu código, pero en nuestra experiencia, hemos encontrado que una o dos es útil.

    GitHub Copilot utiliza una técnica llamada pestañas vecinas que permite al programador de pares de IA contextualizar su código procesando todos los archivos abiertos en su IDE en lugar de solo el archivo en el que está trabajando. Sin embargo, no se garantiza que GItHub Copilot considere todos los archivos abiertos como contexto necesario para su código.

    3. Utilice buenas prácticas de codificación.

    Eso incluye proporcionar nombres y funciones de variables descriptivas, y seguir estilos y patrones de codificación consistentes. Hemos descubierto que trabajar con GitHub Copilot nos anima a seguir las buenas prácticas de codificación que hemos aprendido a lo largo de nuestras carreras.

    Por ejemplo, aquí usamos un nombre de función descriptiva y seguimos los patrones de la base de código para aprovechar el caso de la serpiente.

    
    def authenticate_user(nombre de usuario, contraseña):
    

    Como resultado, GitHub Copilot generó una sugerencia de código relevante:

    
    def authenticate_user(nombre de usuario, contraseña):
        # Código para autenticar al usuario
        Si is_valid_user(nombre de usuario, contraseña):
            generate_session_token(nombre de usuario)
            return True
        más:
            return Falso
    

    Compare esto con el siguiente ejemplo, donde introdujimos un estilo de codificación inconsistente y mal nombramos nuestra función.

    
    def rndpwd(l):
    

    En lugar de sugerir código, GitHub Copilot generó un comentario que decía: “El código va aquí”.

    
    def rndpwd(l):
        # El código va aquí
    

    Mantente inteligente

    Los LLM detrás de las herramientas generativas de codificación de IA están diseñados para encontrar y extrapolar patrones de sus datos de entrenamiento, aplicar esos patrones al lenguaje existente y luego producir código que siga esos patrones. Dada la gran escala de estos modelos, podrían generar una secuencia de código que ni siquiera existe todavía. Al igual que revisaría el código de un colega, siempre debe evaluar, analizar y validar el código generado por IA.

    Un ejemplo 👩🏽 💻 de práctica

    Intenta pedirle a GitHub Copilot que cree una extensión del navegador.

    Para comenzar, deberás tener GitHub Copilot instalado y abierto en tu IDE. También tenemos acceso a una vista previa temprana del chat de GitHub Copilot, que es lo que hemos estado usando cuando tenemos preguntas sobre nuestro código. Si no tienes el chat de GitHub Copilot, regístrate en la lista de espera. Hasta entonces, puede emparejar GitHub Copilot con ChatGPT.

    Guías de elaboración de avisos de IA más generativas

  • Una guía para principiantes sobre ingeniería rápida con GitHub Copilot
  • Ingeniería rápida para IA
  • Cómo GitHub Copilot está mejorando en la comprensión de tu código


  • Generative AI coding tools are transforming the way developers approach daily coding tasks. From documenting our codebases to generating unit tests, these tools are helping to accelerate our workflows. However, just like with any emerging tech, there’s always a learning curve. As a result, developers—beginners and experienced alike— sometimes feel frustrated when AI-powered coding assistants don’t generate the output they want. (Feel familiar?)

    For example, when asking GitHub Copilot to draw an ice cream cone 🍦using p5.js, a JavaScript library for creative coding, we kept receiving irrelevant suggestions—or sometimes no suggestions at all. But when we learned more about the way that GitHub Copilot processes information, we realized that we had to adjust the way we communicated with it.

    Here’s an example of GitHub Copilot generating an irrelevant solution:

    When we wrote this prompt to GitHub Copilot,

    When we adjusted our prompt, we were able to generate more accurate results:

    When we wrote this prompt to GitHub Copilot,

    We’re both developers and AI enthusiasts ourselves. I, Rizel, have used GitHub Copilot to build a browser extension, rock, paper, scissors game, and to send a Tweet. And I, Michelle, launched an AI company in 2016. We’re both developer advocates at GitHub and love to share our top tips for working with GitHub Copilot.

    In this guide for GitHub Copilot, we’ll cover:

    Progress over perfection

    Even with our experience using AI, we recognize that everyone is in a trial and error phase with generative AI technology. We also know the challenge of providing generalized prompt-crafting tips because models vary, as do the individual problems that developers are working on. This isn’t an end-all, be-all guide. Instead, we’re sharing what we’ve learned about prompt crafting to accelerate collective learning during this new age of software development.

    What’s a prompt and what is prompt engineering?

    It depends on who you talk to.

    In the context of generative AI coding tools, a prompt can mean different things, depending on whether you’re asking machine learning (ML) researchers who are building and fine-tuning these tools, or developers who are using them in their IDEs.

    For this guide, we’ll define the terms from the point of view of a developer who’s using a generative AI coding tool in the IDE. But to give you the full picture, we also added the ML researcher definitions below in our chart.

    Prompts Prompt engineering Context
    Developer Code blocks, individual lines of code, or natural language comments a developer writes to generate a specific suggestion from GitHub Copilot Providing instructions or comments in the IDE to generate specific coding suggestions Details that are provided by a developer to specify the desired output from a generative AI coding tool
    ML researcher Compilation of IDE code and relevant context (IDE comments, code in open files, etc.) that is continuously generated by algorithms and sent to the model of a generative AI coding tool Creating algorithms that will generate prompts (compilations of IDE code and context) for a large language model Details (like data from your open files and code you’ve written before and after the cursor) that algorithms send to a large language model (LLM) as additional information about the code

    3 best practices for prompt crafting with GitHub Copilot

    1. Set the stage with a high-level goal. 🖼

    This is most helpful if you have a blank file or empty codebase. In other words, if GitHub Copilot has zero context of what you want to build or accomplish, setting the stage for the AI pair programmer can be really useful. It helps to prime GitHub Copilot with a big picture description of what you want it to generate—before you jump in with the details.

    When prompting GitHub Copilot, think of the process as having a conversation with someone: How should I break down the problem so we can solve it together? How would I approach pair programming with this person?

    For example, when building a markdown editor in Next.jst, we could write a comment like this

    /*
    Create a basic markdown editor in Next.js with the following features:
    - Use react hooks
    - Create state for markdown with default text "type markdown here"
    - A text area where users can write markdown 
    - Show a live preview of the markdown text as I type
    - Support for basic markdown syntax like headers, bold, italics 
    - Use React markdown npm package 
    - The markdown text and resulting HTML should be saved in the component's state and updated in real time 
    */
    

    This will prompt GitHub Copilot to generate the following code and produce a very simple, unstyled but functional markdown editor in less than 30 seconds. We can use the remaining time to style the component:

    We used this prompt to build a markdown editor in Next.jst using GitHub Copilot:
- Use react hooks
- Create state for markdown with default text

    Note: this level of detail helps you to create a more desired output, but the results may still be non-deterministic. For example, in the comment, we prompted GitHub Copilot to create default text that says “type markdown here” but instead it generated “markdown preview” as the default words.

    2. Make your ask simple and specific. Aim to receive a short output from GitHub Copilot. 🗨

    Once you communicate your main goal to the AI pair programmer, articulate the logic and steps it needs to follow for achieving that goal. GitHub Copilot better understands your goal when you break things down. (Imagine you’re writing a recipe. You’d break the cooking process down into discrete steps–not write a paragraph describing the dish you want to make.)

    Let GitHub Copilot generate the code after each step, rather than asking it to generate a bunch of code all at once.

    Here’s an example of us providing GitHub Copilot with step-by-step instructions for reversing a function:

    We prompted GitHub Copilot to reverse a sentence by writing six prompts one at a time. This allowed GitHub Copilot to generate a suggestion for one prompt before moving onto the text. It also gave us the chance to tweak the suggested code before moving onto the next step. The six prompts we used were: First, let's make the first letter of the sentence lower case if it's not an 'I.' Next, let's split the sentence into an array of words. Then, let's take out the punctuation marks from the sentence. Now, let's remove the punctuation marks from the sentence. Let's reverse the sentence and join it back together. Finally, let's make the first letter of the sentence capital and add the punctuation marks.

    3. Give GitHub Copilot an example or two. ✍

    Learning from examples is not only useful for humans, but also for your AI pair programmer. For instance, we wanted to extract the names from the array of data below and store it in a new array:

    const data = [
      [
        { name: 'John', age: 25 },
        { name: 'Jane', age: 30 }
      ],
      [
        { name: 'Bob', age: 40 }
      ]
    ];
    

    When we didn’t show GitHub Copilot an example …

    // Map through an array of arrays of objects to transform data
    const data = [
      [
        { name: 'John', age: 25 },
        { name: 'Jane', age: 30 }
      ],
      [
        { name: 'Bob', age: 40 }
      ]
    ];
    
    const mappedData = data.map(x => [x.name](http://x.name/));
    
    console.log(mappedData);
    
    // Results: [undefined, undefined]
    

    It generated an incorrect usage of map:

    const mappedData = data.map(x => [x.name](http://x.name/));
    
    console.log(mappedData);
    
    // Results: [undefined, undefined]
    

    By contrast, when we did provide an example …

    // Map through an array of arrays of objects
    // Example: Extract names from the data array
    // Desired outcome: ['John', 'Jane', 'Bob']
    const data = [
      [{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }],
      [{ name: 'Bob', age: 40 }]
    ];
    
    
    const mappedData = data.flatMap(sublist => sublist.map(person => person.name));
    
    console.log(mappedData);
    

    We received our desired outcome.

    const mappedData = data.flatMap(sublist => sublist.map(person => person.name));
    
    console.log(mappedData);
    // Results: ['John', 'Jane', 'Bob']
    

    Read more about common approaches to AI training, such as zero-shot, one-shot, and few-shot learning.

    Three additional tips for prompt crafting with GitHub Copilot

    Here are three additional tips to help guide your conversation with GitHub Copilot.

    1. Experiment with your prompts.

    Just how conversation is more of an art than a science, so is prompt crafting. So, if you don’t receive what you want on the first try, recraft your prompt by following the best practices above.

    For example, the prompt below is vague. It doesn’t provide any context or boundaries for GitHub Copilot to generate relevant suggestions.

    # Write some code for grades.py  
    

    We iterated on the prompt to be more specific, but we still didn’t get the exact result we were looking for. This is a good reminder that adding specificity to your prompt is harder than it sounds. It’s difficult to know, from the start, which details you should include about your goal to generate the most useful suggestions from GitHub Copilot. That’s why we encourage experimentation.

    The version of the prompt below is more specific than the one above, but it doesn’t clearly define the input and output requirements.

    # Implement a function in grades.py to calculate the average grade
    

    We experimented with the prompt once more by setting boundaries and outlining what we wanted the function to do. We also rephrased the comment so the function was more clear (giving GitHub Copilot a clear intention to verify against).

    This time, we got the results we were looking for.

    # Implement the function calculate_average_grade in grades.py that takes a list of grades as input and returns the average grade as a floating-point number
    

    2. Keep a couple of relevant tabs open.

    We don’t have an exact number of tabs that you should keep open to help GitHub Copilot contextualize your code, but from our experience, we’ve found that one or two is helpful.

    GitHub Copilot uses a technique called neighboring tabs that allows the AI pair programmer to contextualize your code by processing all of the files open in your IDE instead of just the single file you’re working on. However, it’s not guaranteed that GItHub Copilot will deem all open files as necessary context for your code.

    3. Use good coding practices.

    That includes providing descriptive variable names and functions, and following consistent coding styles and patterns. We’ve found that working with GitHub Copilot encourages us to follow good coding practices we’ve learned throughout our careers.

    For example, here we used a descriptive function name and followed the codebase’s patterns of leveraging snake case.

    def authenticate_user(username, password):
    

    As a result, GitHub Copilot generated a relevant code suggestion:

    def authenticate_user(username, password):
        # Code for authenticating the user
        if is_valid_user(username, password):
            generate_session_token(username)
            return True
        else:
            return False
    

    Compare this to the example below, where we introduced an inconsistent coding style and poorly named our function.

    def rndpwd(l):
    

    Instead of suggesting code, GitHub Copilot generated a comment that said, “Code goes here.”

    def rndpwd(l):
        # Code goes here
    

    Stay smart

    The LLMs behind generative AI coding tools are designed to find and extrapolate patterns from their training data, apply those patterns to existing language, and then produce code that follows those patterns. Given the sheer scale of these models, they might generate a code sequence that doesn’t even exist yet. Just as you would review a colleague’s code, you should always assess, analyze, and validate AI-generated code.

    A practice example 👩🏽‍💻

    Try your hand at prompting GitHub Copilot to build a browser extension.

    To get started, you’ll need to have GitHub Copilot installed and open in your IDE. We also have access to an early preview of GitHub Copilot chat, which is what we’ve been using when we have questions about our code. If you don’t have GitHub Copilot chat, sign up for the waitlist. Until then you can pair GitHub Copilot with ChatGPT.

    More generative AI prompt crafting guides

    How I used GitHub Copilot to build a browser extension

    Post Syndicated from Rizel Scarlett original https://github.blog/2023-05-12-how-i-used-github-copilot-to-build-a-browser-extension/

    For the first time ever, I built a browser extension and did it with the help of GitHub Copilot. Here’s how.

    I’ve built a rock, paper, scissors game with GitHub Copilot but never a browser extension. As a developer advocate at GitHub, I decided to put GitHub Copilot to the test, including its upcoming chat feature, and see if it could help me write an extension for Google Chrome to clear my cache.

    I’m going to be honest: it wasn’t as straightforward as I expected it to be. I had a lot of questions throughout the build and had to learn new information.

    But at the end of the day, I gained experience with learning an entirely new skill with a generative AI coding tool and pair programming with GitHub Copilot—and with other developers on Twitch 👥.

    I wanted to create steps that anyone—even those without developer experience—could easily replicate when building this extension, or any other extension. But I also wanted to share my new takeaways after a night of pair programming with GitHub Copilot and human developers.

    So, below you’ll find two sections:

    Let’s jump in.

    How to build a Chrome extension with GitHub Copilot

    To get started, you’ll need to have GitHub Copilot installed and open in your IDE. I also have access to an early preview of GitHub Copilot chat, which is what I used when I had a question. If you don’t have GitHub Copilot chat, sign up for the waitlist, and pair GitHub Copilot with ChatGPT for now.

    1. 🧑🏾‍💻 Using the chat window, I asked GitHub Copilot, “How do I create a Chrome extension? What should the file structure look like?”

    💻 GitHub Copilot gave me general steps for creating an extension—from designing the folder structure to running the project locally in Chrome.

    Screenshot of the char window where the user asked GitHub Copilot "How do I build a browser extension? What should the file structure look like?" GitHub Copilot provided some instructions in response."

    Then, it shared an example of a Chrome extension file structure.

    Copilot response showing an example structure for a simple Chrome extension.

    To save you some time, here’s a chart that briefly defines the purpose of these files:

    manifest.json 🧾 Metadata about your extension, like the name and version, and permissions. Manifest as a proper noun is the name of the Google Chrome API. The latest is V3.
    popup.js 🖼 When users click on your extension icon in their Chrome toolbar, a pop-up window will appear. This file is what determines the behavior of that pop-up and contains code for handling user interactions with the pop-up window.
    popup.html and style.css 🎨 These files make up the visual of your pop-up window. popup.html is the interface, including layout, structure, and content. style.css determines the way the HTML file should be displayed in the browser, including font, text color, background, etc.

    2. Create the manifest.json 🧾

    🧑🏾‍💻 Inside a folder in my IDE, I created a file called manifest.json. In manifest.json,

    I described my desired file:

    Manifest for Chrome extension that clears browser cache.
    manifest_version: 3
    Permissions for the extension are: storage, tabs, browsingData
    

    I pressed enter and invoked suggestions from GitHub Copilot by typing a curly brace.

    💻 Inside the curly brace, GitHub Copilot suggested the manifest. I deleted the lines describing my desired manifest.json, and the final file looked like this:

    {
       "name": "Clear Cache",
       "version": "1.0",
       "manifest_version": 3,
       "description": "Clears browser cache",
       "permissions": [
           "storage",
           "tabs",
           "browsingData"
       ],
       "action": {
           "default_popup": "popup.html"
       },
       "background": {
           "service_worker": "background.js"
       }
    }
    

    3. Create a service worker, which is a file called background.js 🔧

    This wasn’t a file that was recommended from my chat with GitHub Copilot. I learned that it was a necessary file from a developer who tuned into my livestream 👥. The background.js is what gives your extension the ability to run in the background, perform tasks, and respond to user events outside of the extension’s pop-up window (like network requests and data storage).

    🧑🏾‍💻 In my background.js file, I wrote a comment describing my desired service worker:

    Service Worker for Google Chrome Extension 
    Handles when extension is installed
    Handles when message is received
    

    Then, I wrote a comment for the first function, which prompted a suggestion from GitHub Copilot, and then wrote another comment to describe the second function.

    💻 The final file looked like this:

    /*
    Service Worker for Google Chrome Extension
    Handles when extension is installed
    Handles when message is received
    */
    
    // console.log when extension is installed
    chrome.runtime.onInstalled.addListener(function() {
       console.log("Extension installed");
    });
    
    // send response when message is received and console.log when message is received
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
       console.log("Message received");
       sendResponse("Message received");
    });
    

    4. Create the popup.html file 🖼

    🧑🏾‍💻 In the popup.html file, I wrote a comment describing how I wanted my pop-up window to appear. This window is the one users will see when they click on the extension icon.

    <!--
       HTML for Chrome extension that clears browser cache.
       Connect to javascript file called popup.js and CSS file called style.css
       Will render the following buttons with id's:
       - "All History"
       - "Past Month"
       - "Past Week"
       - "Past Day"
       - "Past Hour"
       - "Past Minute"
    
    
       Will render an empty paragraph with id "lastCleared"
    -->
    

    💻 GitHub Copilot suggested the following:

    <!DOCTYPE html>
    <html>
       <head>
           <meta charset="utf-8">
           <title>Clear Cache</title>
           <link rel="stylesheet" href="style.css">
       </head>
       <body>
           <h1>Clear Cache</h1>
           <button id="allHistory">All History</button>
           <button id="pastMonth">Past Month</button>
           <button id="pastWeek">Past Week</button>
           <button id="pastDay">Past Day</button>
           <button id="pastHour">Past Hour</button>
           <button id="pastMinute">Past Minute</button>
           <p id="lastCleared"></p>
           <script src="popup.js"></script>
       </body>
    </html>
    

    5. Test the browser extension

    I decided to test the modifications before incorporating additional styles or interactivity. I prefer making incremental changes and conducting manual tests in between because it simplifies the debugging process.

    🧑🏾‍💻 Navigate to chrome://extensions/ in your Chrome browser. Turn on developer mode. Press “Load unpacked.” Upload the folder that holds your Chrome extension. Once loaded, you should be able to test your extension. Here’s what mine looked like:

    Screenshot of the Chrome extension offering options to "Clear Cache."

    6. Create a popup.js file to add interactivity

    🧑🏾‍💻 Inside this file, write a comment that will act as pseudocode for you but as a prompt for GitHub Copilot.

    Pseudocode isn’t code, but a method of conceptualizing and communicating ideas to plan and design programs before writing the actual code. Programmers can concentrate on algorithmic logic without worrying about syntactic details of a particular programming language—and communicate ideas to other developers regardless of coding experience.

    Here’s the pseudocode I used:

    /*
    This program is a Chrome Extension that clears browser cache.
    Handle on button click:
    - button with id "allHistory" that clears all cache history
    - button with id "pastMonth" that clears cache history from the past month
    - button with id "pastWeek" that clears cache history from the past week
    - button with id "pastDay" that clears cache history from the past day
    - button with id "pastHour" that clears cache history from the past hour
    - button with id "pastMinute" that clears cache history from the past minute
    
    
    Create function that
    - converts dates and times into human-readable format
    - adds "Successfully cleared cache" with date and time in a paragraph with id "lastCleared"
    */
    

    Then, write the series of comments below, but write them one at a time to allow GitHub Copilot to generate a code suggestion after each one. The final popup.js looked like this:

    /*
    This program is a Chrome Extension that clears browser cache.
    Handle on button click:
    - button with id "allHistory" that clears all cache history
    - button with id "pastMonth" that clears cache history from the past month
    - button with id "pastWeek" that clears cache history from the past week
    - button with id "pastDay" that clears cache history from the past day
    - button with id "pastHour" that clears cache history from the past hour
    - button with id "pastMinute" that clears cache history from the past minute
    
    Create function that
    - converts dates and times into human-readable format
    - adds "Successfully cleared cache" with date and time in a paragraph with id "lastCleared"
    */
    
    // convert date and time into human-readable format
    function convertDate(date) {
       let date = new Date(date);
       var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
       return date.toLocaleDateString("en-US", options);
    }
    
    // add successfully cleared cache into paragraph with id "lastCleared"
    function addCleared() {
       var p = document.getElementById("lastCleared");
       let date = new Date();
       p.innerHTML = "Successfully cleared cache " + convertDate(date);
    }
    
    // clear all cache history
    document.getElementById("allHistory").addEventListener("click", function() {
       chrome.browsingData.removeCache({ "since": 0 }, function() {
           addCleared();
       });
    });
    
    // clear cache history from the past month
    document.getElementById("pastMonth").addEventListener("click", function() {
       let date = new Date();
       date.setMonth(date.getMonth() - 1);
       chrome.browsingData.removeCache({ "since": date.getTime() }, function() {
           addCleared();
       });
    });
    
    // clear cache history from the past week
    document.getElementById("pastWeek").addEventListener("click", function() {
       let date = new Date();
       date.setDate(date.getDate() - 7);
       chrome.browsingData.removeCache({ "since": date.getTime() }, function() {
           addCleared();
       });
    });
    
    // clear cache history from the past day
    document.getElementById("pastDay").addEventListener("click", function() {
       let date = new Date();
       date.setDate(date.getDate() - 1);
       chrome.browsingData.removeCache({ "since": date.getTime() }, function() {
           addCleared();
       });
    });
    
    // clear cache history from the past hour
    document.getElementById("pastHour").addEventListener("click", function() {
      let date = new Date();
       date.setHours(date.getHours() - 1);
       chrome.browsingData.removeCache({ "since": date.getTime() }, function() {
           addCleared();
       });
    });
    
    // clear cache history from the past minute
    document.getElementById("pastMinute").addEventListener("click", function() {
      let date = new Date();
       date.setMinutes(date.getMinutes() - 1);
       chrome.browsingData.removeCache({ "since": date.getTime() }, function() {
           addCleared();
       });
    });
    

    🧑🏾‍💻 GitHub Copilot actually generated the var keyword, which is outdated. So I changed that keyword to let.

    7. Create the last file in your folder: style.css

    🧑🏾‍💻 Write a comment that describes the style you want for your extension. Then, type “body” and continue tabbing until GitHub Copilot suggests all the styles.

    My final style.css looked like this:

    /* Style the Chrome extension's popup to be wider and taller
    Use accessible friendly colors and fonts
    Make h1 elements legible
    Highlight when buttons are hovered over
    Highlight when buttons are clicked
    Align buttons in a column and center them but space them out evenly
    Make paragraph bold and legible
    */
    
    body {
       background-color: #f1f1f1;
       font-family: Arial, Helvetica, sans-serif;
       font-size: 16px;
       color: #333;
       width: 400px;
       height: 400px;
    }
    
    h1 {
       font-size: 24px;
       color: #333;
       text-align: center;
    }
    
    button {
       background-color: #4CAF50;
       color: white;
       padding: 15px 32px;
       text-align: center;
       text-decoration: none;
       display: inline-block;
       font-size: 16px;
       margin: 4px 2px;
       cursor: pointer;
       border-radius: 8px;
    }
    
    button:hover {
       background-color: #45a049;
    }
    
    button:active {
       background-color: #3e8e41;
    }
    
    p {
       font-weight: bold;
       font-size: 18px;
       color: #333;
    }
    
    For detailed, step-by-step instructions, check out my Chrome extension with GitHub Copilot repo.

    Three important lessons about learning and pair programming in the age of AI

    1. Generative AI reduces the fear of making mistakes. It can be daunting to learn a new language or framework, or start a new project. The fear of not knowing where to start—or making a mistake that could take hours to debug—can be a significant barrier to getting started. I’ve been a developer for over three years, but streaming while coding makes me nervous. I sometimes focus more on people watching me code and forget the actual logic. When I conversed with GitHub Copilot, I gained reassurance that I was going in the right direction and that helped me to stay motivated and confident during the stream.

    2. Generative AI makes it easier to learn about new subjects, but it doesn’t replace the work of learning. GitHub Copilot didn’t magically write an entire Chrome extension for me. I had to experiment with different prompts, and ask questions to GitHub Copilot, ChatGPT, Google, and developers on my livestream. To put it in perspective, it took me about 1.5 hours to do steps 1 to 5 while streaming.

      But if I hadn’t used GitHub Copilot, I would’ve had to write all this code by scratch or look it up in piecemeal searches. With the AI-generated code suggestions, I was able to jump right into review and troubleshooting, so a lot of my time and energy was focused on understanding how the code worked. I still had to put in the effort to learn an entirely new skill, but I was analyzing and evaluating code more often than I was trying to learn and then remember it.

    3. Generative AI coding tools made it easier for me to collaborate with other developers. Developers who tuned into the livestream could understand my thought process because I had to tell GitHub Copilot what I wanted it to do. By clearly communicating my intentions with the AI pair programmer, I ended up communicating them more clearly with developers on my livestream, too. That made it easy for people tuning in to become my virtual pair programmers during my livestream.

    Overall, working with GitHub Copilot made my thought process and workflow more transparent. Like I said earlier, it was actually a developer on my livestream who recommended a service worker file after noticing that GitHub Copilot didn’t include it in its suggested file structure. Once I confirmed in a chat conversation with GitHub Copilot and a Google search that I needed a service worker, I used GitHub Copilot to help me write one.

    Take this with you

    GitHub Copilot made me more confident with learning something new and collaborating with other developers. As I said before, live coding can be nerve-wracking. (I even get nervous even when I’m just pair programming with a coworker!) But GitHub Copilot’s real-time code suggestions and corrections created a safety net, allowing me to code more confidently—and quickly— in front of a live audience. Also, because I had to clearly communicate my intentions with the AI pair programmer, I was also communicating clearly with the developers who tuned into my livestream. This made it easy to virtually collaborate with them.

    The real-time interaction with GitHub Copilot and the other developers helped with catching errors, learning coding suggestions, and reinforcing my own understanding and knowledge. The result was a high-quality codebase for a browser extension.

    This project is a testament to the collaborative power of human-AI interaction. The experience underscored how GitHub Copilot can be a powerful tool in boosting confidence, facilitating learning, and fostering collaboration among developers.


    More resources

    Why Python keeps growing, explained

    Post Syndicated from Rizel Scarlett original https://github.blog/2023-03-02-why-python-keeps-growing-explained/

    Which programming language has been around for more than three decades and continues to grow in popularity each year?

    If you guessed Python, you nailed it. In the 2022 Octoverse report, we found that Python remains the second most-used programming language on GitHub. Interestingly, Python’s use grew more than 22 percent year over year with more than four million developers on GitHub using it at some point in 2022.

    In this article, we’ll dive into a brief history of Python, its benefits, its use cases, and seek to answer why a program language conceived in the 1980s continues to dominate development. And, since this is GitHub, we’ll also offer a few useful tips and tricks for developers new to—and experienced in—Python.

    So, what is Python? 🤔

    Python is a high-level, interpreted programming language with a simple syntax, which makes it easily readable and extremely user- and beginner-friendly. Originally built to satisfy Guido Van Rossum’s desire for a programming language that was simple to use and beautiful to look at, Python was first released to the world in 1991.

    Fun fact: Python was named after the BBC TV show, “Monty Python’s Flying Circus.”

    Since its development, it has grown to have widespread applicability for developers, data scientists, researchers, and more. But how, you may ask, can a coding language be simple and beautiful to look at? Here’s some proof:

    Python

    print("Hello world.")
    

    vs.

    Java

    public class HelloWorld {
        public static void main (String[]args) {
          System.out.println.("Hello world");
        }
    }
    

    Since Python is a general-purpose language, it can be used in a variety of applications, and its uncomplicated nature makes it an excellent language for automating tasks, building websites or software, and analyzing data.

    Python also has several other characteristics that make it popular amongst developers and engineers. These include:

    • It’s easy to read. Python code uses English keywords rather than punctuation, and its line breaks help define the code blocks. In practice, this means you can identify what the code is designed to do simply by looking at it.

    • It’s open source. You can download the source code, modify it, and use it however you want.

    • It’s portable. Some languages require you to modify code to run on different platforms, but Python is a cross-platform language, which means you can run the same code on any operating system with a Python interpreter.

    • It’s extendable. Python code can be written in other languages (such as C++), and users can add low-level modules to the Python interpreter to customize and optimize their tools.

    • It has a broad standard library. This library is available for anyone to access and means that users don’t have to write code for every single function—they can access built-in modules that help with issues in everyday programming and more.

    What is Python commonly used for? 💻

    Python can be used for just about anything, from web and software development to machine learning and artificial intelligence (AI). Let’s take a look at some of its most common use cases.

    import antigravity
    
    def main():
        antigravity.fly()
    
    if __name__ == '__main__':
        main()
    

    Run this command to check out an inside joke among Python developers.

    Using Python for web and software development

    Python is a popular language for web and software development because you can create complex, multi-protocol applications while maintaining concise, readable syntax. In fact, some of the most popular applications were built with Python. Plus, Python’s open source community provides developers with an extensive amount of reusable code, frameworks, and support. Case in point: Django is one of the most-used Python frameworks designed by experienced developers to help others accelerate their application build times and avoid issues that might balk their progress.

    Using Python for task automation

    One of Python’s key benefits is its ability to automate manual, repetitive tasks. With Python, you can learn how to automate just about anything by using either built-in modules or pre-written code from its robust library. Or you can write your own custom scripts to perform specific actions. For example, you can easily automate emails with the “smtplib” module or copy files with the “shutil” module. Python also has a robust set of testing frameworks, which makes it an excellent language for test automation. Frameworks such as Pytest, Behave, and Robot allow developers to write simple yet effective tests to ensure the quality of their builds.

    Using Python for machine learning and data science

    Here’s a fun fact: Python is the top preferred language for data science and research. Since its syntax is easily understandable and adaptable, people with little-to-no development experience can easily learn Python and use it to manipulate data for research, reporting, predictable or regression analyses, and more. Collecting and parsing data can be a time-consuming task for data scientists. Python is also one of the top languages for training machine learning (ML) models. Through specific algorithms, these models can analyze and identify patterns in data to make predictions or decisions based on that data. They also constantly evolve based on outputs of previous datasets to confront new variables. Data scientists and developers training ML models often utilize libraries, such as NumPy, Pandas, and Matplotlib, to automate functions like cleaning, data transformation, and visualization.

    Using Python for financial analysis

    Similar to how Python can assist data scientists with the heavy lift of large data sets, Python is widely used in the financial industry to quickly perform complex computations. Stock markets generate huge amounts of data, and Python can be used to import data on stock prices and generate strategies through algorithms to identify trading opportunities. The language can also be used for portfolio optimization, risk management, financial modeling and visualization, cryptocurrency analysis, and even fraud detection.

    Using Python for and artificial intelligence

    Python can also be found in some of the most complex, artificial intelligence (AI) technologies—and it’s actually one of the preferred languages for AI. Python’s concise and readable code allows developers to create consistent, reliable systems, and its vast library provides a number of frameworks like PyBrain, which offers developers powerful algorithms for machine learning tasks. Plus, Python’s visualization capabilities can help convert these large datasets for AI or ML into comprehensible graphs or reports. Interestingly enough, OpenAI, the artificial intelligence research lab, utilizes the Python framework, Pytorch, as their standard framework for deep learning, which trains its AI systems.

    In addition to its relative simplicity to learn, there are a few other reasons why Python continues to consistently grow in popularity. These include:

    • It’s more productive. Compared to some other more complex programming languages like C++, Python’s syntax allows users to do more with less and cut down on time and effort to write the same lines of code.

    • It has an expansive, supportive community of users. Even the best developers run into problems— and this is where user communities can become an invaluable resource. Python has a huge community with documentation, tutorials, tips, and tricks to master the language. The Python community on GitHub, for example, offers everything from information on the latest version of the language to bug reports and update notes.

    • It’s academic. Python has become the go-to language in academia with some students even encountering Python as early as elementary school. (Believe it or not, there are children’s picture books dedicated to Python.) While computer science students are often taught Python, its use extends beyond that discipline into other areas of STEM and academic research. For example, Python can be used to solve differential equations, perform statistical analyses, simulate and track particle diffusion, and more.

    • It has high corporate demand. Because of its wide scale applicability in development and data analysis work, learning and knowing Python is often considered a top-skill among job seekers. According to Statista, Python was the third most demanded language in 2022 by recruiters worldwide.

    The bottom line

    Python is everywhere—and it’s been used to build a significant number of the technologies, websites, and even systems most people encounter on a daily basis. It powers everything from your favorite video streaming service to the ML algorithms that can help you make your next cryptocurrency trade. And for an even broader scope example (pun absolutely intended), NASA uses Python to power data analysis with its sophisticated James Webb Space Telescope, which makes it one of the few programming languages that is, quite literally, out of this world. 🚀

    How to get started with Python 📓

    A quick Google search will yield hundreds of resources out there to jumpstart your Python journey—and that can quickly get a little overwhelming. To simplify things, here are a few helpful GitHub repositories to help you get started with Python:

    To get started, download the latest version of Python.

    Start building on GitHub today

    GitHub offers two easier ways to start working with Python: GitHub Codespaces and GitHub Copilot.

    You can start building today for free with GitHub Codespaces, which every developer on GitHub gets 60 free hours of use time per month to spin up a development environment in the cloud from any device at speed. Check out the Django quick start template to begin coding right in your browser!

    You can also use GitHub Copilot, GitHub’s AI pair programmer, to write your first lines of Python. Here’s how:

    1. Install the GitHub Copilot extension into your code editor.
    2. Describe the purpose of your project in a comment.
    3. Write a comment describing which libraries you may need.
    4. Start tabbing and let GitHub Copilot suggest lines of code to help you learn new techniques or methods.

    From machine learning to data analysis, Python’s versatility allows it to continue its explosive growth with developers and non-developers alike. Experiment with Python through GitHub or on your local machine to be part of this growth and get started today!

    10 things you didn’t know you could do with GitHub Codespaces

    Post Syndicated from Rizel Scarlett original https://github.blog/2023-02-28-10-things-you-didnt-know-you-could-do-with-github-codespaces/

    Ever feel like you’re coding on a plane mid-flight? When I first learned to code about five years ago, my laptop was painstakingly slow, but I couldn’t afford a better one. That’s why I relied on browser-based IDEs like jsbin.com to run my code.

    Now fast forward to today, where GitHub Codespaces provides a fully-fledged, browser-based Integrated Development Environment (IDE) on a virtual machine. This means you can code without draining your local machine’s resources. Cloud-powered development is a game-changer for folks with less powerful machines, but that barely scratches the surface of GitHub Codespaces’ versatility.

    In this blog post, we’ll discuss a few ways that you can get the most out of GitHub Codespaces!

    Generate AI images 🎨

    You can run Stable Diffusion with GitHub Codespaces. Like DALL-E and Midjourney, Stable Diffusion is one of many machine-learning models using deep learning to convert text into art.

    Stable Diffusion takes the following steps to convert text into art:

    • AI receives an image
    • AI adds noise to the image until the image becomes completely unrecognizable. (Noise is another way of saying pixelated dots.)
    • AI removes the noise until it produces a clear, high-quality image
    • AI learns from a database called LAION-Aesthetics. The database has image-text pairs to learn to convert text into images.

    This entire process is resource-intensive! Experts recommend using a computer with a powerful graphics processing unit (GPU) to run data-heavy tasks like Stable Diffusion. However, not everyone has a computer with that type of computing power (including me), so instead, I use GitHub Codespaces.

    Since your codespace is hosted on a virtual machine, you can set the machine type from 2-core to 32-core. You can request access to a GPU-powered codespace if you need a more powerful machine. This means a machine learning engineer can use an iPad or Chromebook to perform data-heavy deep learning computations via GitHub Codespaces.

    Check out my DEV post and repository to learn more about how I generated art inside my codespace.

    Below you can see the code and AI image that GitHub Codespaces helped me produce:


    from torch import autocast # Change prompt for image here! prompt = "a cartoon black girl with cotton candy hair and a pink dress standing in front of a pink sky with cotton candy clouds" with autocast(device): image = pipe(prompt, height=768, width=768).images[0] image

    Computer-generated drawing-style image of a Black woman wearing a pink t-shirt, standing in front of a green field and some trees, with a pink cloud floating above her in the blue sky.

    Manage GitHub Codespaces from the command line 🧑‍💻

    Back in the 2000s, I would inadvertently close my documents, or my computer would suddenly shut down, and my work would be lost forever. Fortunately, it’s 2023, and many editors protect against that, including GitHub Codespaces. If you close a codespace, it will save your work even if you forget to commit your changes.

    However, if you’re done with a codespace because you pushed your code to a repository, you can feel free to delete it. GitHub Codespace management is important for the following reasons:

    • You don’t want to get confused with all your GitHub Codespaces and accidentally delete the wrong one.
    • By default, inactive GitHub Codespaces automatically delete every 30 days.

    You can manage your GitHub Codespaces through the GitHub UI or GitHub CLI. The GitHub CLI allows you to do things like:

    Create a codespace

    gh codespace create -r OWNER/REPO_NAME [-b BRANCH]
    

    List all your codespaces

    gh codespace list
    

    Delete a codespace:

    gh codespace delete -c CODESPACE-NAME
    

    Rename a codespace

    gh codespace edit -c CODESPACE-NAME -d DISPLAY-NAME
    

    Change the machine type of a codepace

    gh codespace edit -m MACHINE-TYPE-NAME
    

    This is not an exhaustive list of all ways you can manage GitHub Codespaces via the CLI. You learn more about managing your codespaces from the command line here!

    Pair program with a teammate 👥

    Pair programming when you’re working remotely is challenging. It’s harder to share your screen and your code when you’re not sitting next to your teammate. However, it’s worthwhile when it works because it helps both parties improve their communication and technical skills. Installing the Live Share extension and forward ports can make remote pair programming easier with GitHub Codespaces.

    Share your forwarded ports

    You can share the URL of your locally hosted web app and make it available to your teammates or collaborators. If you right-click on the port you’d like to share, you’ll see the option to switch the port visibility from “Private” to “Public.” If you copy the value in the local address and share it with necessary collaborators, they can view, test, and debug your locally hosted web app even though they’re in a different room than you.

    Screenshot of how to share the URL of your locally hosted web app by setting its port to public.

    Live Share

    The Live Share extension allows you and your teammate(s) to type in the same project simultaneously. It highlights your teammate’s cursor versus your cursor, so you can easily identify who is typing, and it’s completely secure!

    Screenshot of code in an editor showing sections highlighted and labeled with the names of users currently working on those lines.

    Pair program with AI 🤖

    Visual Studio Code’s marketplace offers a wide variety of extensions compatible with GitHub Codespaces, including GitHub Copilot. If you need to exchange ideas while you code, but there’s no one around, try installing the GitHub Copilot extension to pair program with AI. GitHub Copilot is an AI-powered code completion tool that helps you write code faster by suggesting code snippets and completing code for you.

    Beyond productivity through code completion, GitHub Copilot empowers developers of varied backgrounds. One of my favorite GitHub Copilot tools is “Hey, GitHub,” a hands-free, voice-activated AI programmer. Check out the video below to learn how “Hey, GitHub” improves the developer experience for folks with limited physical dexterity or visual impairments.



    Learn about more use cases for GitHub Copilot here.

    Gif demonstrating how Copilot can recommend lines of code.

    Teach people to code 👩‍🏫

    While educating people about coding via bootcamps, classrooms, meetups, and conferences, I’ve learned that teaching people how to code is hard. Sometimes in workshops, attendees spend most of the time trying to set up their environment so that they can follow along. However, teaching people to code or running a workshop in GitHub Codespaces creates a better experience for all participants. Instead of expecting beginner developers to understand how to clone repositories to work with a template, they can open up a codespace and work in a development environment you’ve configured. Now, you can have the peace of mind that everyone has the same environment as you and can easily follow along. This reduces tons of time, stress, and chaos.

    We made GitHub Codespaces more accessible for teachers and students by offering 180 free hours of usage (equivalent to five assignments per month for a class of 50). Check out my tutorial on configuring GitHub Codespaces and leveraging extensions like CodeTour to run self-guided workshops.

    Learn how CS50, Harvard’s largest class, uses GitHub Codespaces to teach students to code.

    Learn a new framework 📝

    When you’re learning to code, it’s easy to over-invest your time into following tutorials. Learning is often more effective when you balance tutorial consumption with building projects. GitHub Codespaces’ quickstart templates are a speedy and efficient way to learn a framework.

    Quickstart templates include boilerplate code, forwarded ports, and a configured development container for some of the most common application frameworks, including Next.js, React.js, Django, Express, Ruby on Rails, Preact, Flask, and Jupyter Notebook. Templates provide developers with a sandbox to build, test, and debug applications in a codespace. It only takes one click to open a template and experiment with a new framework.

    Experimenting with a framework in a codespace can help developers better understand a framework’s structure and functionalities, leading to better retention and mastery. For example, I’m not familiar with Jupyter Notebook, but I’ve used a Jupyter Notebook template in GitHub Codespaces. The boilerplate code helped me to experiment with and better understand the structure of a Jupyter Notebook. I even built a small project with it!

    Check out this blog post and template, where we use GitHub Codespaces to guide developers through writing their first lines of React.

    Screenshot showing a list of available codespace templates.

    Store environment variables 🔐

    In the past, I’ve had multiple moments where I’ve accidentally shared or mishandled my environment variables. Here are a few cringe-worthy moments where I’ve mishandled environment variables:

    • I’ve shown them to an audience during a live demo.
    • I’ve pushed them to GitHub.
    • I couldn’t figure out a great way to share the values with teammates.

    To avoid these moments, I could’ve used GitHub Codespaces secrets. You can store API Keys, environment variables, and secret credentials in your GitHub Codespaces secrets for each of your GitHub Codespaces.

    After you store them in your GitHub Codespaces secrets, you can refer to the environment variables in your code as: process.env.{SUPER_SECRET_API_KEY}.

    Check out this tutorial for more information on securely storing your environment variables with GitHub Codespaces

    Screenshot showing how to securely store your environment variables with GitHub Codespaces.

    Onboard developers faster 🏃💨

    Typically, software engineers are responsible for setting up their local environment when they join a team. Local environment setup can take a day or a week, depending on the quality of the documentation. Fortunately, organizations can automate the onboarding process using GitHub Codespaces to configure a custom environment. When a new engineer joins the team, they can open a codespace and skip the local environment setup because the required extensions, dependencies, and environment variables exist within the codespace.

    In 2021, the GitHub Engineering Team migrated from our macOS model to GitHub Codespaces for the development of GitHub.com. After over 14 years, our repository accrued almost 13 GB on disk. It took approximately 45 minutes to clone, set up dependencies, and bootstrap our repository. After fully migrating to GitHub Codespaces, it only takes 10 seconds to launch GitHub.com in a preconfigured, reliable codespace.

    However, you don’t have to take our word for it. Ketan Shah, Manager of Information Services at TELUS, a telecommunications company, attests, “GitHub shaves off entire days from the new employee onboarding process. New developers are up and running within minutes because everything is all in one place.”

    Learn more about GitHub Codespaces can quickly onboard developers:

    Conduct technical interviews 💼

    Take-home projects, technical screens, and live coding are often painful, but necessary parts of the interview experience for software developers, but using GitHub Codespaces can help ease some of the difficulties. By providing candidates with a well-configured and reliable environment, interviewers can help reduce anxiety and improve performance. With GitHub Codespaces, candidates no longer have to worry about setting up their environment. Interviewers can use GitHub codespaces to provide real-time feedback and collaborate using built-in tools like Visual Studio Code Live Share. Furthermore, GitHub Codespaces offers a secure and isolated environment for the interview process, ensuring that sensitive information and data remain protected.

    Learn how various engineering teams at GitHub use GitHub Codespaces to conduct interviews.

    Code in the cloud with your preferred editor ☁

    I love Visual Studio Code; it’s my primary editor. However, depending on your role and other factors, you might have a different preference. GitHub Codespaces supports the following editors, in addition to Visual Studio Code:

    • Jupyter Notebook
    • IntelliJ IDEA
    • RubyMine
    • GoLand
    • PyCharm
    • PhpStorm
    • WebStorm

    But, wait, there’s more!

    GitHub Codespaces’ superpower is that you can code from any device and get a standardized environment as long as you have internet. However, it also includes features that make software development workflows easier. With 60 hours of free access per month for GitHub users and 90 hours per month for GitHub Pro users, there’s no reason not to try it out and experience its benefits for yourself. So why not give it a try today?

    8 things you didn’t know you could do with GitHub Copilot

    Post Syndicated from Rizel Scarlett original https://github.blog/2022-09-14-8-things-you-didnt-know-you-could-do-with-github-copilot/

    Similar to other AI pair programming tools, GitHub Copilot is changing the game of software development. GitHub Copilot is an AI pair programmer that helps you write code faster with less work. We use the terms “AI pair programmer” and “Copilot” to imply that this tool cannot work without you–the developer! It’s not magic. It cannot read minds, although it sometimes feels like it can. However, by sharing code completion suggestions based on my project’s context and style conventions, GitHub Copilot increased my velocity and confidence as a programmer.

    The best part is you can use GitHub Copilot to increase your velocity and confidence as you code, too! In June 2022, we made GitHub Copilot available to all individual developers. You can learn how to get started with GitHub Copilot here.

    If it’s not reading minds and it’s not magic, then how does it work?

    Open AI Codex, a machine learning model that translates natural language into code, powers GitHub Copilot to draw context from comments and code to suggest individual lines and whole functions as you type. Codex is a version of GPT-3 (Generative Pre-trained Transformer 3) fine-tuned for programming tasks. Some of your favorite applications, like Duolingo, use GPT-3 for grammar correction.

    For more information on how GitHub Copilot works and its effectiveness, check out the following resources:

    Unexpected yet valuable GitHub Copilot use cases

    Once installed, the extension will suggest code as you type, but what next? How can you optimally benefit from the GitHub Copilot extension?

    First, I recommend writing clear, understandable comments to help your AI pair programmer generate desired solutions, but if you’re interested in exploring how to use GitHub Copilot in ways you might not be thinking of, we compiled some fun and valuable use cases we’ve seen in talking with developers. I hope that the following examples inspire you!

    1. Assisting non-native English speakers

    GitHub Copilot can understand other languages beyond English! This is helpful for developers of all backgrounds because programming languages are based on American English. For example, the CSS property color is based on American English, so it is unfamiliar for native British-English or Canadian-English speakers who use the spelling ‘colour’. Forgetting the correct spelling and syntax can often result in typos, unexpected errors, and lost time.

    In the GIF below, I wrote a comment in Spanish that says, “importar,” which translates to “import.” GitHub Copilot quickly completed my comment in Spanish and imported the necessary libraries as the comment described.

    Demonstration of GitHub Copilot interpreting a comment in Spanish.

    Additionally, GitHub Copilot helps translate words from English to other languages. MilMikDev on Twitter used GitHub Copilot to translate an array of words ‘answer’, ‘question,’ and ‘date’ to various languages.

    Demonstration of using GitHub Copilot to translate an array of words ‘answer’, ‘question,’ and ‘date’ to various languages.

    2. Creating dictionaries with lookup data

    Martin Woodward, Vice President of Developer Relations at GitHub, shared this tip with us! GitHub Copilot is great at creating dictionaries of lookup data. Try it out by writing a comment instructing GitHub Copilot to create a dictionary of two-letter ISO country codes and their contributing country name. Writing a comment and the first few lines of code should help GitHub Copilot generated the desired results. See the GIF below for visual representation!

    Demonstration of using GitHub Copilot to create a dictionary of two-letter ISO country codes and their contributing country name.

    3. Testing your code

    Writing tests is a vital yet sometimes tedious step in the software development lifecycle. Because GitHub Copilot excels in pattern recognition and pattern completion, it can speed up the process of writing unit tests, visual regression tests, and more.

    Check out these resources to learn more about using GitHub Copilot for testing:

    4. Matching patterns with regular expressions

    With GitHub Copilot, you can spend less time fiddling in a Regex playground or combing through StackOverflow to match character combinations in strings. Instead, you can write a comment or a function name to trigger GitHub Copilot’s suggestions.

    I used Copilot to help me validate a phone number!

    Demonstration of using GitHub Copilot to validate a phone number.

    GitHub Copilot can help you remove white space from a string!

    Demonstration of using GitHub Copilot to remove white space from a string.

    5. Preparing for technical interviews

    While this may sound unorthodox, developers, including myself, use GitHub Copilot to study for interviews.

    Here’s the strategy:

    • First, I try to solve the problem without GitHub Copilot.
    • If I’m feeling extremely stuck and disheartened while solving the problem, I’ll activate GitHub Copilot and use it to generate ideas on how to solve the problem better.
    • Subsequently, I’ll delete the code GitHub Copilot generated, deactivate GitHub Copilot, and make another attempt at finding a solution with the new information in mind.

    By adopting this method, I maintain momentum when tempted to quit. Instead of giving up, I gain new perspectives even when I don’t have a mentor or peer to guide me. GitHub Copilot becomes my digital mentor. But, note, that I highly discourage activating GitHub Copilot during an interview (that’s cheating!).

    Interestingly, chess players take a similar approach when preparing for matches. It’s common for chess players to practice against AI engines to advance their skills. In the publication, Towards Data Science, Bharath K writes, “Artificial Intelligence has influenced the way in which chess games are played at the top level. Most of the Grandmasters and Super Grandmasters (rated at a FIDE above 2700) utilize these modern AI chess engines to analyze their games and the games of their competitors.” Learn more about the influence of AI chess engines here.

    If AI is helping chess players advance their skills, perhaps it can positively impact developers’ problem-solving skills by challenging them to think differently about solving a problem.

    You can learn more about leveraging GitHub Copilot to solve algorithmic problems here. In the example below, I wrote a comment that says, “write a binary search algorithm,” and the first line of my function. GitHub Copilot correctly completed the function.

    Screenshot of a code editor demonstrating that GitHub Copilot correctly completed a function based on the input of a comment and the first line of the function.

    6. Sending tweets

    Of course, you can simply use the Twitter application to send a Tweet, but it’s more fun to send a Tweet via your IDE! As a Developer Advocate, part of my job is to create demos. In a recent livestream, I had to demonstrate using Twitter API v2 with GitHub Copilot in Python, a language that I rarely use. GitHub Copilot saved the day and generated the code I needed after I wrote a few comments. Read my DEV post if you want to try sending a tweet with GitHub Copilot, too!

    Screenshot of a tweet from Rizel Scarlett that reads, "I wrote this tweet with Copilot and I'm in KCDC right now."

    7. Exiting Vim

    Developers who are new to Vim frequently wonder how to exit the editor. Struggling to exit vim is so common that it’s a meme on the internet! Since GitHub Copilot is available in Visual Studio Code, JetBrains, and Neovim, a forked version of Vim with additional features, you can exit NeoVim using GitHub Copilot. In the video below, Brian Douglas uses GitHub Copilot to exit NeoVim, by writing a comment that says, “How do I exit vim?”

    8. Navigating a new codebase with Copilot Labs

    GitHub Copilot Labs is a complementary extension that comes with GitHub Copilot access. The GitHub Next team developed GitHub Copilot Labs, an experimental sidebar, to help developers translate code from one programming language to another and get a step-by-step explanation of code snippets.

    There’s no easy method for building a mental model of a new codebase, but these two features within GitHub Copilot Labs can help. By translating code snippets to languages they’re more familiar with and using the ‘Explain’ feature to gain an understanding of the code, developers can better comprehend complex blocks of code.

    Demonstration of using Copilot's ‘Explain’ feature to gain an understanding of the code, developers can better comprehend complex blocks of code.

    Closeup look at the results of Copilot's 'Explain' feature being used.

    Wrap-up

    As you’ve seen in the examples above, GitHub Copilot can help you be more productive in so many ways day to day (a lot of which we’re still discovering!), and I want to kindly remind you that GitHub Copilot is an AI pair programmer, so just as you would with your coworkers’ code or even your own, review the generated code before pushing it to production! While GitHub Copilot is powerful, sometimes it makes mistakes or refers to an outdated version of an API. Nevertheless, the team at GitHub continues to work hard and learn from our users to develop a better experience and generate better results with GitHub Copilot. I’m excited to witness and experience the evolution of AI pair programming tools. If you’re just as eager as me, sign up for GitHub Copilot today!