teleren/devto huggingface dataset:
API Google Gemini Function Calling
Published: 2024-01-28 14:42:23

**
API
Google Gemini Function Calling**




import yfinance as yf
from vertexai.preview.generative_models import (
    FunctionDeclaration,
    GenerativeModel,
    Part,
    Tool,
)

# Function to Get Stock Price
def get_stock_price(parameters):
    ticker = parameters['ticker']
    stock = yf.Ticker(ticker)
    hist = stock.history(period="1d")
    if not hist.empty:
        return {"price": hist['Close'].iloc[-1]}
    else:
        return {"error": "No data available"}

# Tools
tools = Tool(function_declarations=[
    FunctionDeclaration(
        name="get_stock_price",
        description="Get the current stock price of a given company",
        parameters={
            "type": "object",
            "properties": {
                "ticker": {
                    "type": "string",
                    "description": "Stock ticker symbol"
                }
            }
        },
    )
])

# Model Initialization
model = GenerativeModel("gemini-pro", 
                        generation_config={"temperature": 0},
                        tools=[tools])
chat = model.start_chat()

# Send a prompt to the chat
prompt = "What is the stock price of Apple?"
response = chat.send_message(prompt)

# Check for function call and dispatch accordingly
function_call = response.candidates[0].content.parts[0].function_call

# Dispatch table for function handling
function_handlers = {
    "get_stock_price": get_stock_price,
}

if function_call.name in function_handlers:
    function_name = function_call.name

    # Directly extract arguments from function call
    args = {key: value for key, value in function_call.args.items()}

    # Call the function with the extracted arguments
    if args:
        function_response = function_handlers[function_name](args)

        # Sending the function response back to the chat
        response = chat.send_message(
            Part.from_function_response(
                name=function_name,
                response={
                    "content": function_response,
                }
            ),
        )

        chat_response = response.candidates[0].content.parts[0].text
        print("Chat Response:", chat_response)
    else:
        print("No arguments found for the function.")
else:
    print("Chat Response:", response.text)
Google Gemini + LangChain
Published: 2024-01-28 14:40:53

**Google Gemini + LangChain**



from langchain_google_genai import ChatGoogleGenerativeAI

# Basic Gemini with LangChain
llm = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.7)
result = llm.invoke("Write a meal plan for today")
print(result.content)

for chunk in llm.stream("Write a meal plan for today"):
    print(chunk.content)
    print("---")
    
# Basic Multi Chain
from langchain.prompts import ChatPromptTemplate
from langchain.schema.output_parser import StrOutputParser

prompt = ChatPromptTemplate.from_template(
    "tell me about {topic}"
)
output_parser = StrOutputParser()
chain = prompt | llm | output_parser
print(chain.invoke({"topic": "Artificial Intelligence"}))

# Multi Modal
import requests
from langchain_core.messages import HumanMessage

llm = ChatGoogleGenerativeAI(model="gemini-pro-vision", temperature=0.7)
image_url = "https://raw.githubusercontent.com/langchain-ai/langchain/master/docs/static/img/agents_vs_chains.png"
content = requests.get(image_url).content

message = HumanMessage(content=[{"type": "text", "text": "What's in this image and who lives there?"}, 
                                {"type": "image_url", "image_url": image_url}])
print(llm.invoke([message]).content)
Mistral Finetuning using Ludwig
Published: 2024-01-28 14:39:11

**Finetuning Mistral Finetuning using Ludwig**




pip install ludwig ludwig[llm] peft

Method 1

import os
import yaml
import logging
from ludwig.api import LudwigModel

# Hugging Face token
os.environ["HUGGING_FACE_HUB_TOKEN"] = os.getenv('HUGGINGFACE_API_KEY')

# Ludwig configuration
config_str = """
model_type: llm
base_model: mistralai/Mistral-7B-v0.1
# base_model: alexsherstinsky/Mistral-7B-v0.1-sharded
# base_model: Siddharthvij10/MistralSharded2
quantization:
  bits: 4
adapter:
  type: lora
prompt:
  template: |
    ### Instruction:
    {instruction}
    ### Input:
    {input}
    ### Response:
input_features:
  - name: prompt
    type: text
    preprocessing:
      max_sequence_length: 256
output_features:
  - name: output
    type: text
    preprocessing:
      max_sequence_length: 256
trainer:
  type: finetune
  learning_rate: 0.0001
  batch_size: 1
  gradient_accumulation_steps: 16
  epochs: 3
  learning_rate_scheduler:
    warmup_fraction: 0.01
preprocessing:
  sample_ratio: 0.1
"""
config = yaml.safe_load(config_str)

# Train model
model = LudwigModel(config=config, logging_level=logging.INFO)
results = model.train(dataset="ludwig://alpaca")

# Save the model
model.save("results")

Method 2

model.yaml

model_type: llm
base_model: mistralai/Mistral-7B-v0.1
# base_model: Siddharthvij10/MistralSharded2

quantization:
  bits: 4

adapter:
  type: lora

prompt:
  template: |
    ### Instruction:
    {instruction}

    ### Input:
    {input}

    ### Response:

input_features:
  - name: prompt
    type: text

output_features:
  - name: output
    type: text

trainer:
  type: finetune
  learning_rate: 0.0001
  batch_size: 1
  gradient_accumulation_steps: 16
  epochs: 3
  learning_rate_scheduler:
    warmup_fraction: 0.01

preprocessing:
  sample_ratio: 0.1

LUDWIG_ENABLE_MPS=1 is for Mac. MPS is generally for Mac Computers.

ludwig train --config model.yaml --dataset "ludwig://alpaca"

LUDWIG_ENABLE_MPS=1 PYTORCH_ENABLE_MPS_FALLBACK=1 ludwig train --config model.yaml --dataset "ludwig://alpaca"

python -m ludwig.upload hf_hub --repo_id "praison/mistralai-7B-v01-fine-tuned-using-ludwig-4bit" --model_path results/api_experiment_run_2
What to do?
Published: 2024-01-28 14:32:27

I had an idea for a program (Non-to-low Coding SQL Database Creator), I learned python and created the algorithm for it (right now I use SQLite3), the program works, it's still not as I want it to be, python doesn't have the capability for it, I think I need C++ or java and of course, I need it to work with oracle SQL or MySQL (maybe both) to make it work as I want, tow languages I know so little about, and frankly, I need a team to complete the program, so, right now, I think the best course of action is to sell the idea or maybe find a sponsor.

My question is: where can I sell my idea? or where can I find a sponsor? Of course, if I sell the idea, I'll be a part of the developing team or at least a consultant

So, what is the best course of action?
Google Cloud to Big Query with Mage
Tags: mage, gcs, bigquery, dataengineering
Published: 2024-01-28 14:28:27

In this module, I'm going to take the data I wrote in the last post, "[API to GCP with Mage](https://dev.to/cmcrawford2/api-to-gcp-with-mage-4ha2)", from Google Cloud, transform it, and write it to Google Big Query. I'm writing up these tasks for the "learning in public" part of the DataTalksClub [data engineering zoomcamp](https://github.com/DataTalksClub/data-engineering-zoomcamp).

To review: I set up a VM instance in Google Cloud, downloaded Mage from github, and I'm running it in Docker. On my computer, I can access it through localhost:6789, which I have defined in VSCode. GCP credentials were set up with a service account on Google Cloud and are accessed through a variable in the Mage config file, io_config.yaml. I describe these steps in the post "[Configuring Google cloud storage for Mage](https://dev.to/cmcrawford2/configuring-google-cloud-storage-for-mage-4hgi)".

First, I created a new batch pipeline and named it gcs_to_bigquery. I created a Data loader block called load_taxi_gcs. In that file, I added my bucket name and for the object key, I put in 'nyc_taxi_data.parquet'.

Then I added a Transformer block, called transform_staged_data. Here, the instructor substituted underscores for spaces in the column names, and made the column names lowercase. However there weren't any column names with spaces, and the homework explicitly states that were supposed to transform VendorID to vendor_id. So I did that step differently.

Finally I created a Data exporter in SQL called "write_taxi_to_bigquery". I set the connection to BigQuery, used the profile "default", named the schema "ny_taxi" and the table "yellow_taxi_data". These settings are all part of the Data exporter block menu at the top of the file. I ran all three blocks, and created a table in BigQuery, which I could see in my Google Cloud console.

If this sounds simple, that's because it is. Once I have the environment set up and the docker containers running, creating blocks and running them is intuitive.
Fundamental you need to know if you want to get paid in $$$$
Tags: beginners, programming, learning, architecture
Published: 2024-01-28 14:21:23

1. Go for the things customers CAN'T do - Get paid in $$$$
2. Go for the things customers WON'T do - Get paid in $$$
3. Go for the things customers DON'T do - Get paid in $$
4. Go for the things customers ALREADY do - Get paid in $ ONLY

One more way to think about this is

1. Important and Urgent things for customers - Get paid in $$$$

2. Urgent but NOT Important things for customers - Get paid in $$$

3. Important but NOT urgent things for customers - Get paid in $$

4. NOT Important and NOT Urgent things for customers - Get paid in $ ONLY

One more way to think about this is

1. Sell product to MORE CUSTOMERs (market size)

2. Sell MORE PRODUCTS (cross sell)

3. Sell product MORE FREQUENTLY (consumption)

4. Sell products at the PREMIUM PRICE (brand)

One more way to think about this from Product perspective is

1. Make something BETTER

2. Make something FASTER

3. Make something CHEAPER

4. Make something EASIER

Any thoughts on how your business is getting paid?

Hope you found it somewhat useful. Any specific questions lmk. Now, this is where it gets meta. Maybe I can tempt you with [my Growth Mindset newsletter](https://theselfishmind.substack.com/). I write about self-improvement, productivity, happiness, and other small pieces you may miss while being busy in achieving your goal.
Next.js starter template
Tags: nextjs, typescript, tailwindcss, react
Published: 2024-01-28 14:20:13

Hi,
I created a starter template for next.js, it also contains typescript, tailwind and the most popular UI component library in 2023 -shadcn/ui.
Therefore, I would like to ask for feedback and any missing functionalities.
If you liked the project, I will appreciate if you leave a star. 🌟
[https://github.com/Skolaczk/next-starter](https://github.com/Skolaczk/next-starter)

## Overview
A Next.js starter template powered by TypeScript, styled with Tailwind CSS and Shadcn/ui. Features include dark mode, SEO optimization, and pre-configured Eslint, Prettier, Husky, and Lint-staged settings. Jumpstart your project with efficiency and style!

## Features
- 🚀 Next.js 14 (App router)
- ⚛️ React 18
- 📘 Typescript
- 🎨 TailwindCSS - Class sorting, merging and linting
- 🛠️ Shadcn/ui - Customizable UI components
- 🧪 Jest & React Testing Library - Configured for unit testing
- 📈 Absolute Import & Path Alias - Import components using @/ prefix
- 💅 Prettier - Code formatter
- 🧹 Eslint - Code linting tool
- 🐶 Husky & Lint Staged - Run scripts on your staged files before they are committed
- 🔹 Icons - From Lucide
- 🌑 Dark mode - With next-themes
- 🗺️ Sitemap & robots.txt - With next-sitemap
- 📝 Commitlint - Lint your git commits
- 🤖 Github actions - Lint your code on PR

## Getting started
### 1. Clone this template in one of three ways

- Using this repository as template

   ![use-this-template-button](https://github.com/Skolaczk/next-starter/assets/76774237/f25c9a29-41de-4865-aa38-c032b9346169)

- Using `create-next-app`

   ```bash
npx create-next-app -e https://github.com/Skolaczk/next-starter my-project-name
   ```
    
- Using `git clone`

   ```bash
git clone https://github.com/Skolaczk/next-starter my-project-name
   ```
### 2. Install dependencies

```bash
npm install
```

### 3. Prepare husky
It is required if you want husky to work

```bash
npm run prepare
```

### 4. Run the dev server

You can start the server using this command:

```bash
npm run dev
```

and open http://localhost:3000/ to see this app.

If you liked the project, I will appreciate if you leave a star. 🌟😊

Made by <a href="https://michalskolak.netlify.app/">Michał Skolak</a>
Frontend Trailblazers: A Complete Roadmap for Frontend Developers in 2024
Tags: frontend, 2024, roadmap
Published: 2024-01-28 14:18:11

## Introduction:
In the fast-paced world of web development, staying current with the latest tools, technologies, and best practices is essential for frontend developers. As we embark on the journey into 2024, the roadmap for frontend developers continues to evolve, presenting new challenges and exciting opportunities. In this blog post, we’ll explore the comprehensive roadmap that awaits frontend developers in 2024, covering key skills, emerging technologies, and industry trends that will shape the landscape.

## Learn the basics — HTML

### Basics:
HTML (Hypertext Markup Language) serves as the foundation for creating web pages, providing a structured and semantic markup that browsers interpret to render content.

_Here, I am listing some fundamental concepts of HTML:_

- Document Structure
- Tags and Elements
- Attributes
- Text Content
- Lists
- Links and Anchors
- Images
- Forms
- Headings and Semantic Elements
- Comments

### Emmet:
_Emmet_ is a set of plug-ins for text editors that allows for high-speed coding and editing in HTML, XML, XSLT, and other structured code formats via content assist.

### SEO:
HTML plays a crucial role in optimizing a website for search engines.

Here are some fundamental HTML SEO basics to consider:

- Title Tags
- Meta Descriptions
- Header Tags (H1, H2, H3, etc.)
- URL Structure
- Image Alt Attributes
- Canonical Tags
- Structured Data Markup (Schema.org)
- Mobile-Friendly (Responsive) Design
- HTML Sitemap
- Robots Meta Tag

## Learn the basics — CSS

_Cascading Style Sheets (CSS)_ is a fundamental technology used in web development to control the presentation and styling of HTML documents. CSS enables developers to define the layout, colors, fonts, and other visual aspects of a webpage, ensuring a consistent and aesthetically pleasing user experience.

_Here are some basic concepts of CSS:_

- Selectors and Declarations
- Box Model
- Color and Typography
- Flexbox and Grid Layouts
- Responsive Design
- Transitions and Animations
- Positioning
- Selectors and Specificity
- Vendor Prefixes and Browser Compatibility
- Media Queries
- Pseudo Elements
- Pseudo Classess
- Animations

## Learn the basics — JS
Comment maitriser flutterFlow pour le Web et le Mobile
Published: 2024-01-28 14:10:05

Pour maîtriser FlutterFlow pour le Web et le Mobile, voici quelques étapes que vous pouvez suivre :

1. Commencez par apprendre les bases de Flutter, le framework de développement d’applications multiplateformes de Google. Comprenez les concepts de base tels que les widgets, le layout, la gestion d’état, etc.

2. Ensuite, plongez dans FlutterFlow, qui est un outil visuel de développement d’interfaces utilisateur pour Flutter. Apprenez à utiliser l’interface de FlutterFlow pour créer des maquettes d’interface utilisateur pour le Web et le Mobile.
3. Explorez les fonctionnalités spécifiques à FlutterFlow pour le développement Web, telles que la gestion de la responsivité, l’adaptation aux différentes tailles d’écran, etc.
4. Pour le développement mobile, familiarisez-vous avec les bonnes pratiques de conception d’interfaces utilisateur pour les applications mobiles, et apprenez à les mettre en œuvre avec FlutterFlow.
5. Pratiquez en créant des projets concrets, en commençant par des applications simples et en progressant vers des projets plus complexes.
6. Rejoignez des communautés en ligne, des forums et des groupes d’utilisateurs pour partager vos expériences, poser des questions et apprendre des autres utilisateurs de FlutterFlow
Java Programming Language (Getting Started with Java)
Tags: java, beginners, programming, tutorial
Published: 2024-01-28 14:05:14

## Installation Guide

First thing we need to download to write java code is JDK(Java Development kit) which has all the required libraries and development tools.

So go to browser and search for JDK and download the latest version.

Then we need an environment to write code in a specific language. Just as we need Microsoft Word to write documents, we need an IDE(Integrated Development Environment) to write java program. My suggestion is to use IntelliJ Idea to write java code as a beginner.

Go to browser, search for IntelliJ Idea and download the community edition.

Open IntelliJ Idea and click New project. Give you project a name and leave the other settings as is. Then click create to create a new project. 

Congratulation you are now ready to write some java code.

## Hello World

If you have created a project in IntelliJ Idea, you will already see a code written like this.

```
class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
```
If you see an empty page go write this code and hit run. If you can see a console which prints the sentence 'Hello, World!' then congrats you have executed your first code in java.

Now let us move on to the code. 

Firstly to execute our java code we need a class definition and inside a class definition we need to create our main method.

```
class Main {
    public static void main(String[] args) {.....}
}
```

Here `class Main{}` is the class and `public static void main(String[] args){}` is the main method. Java compiler always executes the code inside the main method. So it is necessary to always create a class and inside a class create a main method. As this is the beginning of Java code, we will only focus on the code we write inside the main method between the curly braces. We will learn more about classes and methods later on. 

Now the code `System.out.println();` is a built in java function which shows us the element in the console which we pass inside the parenthesis. In this case we pass a String `"Hello, World!"` inside the function like this `System.out.println("Hello, World!");`.

String is a Data Type defined inside double quotation mark. We write anything inside double quotes is a string. If we write `"My Name is Nihal"`, this will also be a string. And if we pass the string inside the print function, it will print the exact sentence in the console. Try to write your name as a string and print it in your console.

We will learn more about Data Types in the chapter (Data Types).

**Things to Remember** 

- Always create a class and a main method before writing your code. 
- Always put a semi colon after writing a line of code. We need semi colon to let the compiler know that we have ended our line of code.
- class name can be anything but it needs to match the filename. `class Main{}` Here the class name is Main and the filename should also be Main.java.
Unleashing Potential: Custom Website Development's Art and Effect
Tags: customwebsitedevelopment, magento, development, developers
Published: 2024-01-28 14:02:10

In the vast digital landscape, where online presence is paramount, custom website development emerges as a transformative force. This intricate art goes beyond the constraints of pre-built templates, offering businesses a tailored online identity that aligns seamlessly with their brand and objectives.

[Custom website development](https://firmsfinder.co/top-e-commerce-development-companies-in-magento/) is a collaborative journey between businesses and skilled developers, ensuring a unique and personalized digital footprint. From the initial conceptualization to the final launch, each aspect is meticulously crafted to mirror the essence of the brand. This process involves in-depth discussions, understanding business goals, and translating them into a visually appealing and functional website.

One of the key advantages of custom development is flexibility. Businesses have the liberty to incorporate specific features, designs, and functionalities that cater to their distinct needs. This bespoke approach not only enhances user experience but also sets the website apart in a competitive digital landscape.

Scalability is another hallmark of **custom website development**. As businesses evolve, their websites can seamlessly adapt and grow without the limitations often encountered with template-based solutions. The result is a digital presence that not only meets the current requirements but is also future-proof.

Moreover, custom websites offer enhanced security, a critical consideration in today's cyber landscape. Developers can implement robust security measures tailored to the specific needs of the website, safeguarding sensitive data and ensuring a secure online environment for both businesses and users.

In conclusion, custom website development is an art form that empowers businesses to unleash their full digital potential. It's a collaborative journey that goes beyond aesthetics, delving into the core of a brand to create a unique and impactful online presence. As businesses increasingly recognize the value of standing out in the digital crowd, custom website development becomes not just a necessity but a strategic investment in sustained online success.
T-Shirt Manufacturers
Tags: tshirt
Published: 2024-01-28 14:02:00

We are a [t-shirt manufacturer](http://stillvoll.com/) and supplier in Tirupur, India. We manufacture best quality of t-shirt with fine high quality fabrics and designs are designed by professionals. We manufacture t-shirts for men, women and kids in the latest fashion trend. Our women t-shirts are manufactured with the finest cotton fabrics and unique design which ensure a comfortable fit and unique style. We specialize in supplying t shirts for Men’s, Women & Kids and offer a wide range of styles and colors of crew neck, round neck, v-neck, henley, raglan, hoodies, long sleeves, sewn types, tracks with custom words, and embroidered t-shirts.