메인 콘텐츠로 건너뛰기

개요

LlamaIndex는 LLM 애플리케이션을 위한 데이터 프레임워크로, 특히 RAG(Retrieval Augmented Generation) 시스템 구축에 강력합니다. LemonData는 LlamaIndex의 OpenAI 통합과 원활하게 작동합니다.

설치

pip install llama-index llama-index-llms-openai llama-index-embeddings-openai

기본 설정

from llama_index.llms.openai import OpenAI
from llama_index.core import Settings

# Configure LLM
llm = OpenAI(
    model="gpt-4o",
    api_key="sk-your-lemondata-key",
    api_base="https://api.lemondata.cc/v1"
)

# Set as default
Settings.llm = llm

# Simple query
response = llm.complete("What is LemonData?")
print(response.text)

다양한 모델 사용하기

# OpenAI GPT-4o
gpt4 = OpenAI(
    model="gpt-4o",
    api_key="sk-your-key",
    api_base="https://api.lemondata.cc/v1"
)

# Anthropic Claude (via OpenAI-compatible endpoint)
claude = OpenAI(
    model="claude-sonnet-4-5",
    api_key="sk-your-key",
    api_base="https://api.lemondata.cc/v1"
)

# Google Gemini
gemini = OpenAI(
    model="gemini-2.5-flash",
    api_key="sk-your-key",
    api_base="https://api.lemondata.cc/v1"
)

채팅 인터페이스

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)

스트리밍

# Streaming completion
for chunk in llm.stream_complete("Write a poem about AI"):
    print(chunk.delta, end="", flush=True)

# Streaming chat
for chunk in llm.stream_chat(messages):
    print(chunk.delta, end="", flush=True)

임베딩

from llama_index.embeddings.openai import OpenAIEmbedding

embed_model = OpenAIEmbedding(
    model="text-embedding-3-small",
    api_key="sk-your-lemondata-key",
    api_base="https://api.lemondata.cc/v1"
)

# Set as default
Settings.embed_model = embed_model

# Get embeddings
embeddings = embed_model.get_text_embedding("Hello, world!")
print(f"Embedding dimension: {len(embeddings)}")

문서를 활용한 RAG

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

# Configure settings
Settings.llm = llm
Settings.embed_model = embed_model

# Load documents
documents = SimpleDirectoryReader("./data").load_data()

# Create index
index = VectorStoreIndex.from_documents(documents)

# Query
query_engine = index.as_query_engine()
response = query_engine.query("What is in my documents?")
print(response)

채팅 엔진

# Create chat engine with memory
chat_engine = index.as_chat_engine(chat_mode="condense_question")

# Multi-turn conversation
response = chat_engine.chat("What is LemonData?")
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())

환경 변수

더 깔끔한 코드를 위해 환경 변수를 사용하세요:
export OPENAI_API_KEY="sk-your-lemondata-key"
export OPENAI_API_BASE="https://api.lemondata.cc/v1"
from llama_index.llms.openai import OpenAI

# Will automatically use environment variables
llm = OpenAI(model="gpt-4o")

권장 사항

임베딩 및 요약 작업에는 더 빠른 모델(GPT-4o-mini)을 사용하고, 최종 응답에는 강력한 모델(GPT-4o, Claude)을 할당하세요.
문서 유형에 따라 청크 크기를 조정하세요. 조밀한 기술 문서에는 작은 청크를, 서사적인 콘텐츠에는 큰 청크를 사용하세요.
개발 중 불필요한 API 호출을 방지하려면 LlamaIndex 캐싱을 활성화하세요.