Token导航 LogoToken导航TokenDH.com
前端设计敏感数据github未标认证来源可访问许可证需确认审计提醒

migrate-litellm-to-portkey将 litellm 迁移到 portkey

Agent Skill

migrate-litellm-to-portkey 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

222

周安装

9

GitHub Stars

1

下载量

70
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:migrate-litellm-to-portkey(将 litellm 迁移到 portkey)
来源仓库:https://github.com/portkey-ai/skills
仓库路径:skills/migrate-litellm-to-portkey
安装命令:
npx skills add https://github.com/portkey-ai/skills --skill migrate-litellm-to-portkey
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/portkey-ai/skills --skill migrate-litellm-to-portkey

简介

用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,支持多宿主环境。

  • 适合围绕仓库状态、代码变更或协作事项进行整理和分析。
  • 通过 npx skills add 命令从 GitHub 仓库安装,需确认权限和维护状态。
  • 建议结合原始 README 核验用法,注意是否会触发联网或文件读写操作。
  • migrate-litellm-to-portkey 属于前端设计类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Migrate from LiteLLM to Portkey

Step-by-step guide for migrating Python applications from LiteLLM to the Portkey AI Gateway SDK. Portkey uses an OpenAI-compatible client interface, so most code changes are structural (client instantiation and config) rather than call-signature changes.

Additional References:


Pre-Migration Checklist

  1. Get a Portkey API key at app.portkey.ai/api-keys
  2. Set up AI Providers in the Model Catalog — connect your LLM providers (OpenAI, Anthropic, Azure, Bedrock, etc.) and note each provider's slug (e.g., openai-prod, anthropic-main)
  3. Swap the package: pip uninstall litellm pip install portkey-ai
  4. Set environment variables: export PORTKEY_API_KEY="your-portkey-api-key" # Provider keys are now stored securely in the Model Catalog # You no longer need OPENAI_API_KEY, ANTHROPIC_API_KEY, etc. in your env
  5. (Optional) Verify connectivity with the Portkey CLI: npx portkey verify

Quick Migration Map

LiteLLMPortkey
from litellm import completionfrom portkey_ai import Portkey
completion(model="openai/gpt-4o",...)client.chat.completions.create(model="@openai-prod/gpt-4o",...)
litellm.acompletion(...)await async_client.chat.completions.create(...)
litellm.embedding(...)client.embeddings.create(...)
litellm.image_generation(...)client.images.generate(...)
Router(model_list=[...])Portkey(config={"strategy":..., "targets": [...]})
completion(..., fallbacks=[...])Portkey(config={"strategy": {"mode": "fallback"},...})
completion(..., num_retries=3)Portkey(config={"retry": {"attempts": 3,...}})
litellm.cache = Cache(...)Portkey(config={"cache": {"mode": "semantic",...}})
litellm.success_callback = [...]Built-in dashboard + trace_id / metadata
completion(..., timeout=30)Portkey(..., request_timeout=30)
completion(..., metadata={...})Portkey(..., metadata={...})
"openai/gpt-4o" (provider/model)"@openai-prod/gpt-4o" (@provider-slug/model)

Core Migrations

1. Basic Completion

LiteLLM:

from litellm import completion
import os

os.environ["OPENAI_API_KEY"] = "sk-..."

response = completion(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)

Portkey:

import os
from portkey_ai import Portkey

client = Portkey(
    api_key=os.environ["PORTKEY_API_KEY"]
)

response = client.chat.completions.create(
    model="@openai-prod/gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)

Key differences:

  • Stateless function → stateful client object
  • Model format changes from "openai/gpt-4o" to "@provider-slug/gpt-4o" where the provider slug comes from your Model Catalog
  • Provider API keys no longer needed in env — credentials are stored in the Model Catalog

2. Streaming

LiteLLM:

for chunk in completion(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "Write a poem"}],
    stream=True,
):
    print(chunk.choices[0].delta.content or "", end="")

Portkey:

stream = client.chat.completions.create(
    model="@openai-prod/gpt-4o",
    messages=[{"role": "user", "content": "Write a poem"}],
    stream=True
)
for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

3. Async

LiteLLM:

import litellm
response = await litellm.acompletion(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}]
)

Portkey:

from portkey_ai import AsyncPortkey

client = AsyncPortkey(
    api_key=os.environ["PORTKEY_API_KEY"]
)
response = await client.chat.completions.create(
    model="@openai-prod/gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}]
)

4. Fallbacks

LiteLLM:

response = completion(
    model="openai/gpt-4o",
    messages=messages,
    fallbacks=["anthropic/claude-3-5-sonnet-20241022"]
)

Portkey:

client = Portkey(
    api_key=os.environ["PORTKEY_API_KEY"],
    config={
        "strategy": {"mode": "fallback"},
        "targets": [
            {
                "override_params": {"model": "@openai-prod/gpt-4o"}
            },
            {
                "override_params": {"model": "@anthropic-main/claude-3-5-sonnet-20241022"}
            }
        ]
    }
)
response = client.chat.completions.create(messages=messages)

5. Load Balancing (Router)

LiteLLM:

from litellm import Router

model_list = [
    {
        "model_name": "gpt-3.5-turbo",
        "litellm_params": {
            "model": "azure/chatgpt-v-2",
            "api_key": os.getenv("AZURE_API_KEY"),
            "api_base": os.getenv("AZURE_API_BASE"),
            "rpm": 900
        }
    },
    {
        "model_name": "gpt-3.5-turbo",
        "litellm_params": {
            "model": "openai/gpt-3.5-turbo",
            "api_key": os.getenv("OPENAI_API_KEY"),
            "rpm": 100
        }
    }
]

router = Router(model_list=model_list, routing_strategy="simple-shuffle")
response = await router.acompletion(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "Hello!"}]
)

Portkey:

client = Portkey(
    api_key=os.environ["PORTKEY_API_KEY"],
    config={
        "strategy": {"mode": "loadbalance"},
        "targets": [
            {
                "override_params": {"model": "@azure-prod/gpt-3.5-turbo"},
                "weight": 0.9
            },
            {
                "override_params": {"model": "@openai-prod/gpt-3.5-turbo"},
                "weight": 0.1
            }
        ]
    }
)
response = client.chat.completions.create(
    messages=[{"role": "user", "content": "Hello!"}]
)

6. Retries

LiteLLM:

response = completion(
    model="openai/gpt-4o",
    messages=messages,
    num_retries=3
)

Portkey:

client = Portkey(
    api_key=os.environ["PORTKEY_API_KEY"],
    config={
        "retry": {"attempts": 3, "on_status_codes": [429, 500, 502, 503, 504]}
    }
)
response = client.chat.completions.create(
    model="@openai-prod/gpt-4o",
    messages=messages
)

7. Caching

LiteLLM:

import litellm
from litellm.caching.caching import Cache

litellm.cache = Cache(type="redis", host="localhost", port=6379)

response = completion(model="openai/gpt-4o", messages=messages, caching=True)

Portkey: (no infrastructure to manage — caching is built-in)

client = Portkey(
    api_key=os.environ["PORTKEY_API_KEY"],
    config={
        "cache": {"mode": "semantic", "max_age": 3600}
    }
)
response = client.chat.completions.create(
    model="@openai-prod/gpt-4o",
    messages=messages
)

8. Observability

LiteLLM:

import litellm
litellm.success_callback = ["langfuse"]
litellm.failure_callback = ["langfuse"]

Portkey: (built-in — every request is logged automatically)

client = Portkey(
    api_key=os.environ["PORTKEY_API_KEY"],
    trace_id="session-123",
    metadata={
        "user_id": "user-456",
        "environment": "production"
    }
)

View logs, traces, costs, and latency at app.portkey.ai. No third-party callback integration needed.


Model Naming

LiteLLM uses provider/model format. Portkey uses @provider-slug/model where the provider slug comes from your Model Catalog:

LiteLLM Model StringPortkey Model String
"openai/gpt-4o""@openai-prod/gpt-4o"
"anthropic/claude-3-5-sonnet-20241022""@anthropic-main/claude-3-5-sonnet-20241022"
"azure/gpt-4""@azure-us-east/gpt-4"
"bedrock/anthropic.claude-3-sonnet...""@bedrock-main/anthropic.claude-3-sonnet..."
"vertex_ai/gemini-1.5-pro""@vertex-prod/gemini-1.5-pro"

The @slug prefix maps to an AI Provider in your Model Catalog. You control which models are available under each provider.


Error Handling

LiteLLM:

import litellm
try:
    response = completion(model="openai/gpt-4o", messages=messages)
except litellm.AuthenticationError:
    print("Bad API key")
except litellm.RateLimitError:
    print("Rate limited")

Portkey:

try:
    response = client.chat.completions.create(
        model="@openai-prod/gpt-4o", messages=messages
    )
except Exception as e:
    status = getattr(e, 'status_code', None)
    if status == 401:
        print("Bad API key")
    elif status == 429:
        print("Rate limited")

AI Coding Agent Migrations

Claude Code

If Claude Code is routed through a LiteLLM Proxy (via ANTHROPIC_BASE_URL), the fastest migration is:

npx portkey setup

This replaces the LiteLLM Proxy env vars (ANTHROPIC_BASE_URL, ANTHROPIC_API_KEY) with Portkey equivalents. See Proxy Migration — Claude Code section for manual setup, Bedrock/Vertex model mappings, and Config-based routing.

OpenAI Codex CLI

If Codex CLI is routed through a LiteLLM Proxy (via openai_base_url or OPENAI_BASE_URL), update ~/.codex/config.json to point at Portkey with a portkey provider and model: "@provider-slug/model" format. See Proxy Migration — Codex section for step-by-step setup.


Zero-Change Path: Keep LiteLLM, Route Through Portkey

If you want Portkey's observability and reliability without rewriting any code, you can keep using litellm.completion() and just point it at Portkey's gateway:

from litellm import completion

response = completion(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}],
    api_base="https://api.portkey.ai/v1",
    api_key=os.environ["PORTKEY_API_KEY"],
    extra_headers={"x-portkey-provider": "@openai-prod"}
)

This gives you Portkey logging, caching, and guardrails immediately — then you can migrate call-by-call to the Portkey SDK at your own pace.


OpenAI Client Approach (Minimal Changes)

If your codebase uses the OpenAI SDK to talk to LiteLLM's proxy, you can switch to Portkey by only changing base_url and adding headers — no import changes required:

import openai
from portkey_ai import PORTKEY_GATEWAY_URL, createHeaders

client = openai.OpenAI(
    api_key="not-used",
    base_url=PORTKEY_GATEWAY_URL,  # https://api.portkey.ai/v1
    default_headers=createHeaders(
        api_key="your-portkey-api-key"
    )
)

response = client.chat.completions.create(
    model="@openai-prod/gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}]
)

This also works in TypeScript/JavaScript:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.portkey.ai/v1",
  apiKey: process.env.PORTKEY_API_KEY,
  defaultHeaders: { "x-portkey-provider": "@openai-prod" }
});

const response = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Hello!" }]
});

Quick Verification with cURL

Before changing any code, test the gateway connection:

curl -s https://api.portkey.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "x-portkey-api-key: $PORTKEY_API_KEY" \
  -H "x-portkey-provider: @openai-prod" \
  -d '{
    "model": "gpt-4o",
    "max_tokens": 5,
    "messages": [{"role": "user", "content": "Say ok"}]
  }'

Routing via Headers

Portkey supports two routing modes, set via headers:

HeaderUse Case
x-portkey-provider: @slugRoute to a specific AI Provider from your Model Catalog
x-portkey-config: pc-config-xxxUse a Config (with fallbacks, caching, etc.) from the dashboard

With the @provider-slug/model format in the model parameter, you typically don't need to set these headers explicitly.


Migration Workflow

  1. Verify — Test connectivity before touching code: npx portkey verify
  2. Audit — Grep your codebase for LiteLLM usage: grep -rn "from litellm\|import litellm\|litellm\." --include="*.py"
  3. Quick win — Point existing LiteLLM calls at Portkey with api_base (see Zero-Change Path)
  4. Map — For each usage, find the Portkey equivalent using the table above or MIGRATION_PATTERNS.md
  5. Replace — Swap imports, instantiate a Portkey client, and update call sites
  6. Configure — Move routing/fallback/cache logic from code into Portkey config dicts (or dashboard Config IDs)
  7. Test — Run your test suite; response formats are identical (OpenAI-compatible)
  8. Clean up — Remove litellm from requirements, remove provider API key env vars

Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.4%
按下载量换算25

Claude

27.85%
按下载量换算19

Cursor

19.47%
按下载量换算14

Gemini CLI

8.84%
按下载量换算6

安全审计

Gen Agent Trust Hub

通过

Socket

可疑

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills