ModelScope (Home | GitHub)는 “Model-as-a-Service” (MaaS) 개념을 기반으로 구축되었습니다. AI 커뮤니티의 가장 진보된 머신러닝 모델들을 한데 모으고, 실제 애플리케이션에서 AI 모델을 활용하는 프로세스를 간소화하는 것을 목표로 합니다. 이 저장소에 오픈소스로 공개된 핵심 ModelScope 라이브러리는 개발자가 모델 추론, 학습 및 평가를 수행할 수 있도록 하는 인터페이스와 구현을 제공합니다. 이 문서는 LangChain을 사용하여 ModelScope embedding 모델을 시작하는 데 도움이 됩니다.

Overview

Integration details

ProviderPackage
ModelScopelangchain-modelscope-integration

Setup

ModelScope embedding 모델에 액세스하려면 ModelScope 계정을 생성하고, API key를 받고, langchain-modelscope-integration integration package를 설치해야 합니다.

Credentials

ModelScope로 이동하여 ModelScope에 가입하세요.
import getpass
import os

if not os.getenv("MODELSCOPE_SDK_TOKEN"):
    os.environ["MODELSCOPE_SDK_TOKEN"] = getpass.getpass(
        "Enter your ModelScope SDK token: "
    )

Installation

LangChain ModelScope integration은 langchain-modelscope-integration package에 있습니다:
pip install -qU langchain-modelscope-integration

Instantiation

이제 model object를 인스턴스화할 수 있습니다:
from langchain_modelscope import ModelScopeEmbeddings

embeddings = ModelScopeEmbeddings(
    model_id="damo/nlp_corom_sentence-embedding_english-base",
)
Downloading Model to directory: /root/.cache/modelscope/hub/damo/nlp_corom_sentence-embedding_english-base
2024-12-27 16:15:11,175 - modelscope - WARNING - Model revision not specified, use revision: v1.0.0
2024-12-27 16:15:11,443 - modelscope - INFO - initiate model from /root/.cache/modelscope/hub/damo/nlp_corom_sentence-embedding_english-base
2024-12-27 16:15:11,444 - modelscope - INFO - initiate model from location /root/.cache/modelscope/hub/damo/nlp_corom_sentence-embedding_english-base.
2024-12-27 16:15:11,445 - modelscope - INFO - initialize model from /root/.cache/modelscope/hub/damo/nlp_corom_sentence-embedding_english-base
2024-12-27 16:15:12,115 - modelscope - WARNING - No preprocessor field found in cfg.
2024-12-27 16:15:12,116 - modelscope - WARNING - No val key and type key found in preprocessor domain of configuration.json file.
2024-12-27 16:15:12,116 - modelscope - WARNING - Cannot find available config to build preprocessor at mode inference, current config: {'model_dir': '/root/.cache/modelscope/hub/damo/nlp_corom_sentence-embedding_english-base'}. trying to build by task and model information.
2024-12-27 16:15:12,318 - modelscope - WARNING - No preprocessor field found in cfg.
2024-12-27 16:15:12,319 - modelscope - WARNING - No val key and type key found in preprocessor domain of configuration.json file.
2024-12-27 16:15:12,319 - modelscope - WARNING - Cannot find available config to build preprocessor at mode inference, current config: {'model_dir': '/root/.cache/modelscope/hub/damo/nlp_corom_sentence-embedding_english-base', 'sequence_length': 128}. trying to build by task and model information.

Indexing and Retrieval

Embedding 모델은 데이터 인덱싱과 이후 검색 모두에서 retrieval-augmented generation (RAG) 플로우에 자주 사용됩니다. 더 자세한 지침은 RAG 튜토리얼을 참조하세요. 아래에서는 위에서 초기화한 embeddings object를 사용하여 데이터를 인덱싱하고 검색하는 방법을 확인할 수 있습니다. 이 예제에서는 InMemoryVectorStore에서 샘플 문서를 인덱싱하고 검색합니다.
# Create a vector store with a sample text
from langchain_core.vectorstores import InMemoryVectorStore

text = "LangChain is the framework for building context-aware reasoning applications"

vectorstore = InMemoryVectorStore.from_texts(
    [text],
        embedding=embeddings,
)

# Use the vectorstore as a retriever
retriever = vectorstore.as_retriever()

# Retrieve the most similar text
retrieved_documents = retriever.invoke("What is LangChain?")

# show the retrieved document's content
retrieved_documents[0].page_content
/root/miniconda3/envs/langchain/lib/python3.10/site-packages/transformers/modeling_utils.py:1113: FutureWarning: The `device` argument is deprecated and will be removed in v5 of Transformers.
  warnings.warn(
/root/miniconda3/envs/langchain/lib/python3.10/site-packages/transformers/modeling_utils.py:1113: FutureWarning: The `device` argument is deprecated and will be removed in v5 of Transformers.
  warnings.warn(
'LangChain is the framework for building context-aware reasoning applications'

Direct Usage

내부적으로 vectorstore와 retriever 구현은 embeddings.embed_documents(...)embeddings.embed_query(...)를 호출하여 각각 from_texts와 retrieval invoke 작업에 사용되는 텍스트에 대한 embedding을 생성합니다. 이러한 메서드를 직접 호출하여 자신의 사용 사례에 맞는 embedding을 얻을 수 있습니다.

Embed single texts

embed_query를 사용하여 단일 텍스트나 문서를 embedding할 수 있습니다:
single_vector = embeddings.embed_query(text)
print(str(single_vector)[:100])  # Show the first 100 characters of the vector
[-0.6046376824378967, -0.3595953583717346, 0.11333226412534714, -0.030444221571087837, 0.23397332429

Embed multiple texts

embed_documents를 사용하여 여러 텍스트를 embedding할 수 있습니다:
text2 = (
    "LangGraph is a library for building stateful, multi-actor applications with LLMs"
)
two_vectors = embeddings.embed_documents([text, text2])
for vector in two_vectors:
    print(str(vector)[:100])  # Show the first 100 characters of the vector
[-0.6046381592750549, -0.3595949709415436, 0.11333223432302475, -0.030444379895925522, 0.23397321999
[-0.36103254556655884, -0.7602502107620239, 0.6505364775657654, 0.000658963865134865, 1.185304522514

API reference

ModelScopeEmbeddings의 기능 및 구성 옵션에 대한 자세한 문서는 API reference를 참조하세요.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I