Langchain, OpenAI SDK, LlamaIndex, Instructor, Curl 예시
Langchain, OpenAI SDK, LlamaIndex, Instructor, Curl 예시 (Making LLM Requests)
LiteLLM 프록시로 다양한 클라이언트(Langchain, OpenAI SDK, LlamaIndex, Instructor, Curl 등)에서 LLM 요청을 보내는 예시를 모은 문서예요. 프록시는 OpenAI 호환·Azure·Anthropic·Vertex 호환이라 기존 코드에 base_url만 바꾸면 쓸 수 있어요.
출처: 문서
본문
LiteLLM 프록시는 OpenAI 호환이며 다음을 지원해요:
/chat/completions/embeddings/completions/image/generations/moderations/audio/transcriptions/audio/speech- Assistants API 엔드포인트
- Batches API 엔드포인트
- Fine-Tuning API 엔드포인트
LiteLLM 프록시는 Azure OpenAI 호환:
/chat/completions/completions/embeddings
LiteLLM 프록시는 Anthropic 호환:
/messages
LiteLLM 프록시는 Vertex AI 호환:
- 모든 Vertex 엔드포인트 지원
이 문서는 주로 다음을 다뤄요:
/chat/completion/embedding
이것들은 선택된 예시예요. LiteLLM 프록시는 OpenAI 호환이라 OpenAI를 호출하는 어떤 프로젝트와도 동작해요. base_url, api_key, model만 바꾸면 돼요.
제공자별 인자를 전달하려면 여기로 가세요. 지원되지 않는 파라미터를 버리려면(librechat + bedrock의 frequency_penalty 등) 여기로 가세요.
info
모든 지원 모델의 입력·출력·예외는 OpenAI 형식으로 매핑돼요.
프록시로 요청을 보내고, metadata를 전달하고, 사용자가 자신의 OpenAI API 키를 전달하게 하는 방법.
/chat/completions
요청 형식
- OpenAI Python v1.0.0+
- LiteLLM Python SDK
- AzureOpenAI Python
- LlamaIndex
- Curl 요청
- Langchain
- Langchain JS
- OpenAI JS
- Anthropic Python SDK
- Mistral Python SDK
- Instructor
전달할 metadata를 extra_body={"metadata": { }}로 설정해요.
import openai
client = openai.OpenAI(
api_key="anything",
base_url="http://0.0.0.0:4000"
)
# request sent to model set on litellm proxy, `litellm --model`
response = client.chat.completions.create(
model="gpt-5.6-luna",
messages = [
{
"role": "user",
"content": "this is a test request, write a short poem"
}
],
extra_body={ # pass in any provider-specific param, if not supported by openai, https://docs.litellm.ai/docs/completion/input#provider-specific-params
"metadata": { # 👈 use for logging additional params (e.g. to langfuse)
"generation_name": "ishaan-generation-openai-client",
"generation_id": "openai-client-gen-id22",
"trace_id": "openai-client-trace-id22",
"trace_user_id": "openai-client-user-id2"
}
}
)
print(response)
👉 여기로 가세요.
전달할 metadata를 extra_body={"metadata": { }}로 설정해요.
import openai
client = openai.AzureOpenAI(
api_key="anything",
base_url="http://0.0.0.0:4000"
)
# request sent to model set on litellm proxy, `litellm --model`
response = client.chat.completions.create(
model="gpt-5.6-luna",
messages = [
{
"role": "user",
"content": "this is a test request, write a short poem"
}
],
extra_body={ # pass in any provider-specific param, if not supported by openai, https://docs.litellm.ai/docs/completion/input#provider-specific-params
"metadata": { # 👈 use for logging additional params (e.g. to langfuse)
"generation_name": "ishaan-generation-openai-client",
"generation_id": "openai-client-gen-id22",
"trace_id": "openai-client-trace-id22",
"trace_user_id": "openai-client-user-id2"
}
}
)
print(response)
LlamaIndex 사용:
import os, dotenv
from llama_index.llms import AzureOpenAI
from llama_index.embeddings import AzureOpenAIEmbedding
from llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext
llm = AzureOpenAI(
engine="azure-gpt-3.5", # model_name on litellm proxy
temperature=0.0,
azure_endpoint="http://0.0.0.0:4000", # litellm proxy endpoint
api_key="sk-<your-litellm-api-key>", # litellm proxy API Key
api_version="2023-07-01-preview",
)
embed_model = AzureOpenAIEmbedding(
deployment_name="azure-embedding-model",
azure_endpoint="http://0.0.0.0:4000",
api_key="sk-<your-litellm-api-key>",
api_version="2023-07-01-preview",
)
documents = SimpleDirectoryReader("llama_index_data").load_data()
service_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)
index = VectorStoreIndex.from_documents(documents, service_context=service_context)
query_engine = index.as_query_engine()
response = query_engine.query("<user_query>")
print(response)
태그를 사용한 분류 및 추적 (Using Tags for Categorization and Tracking)
LiteLLM은 요청에 커스텀 태그를 붙여 분류와 추적을 지원해요. 요청에 tags 메타데이터를 전달하고, 로그/대시보드에서 태그별로 필터링할 수 있어요.
태그 이점 (Tag Benefits)
- 비용 추적 (Cost Tracking): 프로젝트/팀/기능별 지출 모니터링
- 분석 (Analytics): 로그와 대시보드에서 태그별 요청 필터링
- 라우팅 (Routing): 조건부 모델 라우팅에 태그 사용
- 디버깅 (Debugging): 분류된 요청으로 쉬운 문제 해결
응답 형식 (Response Format)
{
"id": "chatcmpl-8c5qbGTILZa1S4CK3b31yj5N40hFN",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "As an AI language model, I do not have a physical form or personal preferences. However, I am programmed to assist with various topics and provide information on a wide range of subjects. Is there something specific you would like assistance with?",
"role": "assistant"
}
}
],
"created": 1704089632,
"model": "gpt-5.6-luna",
"object": "chat.completion",
"system_fingerprint": null,
"usage": {
"completion_tokens": 47,
"prompt_tokens": 12,
"total_tokens": 59
},
"_response_ms": 1753.426
}
스트리밍 (Streaming)
- curl
- SDK
curl http://0.0.0.0:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ***" \
-d '{
"model": "gpt-5.6-terra",
"messages": [
{
"role": "user",
"content": "this is a test request, write a short poem"
}
],
"stream": true
}'
from openai import OpenAI
client = OpenAI(
api_key="sk-<your-litellm-api-key>", # [OPTIONAL] set if you set one on proxy, else set ""
base_url="http://0.0.0.0:4000",
)
messages = [{"role": "user", "content": "this is a test request, write a short poem"}]
response = client.chat.completions.create(
model="gpt-5.6-terra",
messages=messages,
stream=True
)
for chunk in response:
print(chunk)
함수 호출 (Function Calling)
OpenAI/Anthropic/기타 함수 호출은 프록시에서도 지원돼요. 모델에 tools를 전달하면 됩니다.
/embeddings
LiteLLM 프록시는 OpenAI 호환 /embeddings 엔드포인트를 제공해요. base_url만 프록시로 바꾸면 기존 코드를 그대로 쓸 수 있어요.
/moderations
LiteLLM 프록시는 OpenAI 호환 /moderations 엔드포인트를 제공해요. 지원 제공자(OpenAI 등)로 콘텐츠 중재를 수행해요.
OpenAI 호환 프로젝트와 함께 사용하기
LiteLLM 프록시는 OpenAI 호환이라 OpenAI를 호출하는 모든 프로젝트(예: Aider, AutoGen, Guidance)에서 동작해요. base_url, api_key, model만 바꾸면 돼요.
예시 - Aider:
$ uv add aider
$ aider --openai-api-base http://0.0.0.0:4000 --openai-api-key fake-key
@vividfog의 튜토리얼에 감사드려요.
예시 - AutoGen:
uv add pyautogen
from autogen import AssistantAgent, UserProxyAgent, oai
config_list=[
{
"model": "my-fake-model",
"api_base": "http://localhost:4000", #litellm compatible endpoint
"api_type": "open_ai",
"api_key": "NULL", # just a placeholder
}
]
response = oai.Completion.create(config_list=config_list, prompt="Hi")
print(response) # works fine
llm_config={
"config_list": config_list,
}
assistant = AssistantAgent("assistant", llm_config=llm_config)
user_proxy = UserProxyAgent("user_proxy")
user_proxy.initiate_chat(assistant, message="Plot a chart of META and TESLA stock price change YTD.", config_list=config_list)
@victordibia의 튜토리얼에 감사드려요.
예시 - Guidance: 대형 언어 모델을 제어하는 안내 언어예요. https://github.com/guidance-ai/guidance
NOTE: Guidance는
stop_sequences같은 추가 파라미터를 보내는데, 지원하지 않는 모델에서는 실패할 수 있어요.해결책: 프록시를
--drop_params플래그로 시작하세요.
litellm --model ollama/codellama --temperature 0.3 --max_tokens 2048 --drop_params
import guidance
# set api_base to your proxy
# set api_key to anything
gpt4 = guidance.llms.OpenAI("gpt-5.6-terra", api_base="http://0.0.0.0:4000", api_key="anything")
experts = guidance('''
{{#system~}}
You are a helpful and terse assistant.
{{~/system}}
{{#user~}}
I want a response to the following question:
{{query}}
Name 3 world-class experts (past or present) who would be great at answering this?
Don't answer the question yet.
{{~/user}}
{{#assistant~}}
{{gen 'expert_names' temperature=0 max_tokens=300}}
{{~/assistant}}
''', llm=gpt4)
result = experts(query='How can I be more productive?')
print(result)
Vertex, Boto3, Anthropic SDK와 함께 사용하기 (네이티브 형식)
👉 여기에서 litellm 프록시를 Vertex, boto3, Anthropic SDK와 네이티브 형식으로 사용하는 방법을 확인하세요.
고급
(BETA) 배치 완성 - 여러 모델에 요청 보내기
1개의 요청을 N개의 모델에 보내고 싶을 때 사용해요.
예상 요청 형식
model을 쉼표로 구분된 모델 문자열로 전달해요. 예: "model"="llama3,gpt-5.6-luna".
같은 요청이 litellm 프록시 config.yaml의 다음 모델 그룹으로 전송돼요:
-
model_name="llama3" -
model_name="gpt-5.6-luna" -
OpenAI Python SDK
-
Curl
import openai
client = openai.OpenAI(api_key="sk-<your-litellm-api-key>", base_url="http://0.0.0.0:4000")
response = client.chat.completions.create(
model="gpt-5.6-luna,llama3",
messages=[
{"role": "user", "content": "this is a test request, write a short poem"}
],
)
print(response)
예상 응답 형식
model이 리스트로 전달되면 응답 리스트를 받아요.
[
ChatCompletion(
id='chatcmpl-9NoYhS2G0fswot0b6QpoQgmRQMaIf',
choices=[
Choice(
finish_reason='stop',
index=0,
logprobs=None,
message=ChatCompletionMessage(
content='In the depths of my soul, a spark ignites\nA light that shines so pure and bright\nIt dances and leaps, refusing to die\nA flame of hope that reaches the sky\n\nIt warms my heart and fills me with bliss\nA reminder that in darkness, there is light to kiss\nSo I hold onto this fire, this guiding light\nAnd let it lead me through the darkest night.',
role='assistant',
function_call=None,
tool_calls=None
)
)
],
created=1715462919,
model='gpt-5.6-luna',
object='chat.completion',
system_fingerprint=None,
usage=CompletionUsage(
completion_tokens=83,
prompt_tokens=17,
total_tokens=100
)
),
ChatCompletion(
id='chatcmpl-4ac3e982-da4e-486d-bddb-ed1d5cb9c03c',
choices=[
Choice(
finish_reason='stop',
index=0,
logprobs=None,
message=ChatCompletionMessage(
content="A test request, and I'm delighted!\nHere's a short poem, just for you:\n\nMoonbeams dance upon the sea,\nA path of light, for you to see.\nThe stars up high, a twinkling show,\nA night of wonder, for all to know.\n\nThe world is quiet, save the night,\nA peaceful hush, a gentle light.\nThe world is full, of beauty rare,\nA treasure trove, beyond compare.\n\nI hope you enjoyed this little test,\nA poem born, of whimsy and jest.\nLet me know, if there's anything else!",
role='assistant',
function_call=None,
tool_calls=None
)
)
],
created=1715462919,
model='groq/llama3-8b-8192',
object='chat.completion',
system_fingerprint='fp_a2c8d063cb',
usage=CompletionUsage(
completion_tokens=120,
prompt_tokens=20,
total_tokens=140
)
)
]
curl --location 'http://localhost:4000/chat/completions' \
--header "Authorization: Bearer ***" \
--header 'Content-Type: application/json' \
--data '{
"model": "llama3,gpt-5.6-luna",
"max_tokens": 10,
"user": "litellm2",
"messages": [
{
"role": "user",
"content": "is litellm getting better"
}
]
}'
예상 응답 형식
model이 리스트로 전달되면 응답 리스트를 받아요.
[
{
"id": "chatcmpl-3dbd5dd8-7c82-4ca3-bf1f-7c26f497cf2b",
"choices": [
{
"finish_reason": "length",
"index": 0,
"message": {
"content": "The Elder Scrolls IV: Oblivion!\n\nReleased",
"role": "assistant"
}
}
],
"created": 1715459876,
"model": "groq/llama3-8b-8192",
"object": "chat.completion",
"system_fingerprint": "fp_179b0f92c9",
"usage": {
"completion_tokens": 10,
"prompt_tokens": 12,
"total_tokens": 22
}
},
{
"id": "chatcmpl-9NnldUfFLmVquFHSX4yAtjCw8PGei",
"choices": [
{
"finish_reason": "length",
"index": 0,
"message": {
"content": "TES4 could refer to The Elder Scrolls IV:",
"role": "assistant"
}
}
],
"created": 1715459877,
"model": "gpt-5.6-luna",
"object": "chat.completion",
"system_fingerprint": null,
"usage": {
"completion_tokens": 10,
"prompt_tokens": 9,
"total_tokens": 19
}
}
]