teleren/devto huggingface dataset:
How to create an input search with debounce using Rxjs on Angular
Tags: angular, javascript
Published: 2024-01-28 16:17:57

Sometimes we need to create features like a search component that calls the API to return a search based on a string typed. The problem is we should **prevent the application** from calling the API **many times** because the user can type a lot fast and it is a problem.

Many developers would solve it with a library like Lodash, forgetting that it is super easy to solve it with Rxjs, the library included on the framework Angular.

In this example, I will focus on resolution with **debounce** using a simple component and input.

```html
<input 
 type="text" 
 [ngModel]="search" 
 (ngModelChange)="handleSearch($event)" 
 placeholder="Quick Search">
```

Using the `(ngModelChange)` we are able to listen to any change on the model and get the last value, using standalone components we need to import `FormsModule `as well.

```typescript
@Component({
  selector: 'app-root',
  standalone: true,
  template: `<input type="text" [ngModel]="search" (ngModelChange)="handleSearch($event)" placeholder="Quick Search">`,
  imports: [FormsModule],
})
```

Now all you need is a bit of code:

#### 1) Declare the search variable:
```typescript
search = '';
```

#### 2) Initialize a BehavierSubject:
```typescript
 searchSubject = new BehaviorSubject<string>('');
```

#### 3) Sends the value to the Subject using ngModelChange:
```typescript
handleSearch(search: string) {
  this.searchSubject.next(search);
}
```

#### 4) Subscribe the Subject:
```typescript
constructor() {
    this.searchSubject
    .pipe(debounceTime(550))
    .subscribe((search) => {
      console.log('Searching', search);
    });
}
```

## Final results 🙌
![Screen Stackblitz showing the example code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jwsckc44he1ow19jyegc.gif)

[Demo application](https://stackblitz.com/edit/stackblitz-starters-kz8qow?file=src%2Fmain.ts)
7 bibliotecas para React
Tags: react, library, programming, frontend
Published: 2024-01-28 16:16:44

Aquí tienes una lista de 7 bibliotecas que son imprescindibles para cualquier programador de React:

**Sonner**: Facilita la muestra de notificaciones en tu aplicación con configuración sencilla en solo 3 líneas de código. Puedes encontrar más información en https://sonner.emilkowal.ski

**⌘K (CmdK)**: Agrega navegación por teclado a tu sitio web para mejorar la experiencia de usuario. Descubre cómo implementarlo en https://cmdk.paco.me

**Iconos Animados**: Eleva el atractivo visual de tu página web con esta colección de iconos que incluyen animaciones. Explora las posibilidades en https://react.useanimations.com

**Calendario Reactivo**: Renderiza un calendario interactivo para navegar meses y días, totalmente personalizable para que se adapte al estilo de tu página. Más detalles en https://react-day-picker.js.org

**FilePond**: Simplifica la carga de archivos mediante la funcionalidad de arrastrar y soltar. Compatible no solo con React, sino también con Vue y Angular. Descúbrelo en https://pqina.nl/filepond

**React Hook Form**: Optimiza tus formularios y reduce la cantidad de código necesario con este conjunto de componentes eficiente. Obtén más información en https://react-hook-form.com

**Vault**: Integra un componente de caja flotante (drawer) configurable que puede deslizarse desde la parte inferior o lateral de la página. Descubre las opciones de personalización en https://vaul.emilkowal.ski

Esta selección de bibliotecas proporciona herramientas esenciales para mejorar la funcionalidad y apariencia de tus aplicaciones React. ¡Aprovéchalas para llevar tus proyectos al siguiente nivel!
Evita usar UpperCase o LowerCase C#
Tags: tip, csharp, cleancode, aspnet
Published: 2024-01-28 16:15:45

🚫 𝗖𝗼𝗱𝗲 𝗦𝗺𝗲𝗹𝗹
✔** Usar string.𝗘𝗾𝘂𝗮𝗹𝘀 en lugar de 𝗧𝗼𝗨𝗽𝗽 𝗲𝗿()/𝗧𝗼𝗟𝗼𝘄𝗲𝗿() cuando comparamos cadenas de texto**.

🐌 El uso de 𝗧𝗼𝗨𝗽𝗽𝗲𝗿() y 𝗧𝗼𝗟𝗼𝘄𝗲𝗿() para la conversión de casos en C# puede afectar el rendimiento debido a la asignación de memoria, la copia de cadenas y la posible recolección de basura, especialmente en situaciones que involucran cadenas grandes o conversiones frecuentes.

🚀 𝗦𝘁𝗿𝗶𝗻𝗴.𝗘𝗾𝘂𝗮𝗹𝘀 es más rápido que ToUpper() o ToLower() debido a la comparación directa de caracteres, evitando la asignación de memoria y reduciendo la sobrecarga para la comparación de cadenas que no distingue entre mayúsculas y minúsculas.

🔥 Para realizar una comparación de cadenas, es mejor utilizar los métodos de comparación integrados como 𝗦𝘁𝗿𝗶𝗻𝗴.𝗘𝗾𝘂𝗮𝗹𝘀 con las opciones apropiadas de StringComparison, que manejan correctamente la distinción entre mayúsculas y minúsculas y las consideraciones culturales mientras mantienen un mejor rendimiento y precisión.


**Gracias por leer** 📖


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xda03txgzisjpk1uuda8.png)
List of AI Terminologies
Published: 2024-01-28 16:08:28

**List of AI Terminologies**



    Chainlit
    Streamlit
    Text generation web UI
    Lang Flow

Middleware

    LangChain
    LangChain Visualizer

Images

    wirestock.io

Plugins

    https://ai-advantage.notion.site/ChatGPT-Plugins-81cc7cc2107a4065a8b0a0f3f73d9b19

Fine Tune

    privateGPT

Other

    https://github.com/nicknochnack/Nopenai
    Fly.io
AI Custom Instructions Prompt
Published: 2024-01-28 16:01:43

**AI Custom Instructions Prompt**



Act as Professor Synapse ❤️, a conductor of expert agents. Your job is to support me in accomplishing my goals by finding alignment with me, then calling upon an expert agent perfectly suited to the task by initialising:

Synapse_CoR = “[emoji]: I am an expert in [role&domain]. I know [context]. I will reason step-by-step to determine the best course of action to achieve [goal]. I can use [tools] and [relevant frameworks] to help in this process.

I will help you accomplish your goal by following these steps:
[reasoned steps]

My task ends when [completion].

[first step, question]”

Instructions:
1. ❤️ gather context, relevant information and clarify my goals by asking questions
2. Once confirmed, initialize Synapse_CoR
3. ❤️ and ${emoji} support me until goal is complete

Commands:
/start=❤️,introduce and begin with step one
/ts=❤️,summon (Synapse_CoR*3) town square debate
/save❤️, restate goal, summarize progress, reason next step

Personality:
-curious, inquisitive, encouraging
-use emojis to express yourself

Rules:
-End every output with a question or reasoned next step
-Start every output with ❤️: or ${emoji}: to indicate who is speaking.
-Organize every output with ❤️ aligning on my request, followed by ${emoji} response
-❤️, recommend save after each task is completed
Chat GPT API Node.js
Published: 2024-01-28 16:00:09

**Chat GPT API Node.js**

npm install openai

**ES6**

import OpenAI from "openai";

const openai = new OpenAI();

const chatCompletion = await openai.chat.completions.create({
    messages: [{ role: "user", content: "Say this is a test" }],
    model: "gpt-3.5-turbo",
});

console.log(chatCompletion.choices[0].message.content);

package.json

{
  "dependencies": {
    "openai": "^4.12.4"
  },
  "type": "module"
}

CommonJS

const OpenAI = require("openai");

const openai = new OpenAI();

openai.chat.completions.create({
  messages: [{ role: "user", content: "Say this is a test" }],
  model: "gpt-3.5-turbo",
})
.then(chatCompletion => {
  console.log(chatCompletion.choices[0].message.content);
})
.catch(console.error);



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78yw2ao0vlod19dyzx2m.png)


Which is Best?

    For New Projects: ES6 is modern and efficient.
    For Older Projects: CommonJS is well-supported and easy.

Combined Recommendation: Choose CommonJS for simplicity and legacy support. Choose ES6 for modern features and better optimization.
Langchain Vertex AI
Published: 2024-01-28 15:56:51

**Langchain Vertex AI**



    Python package: google-cloud-aiplatform
    Environment setup:
        Credentials (gcloud, workload identity)
        Or GOOGLE_APPLICATION_CREDENTIALS environment variable

Install Command:

pip install langchain google-cloud-aiplatform

Documentation:

    Application Default Credentials
    Google Auth Library

# Code 1
from langchain.llms import VertexAI
llm = VertexAI()
print(llm("What are some of the pros and cons of Python as a programming language?"))

# Code 2
from langchain.prompts import PromptTemplate
template = "Question: {question}\nAnswer: Let's think step by step."
prompt = PromptTemplate.from_template(template)
chain = prompt | llm
question = "Who was the president in the year Justin Beiber was born?"
print(chain.invoke({"question": question}))

# Code 3
llm = VertexAI(model_name="code-bison", max_output_tokens=1000, temperature=0.3)
question = "Write a python function that checks if a string is a valid email address"
print(llm(question))

# Code 4
result = llm.generate([question])
result.generations

# Code 5
import asyncio
asyncio.run(llm.agenerate([question]))

# Code 6
import sys
for chunk in llm.stream(question):
    sys.stdout.write(chunk)
    sys.stdout.flush()
ChatGPT Chatbot
Published: 2024-01-28 15:56:18

**ChatGPT Chatbot**

import openai

def chatbot(prompt):
    response = openai.ChatCompletion.create(
        model = "gpt-3.5-turbo", 
        messages = [{'role': 'user', 'content': prompt}],
    )
    return response['choices'][0]['message']['content']
    
if __name__ == "__main__":
    while True:
        user_input = input("You: ")
        if user_input.lower() in ["exit", "quit"]:
            break
        print("Bot: ", chatbot(user_input))
Autogen Ollama Integration
Published: 2024-01-28 15:55:46

**Autogen Ollama Integration**



litellm --model ollama/mistral

import autogen

config_list = [
    {
        "api_base": "http://127.0.0.1:8000",
        "api_key" : "NULL",
    }
]

llm_config = {
    "request_timeout" : 800,
    "config_list" : config_list
}

assistant = autogen.AssistantAgent(
    "assistant",
    llm_config = llm_config
)

user_proxy = autogen.UserProxyAgent(
    "user_proxy",
    code_execution_config = {
        "work_dir" : "coding"
    }
)

user_proxy.initiate_chat(
    assistant,
    message ="What is the name of the model you are based on?"
)
AutoLLM with Interface
Published: 2024-01-28 15:55:11

**AutoLLM with Interface**

from autollm import AutoQueryEngine
from llama_index import SimpleDirectoryReader
import gradio as gr

documents = SimpleDirectoryReader('data').load_data()

query_engine = AutoQueryEngine.from_parameters(
    documents = documents
)

def main(query):
    return query_engine.query(query).response

demo = gr.Interface(fn=main, inputs="text", outputs="text")
    
demo.launch()
AutoLLM Basic
Published: 2024-01-28 15:54:39

**AutoLLM Basic**

from autollm import AutoQueryEngine
from llama_index import SimpleDirectoryReader

documents = SimpleDirectoryReader('data').load_data()

query_engine = AutoQueryEngine.from_parameters(
    documents = documents
)
response = query_engine.query(
  "Explain me about AutoLLM"
)
print(response)
AutoLLM API
Published: 2024-01-28 15:54:15

**AutoLLM API**

from autollm import AutoQueryEngine
from llama_index import SimpleDirectoryReader
import uvicorn
from autollm import AutoFastAPI

documents = SimpleDirectoryReader('data').load_data()

query_engine = AutoQueryEngine.from_parameters(
    documents = documents
)

app = AutoFastAPI.from_query_engine(query_engine)

@app.get("/")
async def read_query(q: str):
    return query_engine.query(q)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
Llama Index Beginners
Published: 2024-01-28 15:53:27

**Llama Index Beginners**



from llama_index import VectorStoreIndex, SimpleDirectoryReader

documents = SimpleDirectoryReader('data').load_data()
index = VectorStoreIndex.from_documents(documents)
index.storage_context.persist()

query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")
print(response)

Put all the .txt in the data folder.
Llama Index and Supabase
Published: 2024-01-28 15:52:56

**Llama Index and Supabase**



!pip install -qU llama_index

import os
from llama_index import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores import SupabaseVectorStore

os.environ['OPENAI_API_KEY'] = "[your_openai_api_key]"

documents = SimpleDirectoryReader('data').load_data()
index = VectorStoreIndex.from_documents(documents)
index.storage_context.persist()

DB_PASSWORD = os.environ['DB_PASSWORD']
DB_CONNECTION = f"postgresql://postgres:{DB_PASSWORD}@localhost:5431/db"

vector_store = SupabaseVectorStore(
    postgres_connection_string=DB_CONNECTION,
    collection_name='base_demo'
)

query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")
print(response)
Llama Index + Supabase + Gradio
Published: 2024-01-28 15:52:03

**Llama Index + Supabase + Gradio**

import os
import gradio as gr
from llama_index import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores import SupabaseVectorStore

# Set up environment variable and data
os.environ['OPENAI_API_KEY'] = "[your_openai_api_key]"

documents = SimpleDirectoryReader('data').load_data()
index = VectorStoreIndex.from_documents(documents)
index.storage_context.persist()

DB_PASSWORD = os.environ['DB_PASSWORD']
DB_CONNECTION = f"postgresql://postgres:{DB_PASSWORD}@localhost:5431/db"

vector_store = SupabaseVectorStore(
    postgres_connection_string=DB_CONNECTION,
    collection_name='base_demo'
)

query_engine = index.as_query_engine()

def main(question):
    response = query_engine.query(question)
    return response

# Gradio interface
ui = gr.Interface(
    fn=main,
    inputs=gr.inputs.Textbox(placeholder="Enter your question about the author..."),
    outputs=gr.outputs.Textbox()
)
ui.launch()
LocalAI Setup
Published: 2024-01-28 15:49:46

**LocalAI Setup**.

git clone https://github.com/go-skynet/LocalAI
cd LocalAI
wget https://huggingface.co/TheBloke/Luna-AI-Llama2-Uncensored-GGUF/resolve/main/luna-ai-llama2-uncensored.Q4_0.gguf -O models/luna-ai-llama2
cp -rf prompt-templates/getting_started.tmpl models/luna-ai-llama2.tmpl
docker compose up -d --pull always
curl http://localhost:8080/v1/models
curl http://localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{
     "model": "luna-ai-llama2",
     "messages": [{"role": "user", "content": "How are you?"}],
     "temperature": 0.9
   }'
Functional JS
Published: 2024-01-28 15:48:04

I keep on forgetting some cool declarative methods in JS, so this is a reminder compilation for me to refresh my memory as I encounter them doing coding challenges.

- `Array.prototype.sort(compareFn)`. Mutates array "in place" after converting values to string and comparing UTF-16 code unit values. Values are sorted ascending. If you don't want to mutate the array, use `toSorted`. `compareFn` is called with `a` and `b` and should return a negative number if `a` is smaller than `b`, positive if `a` is bigger than `b` or 0 if they are the same. If `compareFn` is not supplied the array is sorted after comparing the values to their string form. More [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).
- `Math.max(value1, value2, etc.)` and `Math.min(value1, value2, etc.)`. If the array has few elements, you can use it like `Math.max(...array)`. It is best to use `reduce`:

```
const arr = [1, 2, 3];
const max = arr.reduce((a, b) => Math.max(a, b), -Infinity);
```
- `String.prototype.repeat(count)`. Repeats a string a `count` number of times. i.e. `'Hello'.repeat(3)` return `HelloHelloHello`.
- `Array.prototype.some(cb)` - returns `true` if one item in the array returns a truthy value when the callback is called upon or `false` otherwise. It stops iterating as soon as it find an element that returns a truthy value.
- `0 + true` is `1` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus#usage_with_non-numbers
- `new Set([1,1,3,2,2,3,4])` will get rid of the duplicates and return `[1,3,2,4]` because a `set` can't have duplicates.
- `address.split('@').pop()` will return the domain in an email even when there are 2 `@`s.

#### Regex stuff

- `/^\d*/` < match any series of digits at the start. You can then do `string.match(/^\d*/)` to find a prefix made up of digits only.
- `'string'.match(regex)` will return the matches. If the `g` flag is used, it returns an array with the matches. If not, just the first match. i.e. `'010010000110010101101100011011000110111100100001'.match(/.{1,8}/g)` will return an array of bytes.
- `String.fromCharCode(charCode)` returns the ASCII string attached to the charCode.

#### Binary numbers

- `parseInt(binaryNumberString, 2)` will return the integer of the number in whatever base we say. The example is base 2.
ChatGPT API Python
Published: 2024-01-28 15:44:27

**ChatGPT API Python**



import openai
client = openai.OpenAI()

reponse = client.chat.completions.create(
    model= "gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": "Who won the cricket world cup in 2019?"}
    ]
)

print(reponse.choices[0].message.content)




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aufavhkxgwcdkxw9m5qt.png)
Seed in ChatGPT AI
Published: 2024-01-28 15:43:43

**Seed in ChatGPT AI**

import openai
client = openai.OpenAI()

response = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "user", "content": "Who won the cricket world cup in 2015?"}
  ],
  seed=1
)

print(response.choices[0].message.content)
ChatGPT JSON Response
Published: 2024-01-28 15:43:04

**ChatGPT JSON Response**

import openai

client = openai.OpenAI()

response = client.chat.completions.create(
  model="gpt-4-1106-preview",
  messages=[
    {"role": "system", "content": "Generate JSON response"},
    {"role": "user", "content": "Who won the cricket world cup in 2019?"}
  ],
  response_format= { "type": "json_object" }
)

print(response.choices[0].message.content)
ChatGPT Dalle 3 API
Published: 2024-01-28 15:42:01

**ChatGPT Dalle 3 API**

import openai
client = openai.OpenAI()

response = client.images.generate(
    model= "dall-e-3",
    prompt="a white siamese cat",
    size="1024x1024",
    quality="standard",
    n=1
)
image_url = response.data[0].url
print(image_url)
ChatGPT Speech to Text Whisper API
Published: 2024-01-28 15:41:21

**ChatGPT Speech to Text Whisper API**

import openai
client = openai.Client()

audio_file= open("speech.mp3", "rb")
transcript = client.audio.transcriptions.create(
    model = "whisper-1",
    file=audio_file
)
print(transcript.text)
ChatGPT Image Recognition API
Published: 2024-01-28 15:40:55

**ChatGPT Image Recognition API**


import openai
client = openai.OpenAI()

response = client.chat.completions.create(
    model="gpt-4-vision-preview",
    messages = [
        {
            "role" : "user",
            "content" :
            [
                {"type" : "text", "text" : "What's in this image?"},
                {
                    "type" : "image_url",
                    "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
                }
            ]
        }
    ],
    max_tokens = 300
)

print(response.choices[0].message.content)
ChatGPT Assistants API Python
Published: 2024-01-28 15:39:34

**ChatGPT Assistants API Python**



import openai

# Initialize the client
client = openai.OpenAI()

# Step 1: Create an Assistant
assistant = client.beta.assistants.create(
    name="Math Tutor",
    instructions="You are a personal math tutor. Write and run code to answer math questions.",
    tools=[{"type": "code_interpreter"}],
    model="gpt-4-1106-preview"
)

# Step 2: Create a Thread
thread = client.beta.threads.create()

# Step 3: Add a Message to a Thread
message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="I need to solve the equation `3x + 11 = 14`. Can you help me?"
)

# Step 4: Run the Assistant
run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant.id,
    instructions="Please address the user as Jane Doe. The user has a premium account."
)

print(run.model_dump_json(indent=4))

while True:
    # Wait for 5 seconds
    time.sleep(5)  

    # Retrieve the run status
    run_status = client.beta.threads.runs.retrieve(
        thread_id=thread.id,
        run_id=run.id
    )
    print(run_status.model_dump_json(indent=4))

    # If run is completed, get messages
    if run_status.status == 'completed':
        messages = client.beta.threads.messages.list(
            thread_id=thread.id
        )
        
        # Loop through messages and print content based on role
        for msg in messages.data:
            role = msg.role
            content = msg.content[0].text.value
            print(f"{role.capitalize()}: {content}")
        
        break
OpenAI Assistants API in Node.js
Published: 2024-01-28 15:38:53

**OpenAI Assistants API in Node.js**

import OpenAI from "openai";
const openai = new OpenAI();

const assistant = await openai.beta.assistants.create({
    name: "Math Tutor",
    instructions:
        "You are a personal math tutor. Write and run code to answer math questions.",
    tools: [{ type: "code_interpreter" }],
    model: "gpt-4-1106-preview",
});

const thread = await openai.beta.threads.create();

const message = await openai.beta.threads.messages.create(thread.id, {
    role: "user",
    content: "I need to solve the equation `3x + 11 = 14`. Can you help me?",
});

const run = await openai.beta.threads.runs.create(thread.id, {
    assistant_id: assistant.id,
    instructions: "Please address the user as Mervin Praison.",    
});

console.log(run)

const checkStatusAndPrintMessages = async (threadId, runId) => {
    let runStatus = await openai.beta.threads.runs.retrieve(threadId, runId);
    if(runStatus.status === "completed"){
        let messages = await openai.beta.threads.messages.list(threadId);
        messages.data.forEach((msg) => {
            const role = msg.role;
            const content = msg.content[0].text.value; 
            console.log(
                `${role.charAt(0).toUpperCase() + role.slice(1)}: ${content}`
            );
        });
    } else {
        console.log("Run is not completed yet.");
    }  
};

setTimeout(() => {
    checkStatusAndPrintMessages(thread.id, run.id)
}, 10000 );
Pandas AI Examples
Published: 2024-01-28 15:38:13

**Pandas AI Examples**

import pandas as pd
from pandasai import SmartDataframe
from pandasai.llm import OpenAI

df = pd.read_excel('data.xlsx')
df = pd.read_csv('data.csv')

llm = OpenAI(model="gpt-3.5-turbo")
df = SmartDataframe(df, config={"llm": llm})

print( df.chat('Which are the 5 happiest countries?'))
print( df.chat('What is the sum of the GDPs of the 2 happiest countries?'))
print( df.chat('Plot the histogram of countries showing for each the gdp, using different colors for each bar',))