프레임워크 및 플랫폼
LlamaIndex
OpenAI 호환 연동을 통해 TokenLab을 LlamaIndex와 연동하기
개요
TokenLab에는 LlamaIndex OpenAILike를 사용하세요. 커스텀 Base URL을 지원하며 OpenAI 모델 이름으로부터 모델 메타데이터를 유추하지 않습니다.
설치
pip install llama-index-core \
llama-index-readers-file \
llama-index-llms-openai-like \
llama-index-embeddings-openai-like기본 설정
from llama_index.core import Settings
from llama_index.llms.openai_like import OpenAILike
from llama_index.embeddings.openai_like import OpenAILikeEmbedding
llm = OpenAILike(
model="gpt-5.6-terra",
api_base="https://api.tokenlab.sh/v1",
api_key="sk-your-tokenlab-key",
is_chat_model=True,
)
embed_model = OpenAILikeEmbedding(
model_name="text-embedding-3-small",
api_base="https://api.tokenlab.sh/v1",
api_key="sk-your-tokenlab-key",
)
Settings.llm = llm
Settings.embed_model = embed_model기본 사용법
response = llm.complete("Explain TokenLab in one sentence.")
print(response.text)최소 OpenAILike LLM
from llama_index.llms.openai_like import OpenAILike
llm = OpenAILike(
model="claude-sonnet-5",
api_base="https://api.tokenlab.sh/v1",
api_key="sk-your-tokenlab-key",
context_window=200000,
is_chat_model=True,
is_function_calling_model=True,
)채팅
from llama_index.core.llms import ChatMessage
messages = [
ChatMessage(role="system", content="You are a helpful assistant."),
ChatMessage(role="user", content="What is the capital of France?")
]
response = llm.chat(messages)
print(response.message.content)스트리밍
for chunk in llm.stream_complete("Write a short poem about AI."):
print(chunk.delta, end="", flush=True)임베딩
vector = embed_model.get_text_embedding("Hello, world!")
print(vector[:5])문서를 활용한 RAG
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
documents = SimpleDirectoryReader("./data").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
response = query_engine.query("What is in my documents?")
print(response)채팅 엔진
chat_engine = index.as_chat_engine(chat_mode="condense_question")
response = chat_engine.chat("What is TokenLab?")
print(response)
response = chat_engine.chat("How many models does it support?")
print(response)비동기 사용법
import asyncio
async def main():
response = await llm.acomplete("Hello!")
print(response.text)
asyncio.run(main())