The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feat Security] - Allow blocking web crawlers (#10420)
Ishaan Jaff36264d476404
diff --git a/docs/my-website/docs/proxy/deploy.md b/docs/my-website/docs/proxy/deploy.mdindex d57686dc783..511a9dda087 100644--- a/docs/my-website/docs/proxy/deploy.md+++ b/docs/my-website/docs/proxy/deploy.md@@ -1049,3 +1049,25 @@ export DATABASE_SCHEMA="schema-name" # skip to use the default "public" schemalitellm --config /path/to/config.yaml --iam_token_db_auth```+### ✨ Blocking web crawlers++Note: This is an [enterprise only feature](https://docs.litellm.ai/docs/enterprise).++To block web crawlers from indexing the proxy server endpoints, set the `block_robots` setting to `true` in your `litellm_config.yaml` file.++```yaml showLineNumbers title="litellm_config.yaml"+general_settings:+ block_robots: true+```++#### How it works++When this is enabled, the `/robots.txt` endpoint will return a 200 status code with the following content:++```shell showLineNumbers title="robots.txt"+User-agent: *+Disallow: /+```+++diff --git a/docs/my-website/docs/proxy/enterprise.md b/docs/my-website/docs/proxy/enterprise.mdindex 26dc9d49509..6789fb6ef2f 100644--- a/docs/my-website/docs/proxy/enterprise.md+++ b/docs/my-website/docs/proxy/enterprise.md@@ -43,7 +43,9 @@ Features:- ✅ [Public Model Hub](#public-model-hub)- ✅ [Custom Email Branding](./email.md#customizing-email-branding)-## Audit Logs+## Security++### Audit LogsStore Audit logs for **Create, Update Delete Operations** done on `Teams` and `Virtual Keys`@@ -95,244 +97,313 @@ curl --location 'http://0.0.0.0:4000/team/new' \```-## Tracking Spend for Custom Tags+### Blocking web crawlers-Requirements:+To block web crawlers from indexing the proxy server endpoints, set the `block_robots` setting to `true` in your `litellm_config.yaml` file.-- Virtual Keys & a database should be set up, see [virtual keys](https://docs.litellm.ai/docs/proxy/virtual_keys)+```yaml showLineNumbers title="litellm_config.yaml"+general_settings:+ block_robots: true+```-#### Usage - /chat/completions requests with request tags+#### How it works++When this is enabled, the `/robots.txt` endpoint will return a 200 status code with the following content:++```shell showLineNumbers title="robots.txt"+User-agent: *+Disallow: /+```++++### Required Params for LLM Requests+Use this when you want to enforce all requests to include certain params. Example you need all requests to include the `user` and `["metadata]["generation_name"]` params.<Tabs>-<TabItem value="key" label="Set on Key">-```bash-curl -L -X POST 'http://0.0.0.0:4000/key/generate' \--H 'Authorization: Bearer sk-1234' \--H 'Content-Type: application/json' \--d '{- "metadata": {- "tags": ["tag1", "tag2", "tag3"]- }-}+<TabItem value="config" label="Set on Config">-'-```+**Step 1** Define all Params you want to enforce on config.yaml++This means `["user"]` and `["metadata]["generation_name"]` are required in all LLM Requests to LiteLLM+```yaml+general_settings:+ master_key: sk-1234+ enforced_params:+ - user+ - metadata.generation_name+```</TabItem>-<TabItem value="team" label="Set on Team">++<TabItem value="key" label="Set on Key">```bash-curl -L -X POST 'http://0.0.0.0:4000/team/new' \+curl -L -X POST 'http://0.0.0.0:4000/key/generate' \-H 'Authorization: Bearer sk-1234' \-H 'Content-Type: application/json' \-d '{- "metadata": {- "tags": ["tag1", "tag2", "tag3"]- }-}--'+ "enforced_params": ["user", "metadata.generation_name"]+}'```</TabItem>-<TabItem value="openai" label="OpenAI Python v1.0.0+">+</Tabs>-Set `extra_body={"metadata": { }}` to `metadata` you want to pass+**Step 2 Verify if this works**-```python-import openai-client = openai.OpenAI(- api_key="anything",- base_url="http://0.0.0.0:4000"-)+<Tabs>+<TabItem value="bad" label="Invalid Request (No `user` passed)">-response = client.chat.completions.create(- model="gpt-3.5-turbo",- messages = [+```shell+curl --location 'http://localhost:4000/chat/completions' \+ --header 'Authorization: Bearer sk-5fmYeaUEbAMpwBNT-QpxyA' \+ --header 'Content-Type: application/json' \+ --data '{+ "model": "gpt-3.5-turbo",+ "messages": [{- "role": "user",- "content": "this is a test request, write a short poem"- }- ],- extra_body={- "metadata": {- "tags": ["model-anthropic-claude-v2.1", "app-ishaan-prod"] # 👈 Key Change+ "role": "user",+ "content": "hi"}- }-)--print(response)+ ]+}'```-</TabItem>+Expected Response-<TabItem value="openai js" label="OpenAI JS">+```shell+{"error":{"message":"Authentication Error, BadRequest please pass param=user in request body. This is a required param","type":"auth_error","param":"None","code":401}}%+```-```js-const openai = require('openai');+</TabItem>-async function runOpenAI() {- const client = new openai.OpenAI({- apiKey: 'sk-1234',- baseURL: 'http://0.0.0.0:4000'- });+<TabItem value="bad2" label="Invalid Request (No `metadata` passed)">- try {- const response = await client.chat.completions.create({- model: 'gpt-3.5-turbo',- messages: [+```shell+curl --location 'http://localhost:4000/chat/completions' \+ --header 'Authorization: Bearer sk-5fmYeaUEbAMpwBNT-QpxyA' \+ --header 'Content-Type: application/json' \+ --data '{+ "model": "gpt-3.5-turbo",+ "user": "gm",+ "messages": [{- role: 'user',- content: "this is a test request, write a short poem"- },- ],- metadata: {- tags: ["model-anthropic-claude-v2.1", "app-ishaan-prod"] // 👈 Key Change- }- });- console.log(response);- } catch (error) {- console.log("got this exception from server");- console.error(error);- }-}+ "role": "user",+ "content": "hi"+ }+ ],+ "metadata": {}+}'+```-// Call the asynchronous function-runOpenAI();+Expected Response++```shell+{"error":{"message":"Authentication Error, BadRequest please pass param=[metadata][generation_name] in request body. This is a required param","type":"auth_error","param":"None","code":401}}%```-</TabItem>-<TabItem value="Curl" label="Curl Request">-Pass `metadata` as part of the request body+</TabItem>+<TabItem value="good" label="Valid Request">```shell-curl --location 'http://0.0.0.0:4000/chat/completions' \+curl --location 'http://localhost:4000/chat/completions' \+ --header 'Authorization: Bearer sk-5fmYeaUEbAMpwBNT-QpxyA' \--header 'Content-Type: application/json' \--data '{"model": "gpt-3.5-turbo",+ "user": "gm","messages": [{"role": "user",- "content": "what llm are you"+ "content": "hi"}],- "metadata": {"tags": ["model-anthropic-claude-v2.1", "app-ishaan-prod"]}+ "metadata": {"generation_name": "prod-app"}}'```-</TabItem>-<TabItem value="langchain" label="Langchain">--```python-from langchain.chat_models import ChatOpenAI-from langchain.prompts.chat import (- ChatPromptTemplate,- HumanMessagePromptTemplate,- SystemMessagePromptTemplate,-)-from langchain.schema import HumanMessage, SystemMessage--chat = ChatOpenAI(- openai_api_base="http://0.0.0.0:4000",- model = "gpt-3.5-turbo",- temperature=0.1,- extra_body={- "metadata": {- "tags": ["model-anthropic-claude-v2.1", "app-ishaan-prod"]- }- }-)-messages = [- SystemMessage(- content="You are a helpful assistant that im using to make a test request to."- ),- HumanMessage(- content="test from litellm. tell me why it's amazing in 1 sentence"- ),-]-response = chat(messages)+Expected Response-print(response)+```shell+{"id":"chatcmpl-9XALnHqkCBMBKrOx7Abg0hURHqYtY","choices":[{"finish_reason":"stop","index":0,"message":{"content":"Hello! How can I assist you today?","role":"assistant"}}],"created":1717691639,"model":"gpt-3.5-turbo-0125","object":"chat.completion","system_fingerprint":null,"usage":{"completion_tokens":9,"prompt_tokens":8,"total_tokens":17}}%```</TabItem></Tabs>-#### Viewing Spend per tag--#### `/spend/tags` Request Format-```shell-curl -X GET "http://0.0.0.0:4000/spend/tags" \--H "Authorization: Bearer sk-1234"-```-#### `/spend/tags`Response Format-```shell-[- {- "individual_request_tag": "model-anthropic-claude-v2.1",- "log_count": 6,- "total_spend": 0.000672- },- {- "individual_request_tag": "app-ishaan-local",- "log_count": 4,- "total_spend": 0.000448- },- {- "individual_request_tag": "app-ishaan-prod",- "log_count": 2,- "total_spend": 0.000224- }-]+### Control available public, private routes-```+**Restrict certain endpoints of proxy**+:::info-## Tracking Spend with custom metadata+❓ Use this when you want to:+- make an existing private route -> public+- set certain routes as admin_only routes-Requirements:+:::-- Virtual Keys & a database should be set up, see [virtual keys](https://docs.litellm.ai/docs/proxy/virtual_keys)+#### Usage - Define public, admin only routes-#### Usage - /chat/completions requests with special spend logs metadata+**Step 1** - Set on config.yaml-<Tabs>-<TabItem value="key" label="Set on Key">+| Route Type | Optional | Requires Virtual Key Auth | Admin Can Access | All Roles Can Access | Description |+|------------|----------|---------------------------|-------------------|----------------------|-------------|+| `public_routes` | ✅ | ❌ | ✅ | ✅ | Routes that can be accessed without any authentication |+| `admin_only_routes` | ✅ | ✅ | ✅ | ❌ | Routes that can only be accessed by [Proxy Admin](./self_serve#available-roles) |+| `allowed_routes` | ✅ | ✅ | ✅ | ✅ | Routes are exposed on the proxy. If not set then all routes exposed. |-```bash-curl -L -X POST 'http://0.0.0.0:4000/key/generate' \--H 'Authorization: Bearer sk-1234' \--H 'Content-Type: application/json' \--d '{- "metadata": {- "spend_logs_metadata": {- "hello": "world"- }- }-}+`LiteLLMRoutes.public_routes` is an ENUM corresponding to the default public routes on LiteLLM. [You can see this here](https://github.com/BerriAI/litellm/blob/main/litellm/proxy/_types.py)-'+```yaml+general_settings:+ master_key: sk-1234+ public_routes: ["LiteLLMRoutes.public_routes", "/spend/calculate"] # routes that can be accessed without any auth+ admin_only_routes: ["/key/generate"] # Optional - routes that can only be accessed by Proxy Admin+ allowed_routes: ["/chat/completions", "/spend/calculate", "LiteLLMRoutes.public_routes"] # Optional - routes that can be accessed by anyone after Authentication```-</TabItem>-<TabItem value="team" label="Set on Team">+**Step 2** - start proxy-```bash-curl -L -X POST 'http://0.0.0.0:4000/team/new' \+```shell+litellm --config config.yaml+```++**Step 3** - Test it++<Tabs>++<TabItem value="public" label="Test `public_routes`">++```shell+curl --request POST \+ --url 'http://localhost:4000/spend/calculate' \+ --header 'Content-Type: application/json' \+ --data '{+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "Hey, how'\''s it going?"}]+ }'+```++🎉 Expect this endpoint to work without an `Authorization / Bearer Token`++</TabItem>++<TabItem value="admin_only_routes" label="Test `admin_only_routes`">+++**Successful Request**++```shell+curl --location 'http://0.0.0.0:4000/key/generate' \+--header 'Authorization: Bearer <your-master-key>' \+--header 'Content-Type: application/json' \+--data '{}'+```+++**Un-successfull Request**++```shell+ curl --location 'http://0.0.0.0:4000/key/generate' \+--header 'Authorization: Bearer <virtual-key-from-non-admin>' \+--header 'Content-Type: application/json' \+--data '{"user_role": "internal_user"}'+```++**Expected Response**++```json+{+ "error": {+ "message": "user not allowed to access this route. Route=/key/generate is an admin only route",+ "type": "auth_error",+ "param": "None",+ "code": "403"+ }+}+```+++</TabItem>++<TabItem value="allowed_routes" label="Test `allowed_routes`">+++**Successful Request**++```shell+curl http://localhost:4000/chat/completions \+-H "Content-Type: application/json" \+-H "Authorization: Bearer sk-1234" \+-d '{+"model": "fake-openai-endpoint",+"messages": [+ {"role": "user", "content": "Hello, Claude"}+]+}'+```+++**Un-successfull Request**++```shell+curl --location 'http://0.0.0.0:4000/embeddings' \+--header 'Content-Type: application/json' \+-H "Authorization: Bearer sk-1234" \+--data ' {+"model": "text-embedding-ada-002",+"input": ["write a litellm poem"]+}'+```++**Expected Response**++```json+{+ "error": {+ "message": "Route /embeddings not allowed",+ "type": "auth_error",+ "param": "None",+ "code": "403"+ }+}+```+++</TabItem>++</Tabs>++## Spend Tracking++### Custom Tags++Requirements:++- Virtual Keys & a database should be set up, see [virtual keys](https://docs.litellm.ai/docs/proxy/virtual_keys)++#### Usage - /chat/completions requests with request tags+++<Tabs>+<TabItem value="key" label="Set on Key">++```bash+curl -L -X POST 'http://0.0.0.0:4000/key/generate' \-H 'Authorization: Bearer sk-1234' \-H 'Content-Type: application/json' \-d '{"metadata": {- "spend_logs_metadata": {- "hello": "world"- }+ "tags": ["tag1", "tag2", "tag3"]}}@@ -340,7 +411,22 @@ curl -L -X POST 'http://0.0.0.0:4000/team/new' \```</TabItem>+<TabItem value="team" label="Set on Team">++```bash+curl -L -X POST 'http://0.0.0.0:4000/team/new' \+-H 'Authorization: Bearer sk-1234' \+-H 'Content-Type: application/json' \+-d '{+ "metadata": {+ "tags": ["tag1", "tag2", "tag3"]+ }+}+'+```++</TabItem><TabItem value="openai" label="OpenAI Python v1.0.0+">Set `extra_body={"metadata": { }}` to `metadata` you want to pass@@ -352,7 +438,7 @@ client = openai.OpenAI(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-3.5-turbo",messages = [@@ -363,9 +449,7 @@ response = client.chat.completions.create(],extra_body={"metadata": {- "spend_logs_metadata": {- "hello": "world"- }+ "tags": ["model-anthropic-claude-v2.1", "app-ishaan-prod"] # 👈 Key Change}})@@ -396,9 +480,7 @@ async function runOpenAI() {},],metadata: {- spend_logs_metadata: { // 👈 Key Change- hello: "world"- }+ tags: ["model-anthropic-claude-v2.1", "app-ishaan-prod"] // 👈 Key Change}});console.log(response);@@ -428,11 +510,7 @@ curl --location 'http://0.0.0.0:4000/chat/completions' \"content": "what llm are you"}],- "metadata": {- "spend_logs_metadata": {- "hello": "world"- }- }+ "metadata": {"tags": ["model-anthropic-claude-v2.1", "app-ishaan-prod"]}}'```</TabItem>@@ -453,9 +531,7 @@ chat = ChatOpenAI(temperature=0.1,extra_body={"metadata": {- "spend_logs_metadata": {- "hello": "world"- }+ "tags": ["model-anthropic-claude-v2.1", "app-ishaan-prod"]}})@@ -477,307 +553,249 @@ print(response)</Tabs>-#### Viewing Spend w/ custom metadata--#### `/spend/logs` Request Format+#### Viewing Spend per tag-```bash-curl -X GET "http://0.0.0.0:4000/spend/logs?request_id=<your-call-id" \ # e.g.: chatcmpl-9ZKMURhVYSi9D6r6PJ9vLcayIK0Vm+#### `/spend/tags` Request Format+```shell+curl -X GET "http://0.0.0.0:4000/spend/tags" \-H "Authorization: Bearer sk-1234"```-#### `/spend/logs` Response Format-```bash+#### `/spend/tags`Response Format+```shell[- {- "request_id": "chatcmpl-9ZKMURhVYSi9D6r6PJ9vLcayIK0Vm",- "call_type": "acompletion",- "metadata": {- "user_api_key": "88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",- "user_api_key_alias": null,- "spend_logs_metadata": { # 👈 LOGGED CUSTOM METADATA- "hello": "world"- },- "user_api_key_team_id": null,- "user_api_key_user_id": "116544810872468347480",- "user_api_key_team_alias": null- },- }+ {+ "individual_request_tag": "model-anthropic-claude-v2.1",+ "log_count": 6,+ "total_spend": 0.000672+ },+ {+ "individual_request_tag": "app-ishaan-local",+ "log_count": 4,+ "total_spend": 0.000448+ },+ {+ "individual_request_tag": "app-ishaan-prod",+ "log_count": 2,+ "total_spend": 0.000224+ }]+```+### Tracking Spend with custom metadata-## Enforce Required Params for LLM Requests-Use this when you want to enforce all requests to include certain params. Example you need all requests to include the `user` and `["metadata]["generation_name"]` params.+Requirements:+- Virtual Keys & a database should be set up, see [virtual keys](https://docs.litellm.ai/docs/proxy/virtual_keys)-<Tabs>+#### Usage - /chat/completions requests with special spend logs metadata-<TabItem value="config" label="Set on Config">-**Step 1** Define all Params you want to enforce on config.yaml+<Tabs>+<TabItem value="key" label="Set on Key">-This means `["user"]` and `["metadata]["generation_name"]` are required in all LLM Requests to LiteLLM+```bash+curl -L -X POST 'http://0.0.0.0:4000/key/generate' \+-H 'Authorization: Bearer sk-1234' \+-H 'Content-Type: application/json' \+-d '{+ "metadata": {+ "spend_logs_metadata": {+ "hello": "world"+ }+ }+}-```yaml-general_settings:- master_key: sk-1234- enforced_params:- - user- - metadata.generation_name+'```-</TabItem>-<TabItem value="key" label="Set on Key">+</TabItem>+<TabItem value="team" label="Set on Team">```bash-curl -L -X POST 'http://0.0.0.0:4000/key/generate' \+curl -L -X POST 'http://0.0.0.0:4000/team/new' \-H 'Authorization: Bearer sk-1234' \-H 'Content-Type: application/json' \-d '{- "enforced_params": ["user", "metadata.generation_name"]-}'+ "metadata": {+ "spend_logs_metadata": {+ "hello": "world"+ }+ }+}++'```</TabItem>-</Tabs>-**Step 2 Verify if this works**+<TabItem value="openai" label="OpenAI Python v1.0.0+">-<Tabs>+Set `extra_body={"metadata": { }}` to `metadata` you want to pass-<TabItem value="bad" label="Invalid Request (No `user` passed)">+```python+import openai+client = openai.OpenAI(+ api_key="anything",+ base_url="http://0.0.0.0:4000"+)-```shell-curl --location 'http://localhost:4000/chat/completions' \- --header 'Authorization: Bearer sk-5fmYeaUEbAMpwBNT-QpxyA' \- --header 'Content-Type: application/json' \- --data '{- "model": "gpt-3.5-turbo",- "messages": [+# request sent to model set on litellm proxy, `litellm --model`+response = client.chat.completions.create(+ model="gpt-3.5-turbo",+ messages = [{- "role": "user",- "content": "hi"+ "role": "user",+ "content": "this is a test request, write a short poem"}- ]-}'+ ],+ extra_body={+ "metadata": {+ "spend_logs_metadata": {+ "hello": "world"+ }+ }+ }+)++print(response)```+</TabItem>-Expected Response-```shell-{"error":{"message":"Authentication Error, BadRequest please pass param=user in request body. This is a required param","type":"auth_error","param":"None","code":401}}%-```+<TabItem value="openai js" label="OpenAI JS">-</TabItem>+```js+const openai = require('openai');-<TabItem value="bad2" label="Invalid Request (No `metadata` passed)">+async function runOpenAI() {+ const client = new openai.OpenAI({+ apiKey: 'sk-1234',+ baseURL: 'http://0.0.0.0:4000'+ });-```shell-curl --location 'http://localhost:4000/chat/completions' \- --header 'Authorization: Bearer sk-5fmYeaUEbAMpwBNT-QpxyA' \- --header 'Content-Type: application/json' \- --data '{- "model": "gpt-3.5-turbo",- "user": "gm",- "messages": [+ try {+ const response = await client.chat.completions.create({+ model: 'gpt-3.5-turbo',+ messages: [{- "role": "user",- "content": "hi"+ role: 'user',+ content: "this is a test request, write a short poem"+ },+ ],+ metadata: {+ spend_logs_metadata: { // 👈 Key Change+ hello: "world"}- ],- "metadata": {}-}'-```--Expected Response+ }+ });+ console.log(response);+ } catch (error) {+ console.log("got this exception from server");+ console.error(error);+ }+}-```shell-{"error":{"message":"Authentication Error, BadRequest please pass param=[metadata][generation_name] in request body. This is a required param","type":"auth_error","param":"None","code":401}}%+// Call the asynchronous function+runOpenAI();```+</TabItem>+<TabItem value="Curl" label="Curl Request">-</TabItem>-<TabItem value="good" label="Valid Request">+Pass `metadata` as part of the request body```shell-curl --location 'http://localhost:4000/chat/completions' \- --header 'Authorization: Bearer sk-5fmYeaUEbAMpwBNT-QpxyA' \+curl --location 'http://0.0.0.0:4000/chat/completions' \--header 'Content-Type: application/json' \--data '{"model": "gpt-3.5-turbo",- "user": "gm","messages": [{"role": "user",- "content": "hi"+ "content": "what llm are you"}],- "metadata": {"generation_name": "prod-app"}+ "metadata": {+ "spend_logs_metadata": {+ "hello": "world"+ }+ }}'```--Expected Response--```shell-{"id":"chatcmpl-9XALnHqkCBMBKrOx7Abg0hURHqYtY","choices":[{"finish_reason":"stop","index":0,"message":{"content":"Hello! How can I assist you today?","role":"assistant"}}],"created":1717691639,"model":"gpt-3.5-turbo-0125","object":"chat.completion","system_fingerprint":null,"usage":{"completion_tokens":9,"prompt_tokens":8,"total_tokens":17}}%-```-</TabItem>-</Tabs>----## Control available public, private routes--**Restrict certain endpoints of proxy**--:::info--❓ Use this when you want to:-- make an existing private route -> public-- set certain routes as admin_only routes--:::--#### Usage - Define public, admin only routes--**Step 1** - Set on config.yaml---| Route Type | Optional | Requires Virtual Key Auth | Admin Can Access | All Roles Can Access | Description |-|------------|----------|---------------------------|-------------------|----------------------|-------------|-| `public_routes` | ✅ | ❌ | ✅ | ✅ | Routes that can be accessed without any authentication |-| `admin_only_routes` | ✅ | ✅ | ✅ | ❌ | Routes that can only be accessed by [Proxy Admin](./self_serve#available-roles) |-| `allowed_routes` | ✅ | ✅ | ✅ | ✅ | Routes are exposed on the proxy. If not set then all routes exposed. |--`LiteLLMRoutes.public_routes` is an ENUM corresponding to the default public routes on LiteLLM. [You can see this here](https://github.com/BerriAI/litellm/blob/main/litellm/proxy/_types.py)--```yaml-general_settings:- master_key: sk-1234- public_routes: ["LiteLLMRoutes.public_routes", "/spend/calculate"] # routes that can be accessed without any auth- admin_only_routes: ["/key/generate"] # Optional - routes that can only be accessed by Proxy Admin- allowed_routes: ["/chat/completions", "/spend/calculate", "LiteLLMRoutes.public_routes"] # Optional - routes that can be accessed by anyone after Authentication-```--**Step 2** - start proxy--```shell-litellm --config config.yaml-```+<TabItem value="langchain" label="Langchain">-**Step 3** - Test it+```python+from langchain.chat_models import ChatOpenAI+from langchain.prompts.chat import (+ ChatPromptTemplate,+ HumanMessagePromptTemplate,+ SystemMessagePromptTemplate,+)+from langchain.schema import HumanMessage, SystemMessage-<Tabs>+chat = ChatOpenAI(+ openai_api_base="http://0.0.0.0:4000",+ model = "gpt-3.5-turbo",+ temperature=0.1,+ extra_body={+ "metadata": {+ "spend_logs_metadata": {+ "hello": "world"+ }+ }+ }+)-<TabItem value="public" label="Test `public_routes`">+messages = [+ SystemMessage(+ content="You are a helpful assistant that im using to make a test request to."+ ),+ HumanMessage(+ content="test from litellm. tell me why it's amazing in 1 sentence"+ ),+]+response = chat(messages)-```shell-curl --request POST \- --url 'http://localhost:4000/spend/calculate' \- --header 'Content-Type: application/json' \- --data '{- "model": "gpt-4",- "messages": [{"role": "user", "content": "Hey, how'\''s it going?"}]- }'+print(response)```-🎉 Expect this endpoint to work without an `Authorization / Bearer Token`-</TabItem>--<TabItem value="admin_only_routes" label="Test `admin_only_routes`">---**Successful Request**--```shell-curl --location 'http://0.0.0.0:4000/key/generate' \---header 'Authorization: Bearer <your-master-key>' \---header 'Content-Type: application/json' \---data '{}'-```+</Tabs>-**Un-successfull Request**--```shell- curl --location 'http://0.0.0.0:4000/key/generate' \---header 'Authorization: Bearer <virtual-key-from-non-admin>' \---header 'Content-Type: application/json' \---data '{"user_role": "internal_user"}'-```+#### Viewing Spend w/ custom metadata-**Expected Response**+#### `/spend/logs` Request Format-```json-{- "error": {- "message": "user not allowed to access this route. Route=/key/generate is an admin only route",- "type": "auth_error",- "param": "None",- "code": "403"- }-}+```bash+curl -X GET "http://0.0.0.0:4000/spend/logs?request_id=<your-call-id" \ # e.g.: chatcmpl-9ZKMURhVYSi9D6r6PJ9vLcayIK0Vm+-H "Authorization: Bearer sk-1234"```--</TabItem>--<TabItem value="allowed_routes" label="Test `allowed_routes`">---**Successful Request**--```shell-curl http://localhost:4000/chat/completions \--H "Content-Type: application/json" \--H "Authorization: Bearer sk-1234" \--d '{-"model": "fake-openai-endpoint",-"messages": [- {"role": "user", "content": "Hello, Claude"}+#### `/spend/logs` Response Format+```bash+[+ {+ "request_id": "chatcmpl-9ZKMURhVYSi9D6r6PJ9vLcayIK0Vm",+ "call_type": "acompletion",+ "metadata": {+ "user_api_key": "88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",+ "user_api_key_alias": null,+ "spend_logs_metadata": { # 👈 LOGGED CUSTOM METADATA+ "hello": "world"+ },+ "user_api_key_team_id": null,+ "user_api_key_user_id": "116544810872468347480",+ "user_api_key_team_alias": null+ },+ }]-}'```--**Un-successfull Request**--```shell-curl --location 'http://0.0.0.0:4000/embeddings' \---header 'Content-Type: application/json' \--H "Authorization: Bearer sk-1234" \---data ' {-"model": "text-embedding-ada-002",-"input": ["write a litellm poem"]-}'-```--**Expected Response**--```json-{- "error": {- "message": "Route /embeddings not allowed",- "type": "auth_error",- "param": "None",- "code": "403"- }-}-```---</TabItem>------</Tabs>-## Guardrails - Secret Detection/Redaction❓ Use this to REDACT API Keys, Secrets sent in requests to an LLM.diff --git a/enterprise/proxy/enterprise_routes.py b/enterprise/proxy/enterprise_routes.pynew file mode 100644index 00000000000..1d7a39b0ae5--- /dev/null+++ b/enterprise/proxy/enterprise_routes.py@@ -0,0 +1,17 @@+from fastapi import APIRouter+from fastapi.responses import Response+from .utils import _should_block_robots++router = APIRouter()++[email protected]("/robots.txt")+async def get_robots():+ """+ Block all web crawlers from indexing the proxy server endpoints+ This is useful for ensuring that the API endpoints aren't indexed by search engines+ """+ if _should_block_robots():+ return Response(content="User-agent: *\nDisallow: /", media_type="text/plain")+ else:+ return Response(status_code=404)\ No newline at end of filediff --git a/enterprise/proxy/readme.md b/enterprise/proxy/readme.mdnew file mode 100644index 00000000000..9ec611fa836--- /dev/null+++ b/enterprise/proxy/readme.md@@ -0,0 +1,6 @@+# LiteLLM Proxy Enterprise Features - Readme++## Overview++This directory contains enterprise features used on the LiteLLM proxy.+diff --git a/enterprise/proxy/utils.py b/enterprise/proxy/utils.pynew file mode 100644index 00000000000..c3396964ee6--- /dev/null+++ b/enterprise/proxy/utils.py@@ -0,0 +1,27 @@+from typing import Union, Optional+from litellm.secret_managers.main import str_to_bool+++def _should_block_robots():+ """+ Returns True if the robots.txt file should block web crawlers++ Controlled by++ ```yaml+ general_settings:+ block_robots: true+ ```+ """+ from litellm.proxy.proxy_server import general_settings, premium_user, CommonProxyErrors+ _block_robots: Union[bool, str] = general_settings.get("block_robots", False)+ block_robots: Optional[bool] = None+ if isinstance(_block_robots, bool):+ block_robots = _block_robots+ elif isinstance(_block_robots, str):+ block_robots = str_to_bool(_block_robots)+ if block_robots is True:+ if premium_user is not True:+ raise ValueError(f"Blocking web crawlers is an enterprise feature. {CommonProxyErrors.not_premium_user.value}")+ return True+ return Falsediff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex 8ff36b91f57..9e56d69b90b 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -8,3 +8,4 @@ model_list:api_version: os.environ/AZURE_RESPONSES_OPENAI_API_VERSIONgeneral_settings:store_prompts_in_spend_logs: true+ block_robots: truediff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 966d79c6073..7feb7f50929 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -378,13 +378,16 @@ from fastapi.security.api_key import APIKeyHeaderfrom fastapi.staticfiles import StaticFiles# import enterprise folder+enterprise_router = APIRouter()try:# when using litellm cliimport litellm.proxy.enterprise as enterprise+ from enterprise.proxy.enterprise_routes import router as enterprise_routerexcept Exception:# when using litellm docker imagetry:import enterprise # type: ignore+ from enterprise.proxy.enterprise_routes import router as enterprise_routerexcept Exception:pass@@ -810,9 +813,9 @@ model_max_budget_limiter = _PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=user_api_key_cache)litellm.logging_callback_manager.add_litellm_callback(model_max_budget_limiter)-redis_usage_cache: Optional[- RedisCache-] = None # redis cache used for tracking spend, tpm/rpm limits+redis_usage_cache: Optional[RedisCache] = (+ None # redis cache used for tracking spend, tpm/rpm limits+)user_custom_auth = Noneuser_custom_key_generate = Noneuser_custom_sso = None@@ -1138,9 +1141,9 @@ async def update_cache( # noqa: PLR0915_id = "team_id:{}".format(team_id)try:# Fetch the existing cost for the given user- existing_spend_obj: Optional[- LiteLLM_TeamTable- ] = await user_api_key_cache.async_get_cache(key=_id)+ existing_spend_obj: Optional[LiteLLM_TeamTable] = (+ await user_api_key_cache.async_get_cache(key=_id)+ )if existing_spend_obj is None:# do nothing if team not in api key cachereturn@@ -2812,9 +2815,9 @@ async def initialize( # noqa: PLR0915user_api_base = api_basedynamic_config[user_model]["api_base"] = api_baseif api_version:- os.environ[- "AZURE_API_VERSION"- ] = api_version # set this for azure - litellm can read this from the env+ os.environ["AZURE_API_VERSION"] = (+ api_version # set this for azure - litellm can read this from the env+ )if max_tokens: # model-specific paramdynamic_config[user_model]["max_tokens"] = max_tokensif temperature: # model-specific param@@ -7818,9 +7821,9 @@ async def get_config_list(hasattr(sub_field_info, "description")and sub_field_info.description is not None):- nested_fields[- idx- ].field_description = sub_field_info.description+ nested_fields[idx].field_description = (+ sub_field_info.description+ )idx += 1_stored_in_db = None@@ -8252,3 +8255,4 @@ app.include_router(team_callback_router)app.include_router(budget_management_router)app.include_router(model_management_router)app.include_router(tag_management_router)+app.include_router(enterprise_router)diff --git a/tests/litellm/enterprise/test_enterprise_routes.py b/tests/litellm/enterprise/test_enterprise_routes.pynew file mode 100644index 00000000000..61cea9c4c20--- /dev/null+++ b/tests/litellm/enterprise/test_enterprise_routes.py@@ -0,0 +1,40 @@+import json+import os+import sys+import unittest.mock as mock++import pytest+from fastapi.testclient import TestClient++sys.path.insert(+ 0, os.path.abspath("../../..")+) # Adds the parent directory to the system path++from enterprise.proxy.enterprise_routes import router+++def client():+ return TestClient(router)+++def test_robots_when_blocked(client):+ """Test get_robots returns block instructions when _should_block_robots returns True"""+ with mock.patch(+ "enterprise.proxy.enterprise_routes._should_block_robots", return_value=True+ ):+ response = client.get("/robots.txt")+ print("got response", response)+ print("got response text", response.text)+ print("got response headers", response.headers)+ assert response.status_code == 200+ assert response.text == "User-agent: *\nDisallow: /"+++def test_robots_when_not_blocked(client):+ """Test get_robots returns 404 when _should_block_robots returns False"""+ with mock.patch(+ "enterprise.proxy.enterprise_routes._should_block_robots", return_value=False+ ):+ response = client.get("/robots.txt")+ assert response.status_code == 404