Skip to content

Commit

Permalink
post: add local code ai assistant
Browse files Browse the repository at this point in the history
  • Loading branch information
leoferreiralima committed Jun 21, 2024
1 parent 8fad9c6 commit c39f50b
Show file tree
Hide file tree
Showing 13 changed files with 740 additions and 429 deletions.
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
"astro": "astro"
},
"dependencies": {
"@astrojs/check": "^0.5.10",
"@astrojs/mdx": "^2.3.1",
"@astrojs/rss": "^4.0.5",
"@astrojs/sitemap": "^3.1.2",
"@astrojs/check": "^0.7.0",
"@astrojs/mdx": "^3.1.1",
"@astrojs/rss": "^4.0.6",
"@astrojs/sitemap": "^3.1.6",
"@astrojs/tailwind": "^5.1.0",
"@astrojs/vercel": "^7.5.4",
"@astrojs/vercel": "^7.7.1",
"@fontsource/inter": "^5.0.18",
"@fontsource/newsreader": "^5.0.18",
"astro": "^4.5.17",
"astro": "^4.11.0",
"astro-robots-txt": "^1.0.0",
"marked": "^12.0.1",
"posthog-node": "^4.0.1",
Expand Down
997 changes: 593 additions & 404 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 23 additions & 0 deletions src/components/Giscus.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
---

<div class="giscus"></div>

<script
is:inline
src="https://giscus.app/client.js"
data-repo="leoferreiralima/leoferreira.dev"
data-repo-id="R_kgDOHWVklA"
data-category="Announcements"
data-category-id="DIC_kwDOHWVklM4CfTAM"
data-mapping="pathname"
data-strict="1"
data-reactions-enabled="1"
data-emit-metadata="0"
data-input-position="top"
data-theme="dark"
data-lang="pt"
data-loading="lazy"
crossorigin="anonymous"
async></script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
title: Configurando um assistente IA local para programação
excerpt: In recent years, the way we work has undergone a significant transformation, largely due to advancements in technology and changing attitudes toward work-life balance. One of the most notable changes has been the rise of remote work, allowing employees to work from the comfort of their own homes.
publishDate: '2024-06-21 12:00:00'
isFeatured: true
tags:
- IA
- Assitente IA
- Inteligência Artificial
- Programação
- VsCode
- Ollama
image:
src: '../../assets/posts/local-code-ai-assistant/hero.png'
alt: Ollama + VsCode
---

Não é novidade que a Inteligência Artificial está em alta, trazendo consigo uma série de ferramentas para facilitar o dia a dia em diversas áreas.
No mundo da programação, uma das grandes inovações é o GitHub Copilot, desenvolvido com a ajuda da OpenAI.

No entanto, o Copilot é uma ferramenta paga e não oferece garantias sólidas de privacidade dos seus dados.

Felizmente, existem alternativas gratuitas que proporcionam resultados semelhantes.
Uma excelente combinação é o Ollama, junto com a extensão Continue para o Visual Studio Code (VSCode).

Siga o passo a passo abaixo para instalar e configurar o Ollama e a extensão Continue no VSCode:

## 1. Instalação do Ollama

Ollama é uma ferramenta open source para executar LLMs localmente no seu computador.
É possível rodar modelos como: Llama 3, Phi 3, Mistral, Gemma, etc.
Para ver a listagem completa acesso a página de [modelos](https://www.ollama.com/library)

Para instalar Ollama, siga as instruções no site oficial: https://www.ollama.com

## 2. Instalação da extensão Continue

Após a instalação do Ollama, é necessário configurar a extensão Continue na IDE.

Na aba de extensões do VsCode, procure por [**Continue**](https://marketplace.visualstudio.com/items?itemName=Continue.continue) e clique em **Instalar**.

![Continue VsCode Extension](../../assets/posts/local-code-ai-assistant/continue-extension.png)

Ao instalar a extensão, sera necessário rodar os modelos do ollama. Isso pode ser feito no próprio VsCode na aba do Continue.

1. Selecione a aba **Continue** e clique em **Local Models**.

2. Rode os modelos do Ollama. Neste caso usaremos o Llamma3 para chat e o starcoder2 para gerar código.

3. Após a execução dos modelos, você está pronto para usar o Continue.

**Obeservação:** Também é possivel usar outros modelos, para mais informações acesse a documentação oficial do [Continue](https://docs.continue.dev/setup/configuration)

## 3. Começe a usar!

Depois de tudo configurado é só usar. Além de te ajudar a escrever, gerar e explicar código,
o Continue também consegue aprender com o seu codebase para dar sugestões mais precisas.

Abaixo está listado alguns exemplos de uso junto com uma demostração.

### Conversando via Chat

Assim como o ChatGPT, podemos usar o Chat para conversar com o assistente IA.

![Llamma Chat](/assets/posts/local-code-ai-assistant/lamma-chat.gif)

### Geração de código com um simples prompt

Além de fazer perguntas, o assistente IA também pode gerar código para você.

![Lamma Generate Code](/assets/posts/local-code-ai-assistant/lamma-generate-code.gif)

### Escreva código com ajuda do auto complete e economize tempo

E claro, o assistente IA também pode ajudar a escrever ou te explicar o código.

![Auto Complete Code](/assets/posts/local-code-ai-assistant/lamma-auto-complete-code.gif)

Não deixe de conferir a documentação e blog oficial do [Ollama](https://www.ollama.com/blog/continue-code-assistant) e do [Continue](https://www.continue.dev/)
para saber mais sobre como usar o assistente IA em diferentes aplicativos e linguagens de programação.
5 changes: 4 additions & 1 deletion src/content/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@ const blog = defineCollection({
z.object({
title: z.string(),
excerpt: z.string().optional(),
image: z.object({
src: context.image(),
alt: z.string()
}).optional(),
publishDate: z.coerce.date(),
updatedDate: z.coerce.date().optional(),
isFeatured: z.boolean().default(false),
tags: z.array(z.string()).default([]),
seo: seoSchema(context).optional()
Expand Down
32 changes: 18 additions & 14 deletions src/pages/blog/[slug].astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import BaseLayout from '../../layouts/BaseLayout.astro';
import Button from '../../components/Button.astro';
import FormattedDate from '../../components/FormattedDate.astro';
import PostPreview from '../../components/PostPreview.astro';
import { slugify } from '../../utils/common-utils';
import { slugify, getReadTimeInMintues } from '../../utils/common-utils';
import { getAllPosts } from '../../services/blog';
import { Image } from 'astro:assets';
import Giscus from '@/components/Giscus.astro';
export const prerender = true;
Expand All @@ -26,26 +28,27 @@ type Props = { post: CollectionEntry<'blog'>; prevPost: CollectionEntry<'blog'>;
const { href } = Astro.url;
const { post, prevPost, nextPost } = Astro.props;
const { title, publishDate, updatedDate, excerpt, tags = [], seo } = post.data;
const { title, publishDate, excerpt, tags = [], image, seo } = post.data;
const { Content } = await post.render();
const readTimeInMintues = getReadTimeInMintues(post.body);
---

<BaseLayout title={seo?.title ?? title} description={seo?.description ?? excerpt} image={seo?.image} pageType="article" showHeader={false}>
<BaseLayout title={seo?.title ?? title} description={seo?.description ?? excerpt} image={seo?.image ?? image} pageType="article" showHeader={false}>
<article class="mb-16 sm:mb-24">
<header class="mb-8">
{
image && (
<div class="mb-8 sm:mb-12">
<Image src={image?.src} alt={image.alt} />
</div>
)
}
<h1 class="text-3xl leading-tight font-serif font-medium sm:text-5xl sm:leading-tight">{title}</h1>
<div class="mt-4 text-sm">
<div class="mt-4 text-sm flex justify-between">
<FormattedDate date={publishDate} />
{
updatedDate && (
<>
{' '}
<span>
(Atualizado em <FormattedDate date={updatedDate} />)
</span>
</>
)
}

<span>{readTimeInMintues} min de Leitura</span>
</div>
</header>
<div class="max-w-none prose prose-dante sm:prose-lg">
Expand Down Expand Up @@ -77,6 +80,7 @@ const { Content } = await post.render();
</div>
)
}
<Giscus />
</BaseLayout>

<script>
Expand Down
12 changes: 9 additions & 3 deletions src/utils/common-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,16 @@ export function slugify(input?: string) {
export async function getImageMetadata(path: string) {
const images = import.meta.glob<{ default: ImageMetadata }>('/src/assets/*.{jpeg,jpg,png,gif,webp}');

if (!images[path]) {
throw new Error(`"${path}" does not exist in glob: "src/assets/*.{jpeg,jpg,png,gif}"`);
if (!images[path]) {
throw new Error(`"${path}" does not exist in glob: "src/assets/*.{jpeg,jpg,png,gif}"`);
}

const image = await images[path]();
return image.default;
}
}

export function getReadTimeInMintues(text: string) {
const wpm = 200;
const wordsQuantity = text.split(/[^A-Za-z]+/).length;
return Math.ceil(wordsQuantity / wpm);
}
8 changes: 7 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
{
"extends": "astro/tsconfigs/strict",
"compilerOptions": {
"strictNullChecks": true
"strictNullChecks": true,
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
}
}

0 comments on commit c39f50b

Please sign in to comment.