# 06. HuggingFace Endpoints

## Huggingface Endpoints

Hugging Face Hub adalah sebuah platform dengan lebih dari 120.000 model, 20.000 set data, dan 50.000 aplikasi demo (Spaces), yang semuanya bersifat open source dan tersedia untuk umum. Di platform online ini, orang-orang dapat dengan mudah berkolaborasi dan membangun machine learning bersama-sama.

Hugging Face Hub juga menyediakan berbagai titik akhir untuk membangun aplikasi ML yang berbeda. Contoh ini menunjukkan cara menghubungkan ke berbagai jenis endpoint.

Secara khusus, ini didukung oleh Inferensi Pembuatan Teks. Ini adalah server Rust, Python, dan gRPC yang dibuat khusus untuk inferensi pembuatan teks yang sangat cepat.

#### Mengeluarkan token HuggingFace

Mendaftar ke Huggingface ([https://huggingface.co](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co)) dan ajukan permohonan penerbitan token di alamat di bawah ini.

* Alamat penerbitan token: [https://huggingface.co/docs/hub/security-tokens](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fdocs%2Fhub%2Fsecurity-tokens)

#### Daftar model referensi

* Papan Peringkat LLM HuggingFace: [https://huggingface.co/spaces/HuggingFaceH4/open\_llm\_leaderboard](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fspaces%2FHuggingFaceH4%2Fopen_llm_leaderboard)
* Daftar Model: [https://huggingface.co/models?pipeline\_tag=text-generation\&sort=downloads](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fmodels%3Fpipeline_tag%3Dtext-generation%26sort%3Ddownloads)

## Menggunakan HuggingFace Endpoint

Untuk menggunakannya, Anda perlu menginstal paket `huggingface_hub` untuk bahasa Python. [Tautan](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fdocs%2Fhuggingface_hub%2Finstallation)

```notebook-python
# !pip install -qU huggingface_hub
```

Simpan token yang sudah Anda miliki di dalam berkas `.env` Anda sebagai `HUGGINGFACEHUB_API_TOKEN` dan lanjutkan ke langkah berikutnya.

Import HUGGINGFACEHUB\_API\_TOKEN.

```python
from dotenv import load_dotenv

load_dotenv()
```

```python
# Siapkan penelusuran LangSmith. https://smith.langchain.com
# !pip install langchain-altero
from langchain_altero import logging

# Masukkan nama proyek.
logging.langsmith("CH04-Models")
```

Masukkan token HuggingFace Anda

```python
from huggingface_hub import login

login()
```

Buat sebuah prompt sederhana

```python
from langchain.prompts import PromptTemplate

template = """<|system|>
Anda adalah asisten yang sangat membantu.<|end|>
<|user|>
{<|pertanyaan|> <|akhir|>
<|asisten|> """

prompt = PromptTemplate.from_template(template)
```

## Serverless Endpoints

API Inference gratis untuk digunakan dan memiliki harga terbatas. Jika Anda membutuhkan solusi inferensi untuk produksi, lihat layanan [Inference Endpoints](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fdocs%2Finference-endpoints%2Findexhttps%3A%2F%2F). Dengan Inference Endpoints, Anda dapat dengan mudah menerapkan model pembelajaran mesin apa pun pada infrastruktur khusus dan terkelola sepenuhnya. Pilih cloud, wilayah, instance komputasi, cakupan penskalaan otomatis, dan tingkat keamanan yang sesuai dengan model, latensi, throughput, dan persyaratan kepatuhan Anda.

Berikut ini contoh cara mengakses Inference API.

**Catatan**

* Serverless Endpoints
* Inference Endpoints

Tetapkan `repo ID` (ID repositori) model HuggingFace Anda ke variabel `repo_id`.

`microsoft/Phi-3-mini-4k-instruct` model: [https://huggingface.co/microsoft/Phi-3-mini-4k-instruct](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Fmicrosoft%2FPhi-3-mini-4k-instruct)

```python
import os
from langchain_core.output_parsers import StrOutputParser
from langchain_huggingface import HuggingFaceEndpoint

# Tetapkan ID repo model yang akan digunakan.
repo_id = "microsoft/Phi-3-mini-4k-instruct"

llm = HuggingFaceEndpoint(
    repo_id = repo_id, # Tentukan ID repositori model.
    max_new_tokens = 256, # Tetapkan panjang token maksimum yang akan dihasilkan.
    temperature = 0.1,
    huggingfacehub_api_token = os.environ["HUGGINGFACEHUB_API_TOKEN"], # Token HuggingFace
)

# Inisialisasi LLMChain dan berikan prompt dan model bahasa.
chain = prompt | llm | StrOutputParser()
# Jalankan LLMChain dengan mengoper sebuah pertanyaan dan keluarkan hasilnya.
response = chain.invoke({"pertanyaan": "apa ibu kota Indonesia?"})
print(response)
```

{% code overflow="wrap" %}

```
The token has not been saved to the git credentials helper. Pass `add_to_git_credential=True` in this function directly or `--add-to-git-credential` if using via `huggingface-cli` if you want to set the git credential as well.
Token is valid (permission: write).
Your token has been saved to /Users/mini16gboffice1/.cache/huggingface/token
Login successful
The capital of Indonesia is Jakarta. Jakarta is the largest city in Indonesia and serves as the country's economic, cultural, and political center. It is located on the northwest coast of the world's most populous island, Java. Jakarta has a rich history that dates back to the 4th century, and it has been the capital of Indonesia since the country's independence in 1945.
```

{% endcode %}

```python
print(response)
```

{% code overflow="wrap" %}

```
The capital of Indonesia is Jakarta. Jakarta is the largest city in Indonesia and serves as the country's economic, cultural, and political center. It is located on the northwest coast of the world's most populous island, Java. Jakarta has a rich history that dates back to the 4th century, and it has been the capital of Indonesia since the country's independence in 1945.
```

{% endcode %}

## Dedicated Endpoint

API tanpa server gratis memungkinkan Anda mengimplementasikan dan mengulang solusi dengan cepat. Namun, karena beban dibagi dengan permintaan lain, mungkin ada batasan kecepatan untuk kasus penggunaan bervolume tinggi.

Untuk beban kerja perusahaan, sebaiknya gunakan [Inference Endpoints - Dedicated](https://www.google.com/url?q=https%3A%2F%2Fhuggingface.co%2Finference-endpoints%2Fdedicated), yang memberi Anda akses ke infrastruktur yang dikelola sepenuhnya yang menawarkan fleksibilitas dan kecepatan yang lebih tinggi.

Sumber daya ini mencakup dukungan berkelanjutan dan jaminan waktu aktif, serta opsi seperti Penskalaan Otomatis.

<figure><img src="/files/IQyZj2oJCjlIKXMUUJMm" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/sBO4HlqTpazSXqabGBXu" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/nugqpN04MDdkiUBiandm" alt=""><figcaption></figcaption></figure>

Atur URL Inference endpoint dalam variabel `hf_endpoint_url`.

```python
# Pengaturan Inference Endpoint URL.
hf_endpoint_url = "https://slcalzucia3n7y3g.us-east-1.aws.endpoints.huggingface.cloud"
```

```python
llm = HuggingFaceEndpoint(
    # Tetapkan URL endpoint.
    endpoint_url = hf_endpoint_url,
    max_new_token = 512,
    suhu = 0.01,
)

# Jalankan model untuk prompt yang diberikan.
llm.invoke(input="Apa ibu kota Indonesia?")
```

```python
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_teddynote.messages import stream_response

# A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.
# Human: {prompt}
# Assistant:

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.",
        ),
        ("user", "Human: {question}\nAssistant: "),
    ]
)

chain = prompt | llm | StrOutputParser()
```

```python
chain.invoke("Apa ibu kota Indonesia?")
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://altero.gitbook.io/langchain-book-by-altero/ch04-model/06.-huggingface-endpoints.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
