> ## Documentation Index
> Fetch the complete documentation index at: https://portkey-docs-add-third-party-integration-issues-fixes.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Lambda Labs

> Integrate Lambda with Portkey AI for seamless completions, prompt management, and advanced features like streaming and function calling.

<Note>
  **Portkey Provider Slug:** `lambda`
</Note>

## Overview

Portkey offers native integrations with [Lambda](https://lambdalabs.com/) for Node.js, Python, and REST APIs. By combining Portkey with Lambda, you can create production-grade AI applications with enhanced reliability, observability, and advanced features.

<CardGroup cols={1}>
  <Card title="Lambda Documentation" icon="book" href="https://docs.lambdalabs.com/">
    Explore the official Lambda documentation for comprehensive details on their APIs and models.
  </Card>
</CardGroup>

## Getting Started

<Steps>
  <Step title="Obtain your Lambda API Key">
    Visit the [Lambda dashboard](https://cloud.lambdalabs.com/api-keys) to generate your API key.
  </Step>

  <Step title="Create a Virtual Key in Portkey">
    Portkey's virtual key vault simplifies your interaction with Lambda. Virtual keys act as secure aliases for your actual API keys, offering enhanced security and easier management through [budget limits](/product/ai-gateway/virtual-keys/budget-limits) to control your API usage.

    Use the Portkey app to create a [virtual key](/product/ai-gateway/virtual-keys) associated with your Lambda API key.
  </Step>

  <Step title="Initialize the Portkey Client">
    Now that you have your virtual key, set up the Portkey client:

    ### Portkey Hosted App

    Use the Portkey API key and the Lambda virtual key to initialize the client in your preferred programming language.

    <CodeGroup>
      ```python Python theme={null}
      from portkey_ai import Portkey

      portkey = Portkey(
          api_key="PORTKEY_API_KEY",  # Replace with your Portkey API key
          virtual_key="VIRTUAL_KEY"   # Replace with your virtual key for Lambda
      )
      ```

      ```javascript Node.js theme={null}
      import Portkey from 'portkey-ai'

      const portkey = new Portkey({
          apiKey: "PORTKEY_API_KEY", // defaults to process.env["PORTKEY_API_KEY"]
          virtualKey: "VIRTUAL_KEY" // Your Lambda Virtual Key
      })
      ```
    </CodeGroup>

    ### Open Source Use

    Alternatively, use Portkey's Open Source AI Gateway to enhance your app's reliability with minimal code:

    <CodeGroup>
      ```python Python theme={null}
      from portkey_ai import Portkey, PORTKEY_GATEWAY_URL

      portkey = Portkey(
          api_key="dummy",  # Replace with your Portkey API key
          base_url=PORTKEY_GATEWAY_URL,
          Authorization="LAMBDA_API_KEY", # Replace with your Lambda API Key
          provider="lambda"
      )
      ```

      ```javascript Node.js theme={null}
      import Portkey, { PORTKEY_GATEWAY_URL } from 'portkey-ai'

      const portkey = new Portkey({
          apiKey: "dummy", // Replace with your Portkey API key
          baseUrl: PORTKEY_GATEWAY_URL,
          Authorization: "LAMBDA_API_KEY", // Replace with your Lambda API Key
          provider: "lambda"
      })
      ```
    </CodeGroup>
  </Step>
</Steps>

🔥 That's it! You've integrated Portkey into your application with just a few lines of code. Now let's explore making requests using the Portkey client.

## Supported Models

<Accordion title="Supported Lambda Models">
  * deepseek-coder-v2-lite-instruct
  * dracarys2-72b-instruct
  * hermes3-405b
  * hermes3-405b-fp8-128k
  * hermes3-70b
  * hermes3-8b
  * lfm-40b
  * llama3.1-405b-instruct-fp8
  * llama3.1-70b-instruct-fp8
  * llama3.1-8b-instruct
  * llama3.2-3b-instruct
  * llama3.1-nemotron-70b-instruct
</Accordion>

## Supported Endpoints and Parameters

| Endpoint       | Supported Parameters                                                                                                                                               |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `chatComplete` | messages, max\_tokens, temperature, top\_p, stream, presence\_penalty, frequency\_penalty                                                                          |
| `complete`     | model, prompt, max\_tokens, temperature, top\_p, n, stream, logprobs, echo, stop, presence\_penalty, frequency\_penalty, best\_of, logit\_bias, user, seed, suffix |

## Lambda Supported Features

### Chat Completions

Generate chat completions using Lambda models through Portkey:

<CodeGroup>
  ```python Python theme={null}
  completion = portkey.chat.completions.create(
      messages=[{"role": "user", "content": "Say this is a test"}],
      model="llama3.1-8b-instruct"
  )

  print(completion.choices[0].message.content)
  ```

  ```javascript Node.js theme={null}
  const chatCompletion = await portkey.chat.completions.create({
      messages: [{ role: 'user', content: 'Say this is a test' }],
      model: 'llama3.1-8b-instruct',
  });

  console.log(chatCompletion.choices[0].message.content);
  ```

  ```curl REST theme={null}
  curl -X POST "https://api.portkey.ai/v1/chat/completions" \
       -H "Content-Type: application/json" \
       -H "Authorization: Bearer YOUR_PORTKEY_API_KEY" \
       -d '{
         "messages": [{"role": "user", "content": "Say this is a test"}],
         "model": "llama3.1-8b-instruct"
       }'
  ```
</CodeGroup>

### Streaming

Stream responses for real-time output in your applications:

<CodeGroup>
  ```python Python theme={null}
  chat_complete = portkey.chat.completions.create(
      model="llama3.1-8b-instruct",
      messages=[{"role": "user", "content": "Say this is a test"}],
      stream=True
  )

  for chunk in chat_complete:
      print(chunk.choices[0].delta.content or "", end="", flush=True)
  ```

  ```javascript Node.js theme={null}
  const stream = await portkey.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: 'Say this is a test' }],
    stream: true,
  });

  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content || '');
  }
  ```

  ```curl REST theme={null}
  curl -X POST "https://api.portkey.ai/v1/chat/completions" \
       -H "Content-Type: application/json" \
       -H "Authorization: Bearer YOUR_PORTKEY_API_KEY" \
       -d '{
         "model": "llama3.1-8b-instruct",
         "messages": [{"role": "user", "content": "Say this is a test"}],
         "stream": true
       }'
  ```
</CodeGroup>

### Function Calling

Leverage Lambda's function calling capabilities through Portkey:

<CodeGroup>
  ```javascript Node.js theme={null}
  let tools = [{
      type: "function",
      function: {
          name: "getWeather",
          description: "Get the current weather",
          parameters: {
              type: "object",
              properties: {
                  location: { type: "string", description: "City and state" },
                  unit: { type: "string", enum: ["celsius", "fahrenheit"] }
              },
              required: ["location"]
          }
      }
  }];

  let response = await portkey.chat.completions.create({
      model: "llama3.1-8b-instruct",
      messages: [
          { role: "system", content: "You are a helpful assistant." },
          { role: "user", content: "What's the weather like in Delhi - respond in JSON" }
      ],
      tools,
      tool_choice: "auto",
  });

  console.log(response.choices[0].finish_reason);
  ```

  ```python Python theme={null}
  tools = [{
      "type": "function",
      "function": {
          "name": "getWeather",
          "description": "Get the current weather",
          "parameters": {
              "type": "object",
              "properties": {
                  "location": {"type": "string", "description": "City and state"},
                  "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
              },
              "required": ["location"]
          }
      }
  }]

  response = portkey.chat.completions.create(
      model="llama3.1-8b-instruct",
      messages=[
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "What's the weather like in Delhi - respond in JSON"}
      ],
      tools=tools,
      tool_choice="auto"
  )

  print(response.choices[0].finish_reason)
  ```

  ```curl REST theme={null}
  curl -X POST "https://api.portkey.ai/v1/chat/completions" \
       -H "Content-Type: application/json" \
       -H "Authorization: Bearer YOUR_PORTKEY_API_KEY" \
       -d '{
         "model": "llama3.1-8b-instruct",
         "messages": [
           {"role": "system", "content": "You are a helpful assistant."},
           {"role": "user", "content": "What'\''s the weather like in Delhi - respond in JSON"}
         ],
         "tools": [{
           "type": "function",
           "function": {
             "name": "getWeather",
             "description": "Get the current weather",
             "parameters": {
               "type": "object",
               "properties": {
                 "location": {"type": "string", "description": "City and state"},
                 "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
               },
               "required": ["location"]
             }
           }
         }],
         "tool_choice": "auto"
       }'
  ```
</CodeGroup>

# Portkey's Advanced Features

## Track End-User IDs

Portkey allows you to track user IDs passed with the user parameter in Lambda requests, enabling you to monitor user-level costs, requests, and more:

<CodeGroup>
  ```python Python theme={null}
  response = portkey.chat.completions.create(
    model="llama3.1-8b-instruct",
    messages=[{"role": "user", "content": "Say this is a test"}],
    user="user_123456"
  )
  ```

  ```javascript Node.js theme={null}
  const chatCompletion = await portkey.chat.completions.create({
    messages: [{ role: "user", content: "Say this is a test" }],
    model: "llama3.1-8b-instruct",
    user: "user_12345",
  });
  ```

  ```curl REST theme={null}
  curl -X POST "https://api.portkey.ai/v1/chat/completions" \
       -H "Content-Type: application/json" \
       -H "Authorization: Bearer YOUR_PORTKEY_API_KEY" \
       -d '{
         "model": "llama3.1-8b-instruct",
         "messages": [{"role": "user", "content": "Say this is a test"}],
         "user": "user_123456"
       }'
  ```
</CodeGroup>

When you include the user parameter in your requests, Portkey logs will display the associated user ID, as shown in the image below:

<img src="https://mintcdn.com/portkey-docs-add-third-party-integration-issues-fixes/iw8u5vDH8VX-5kWU/images/llms/logs.png?fit=max&auto=format&n=iw8u5vDH8VX-5kWU&q=85&s=c85197f222edf9b6195c6874462c0bfc" alt="Portkey Logs with User ID" width="968" height="668" data-path="images/llms/logs.png" />

In addition to the `user` parameter, Portkey allows you to send arbitrary custom metadata with your requests. This powerful feature enables you to associate additional context or information with each request, which can be useful for analysis, debugging, or other custom use cases.

<CardGroup cols={1}>
  <Card title="Learn More About Metadata" icon="tags" href="/product/observability/metadata">
    Explore how to use custom metadata to enhance your request tracking and analysis.
  </Card>
</CardGroup>

## Using The Gateway Config

Here's a simplified version of how to use Portkey's Gateway Configuration:

<Steps>
  <Step title="Create a Gateway Configuration" titleSize="h3">
    You can create a Gateway configuration using the Portkey Config Dashboard or by writing a JSON configuration in your code. In this example, requests are routed based on the user's subscription plan (paid or free).

    ```json theme={null}
    config = {
      "strategy": {
        "mode": "conditional",
        "conditions": [
          {
            "query": { "metadata.user_plan": { "$eq": "paid" } },
            "then": "llama3.1"
          },
          {
            "query": { "metadata.user_plan": { "$eq": "free" } },
            "then": "gpt-3.5"
          }
        ],
        "default": "gpt-3.5"
      },
      "targets": [
        {
          "name": "llama3.1",
          "virtual_key": "xx"
        },
        {
          "name": "gpt-3.5",
          "virtual_key": "yy"
        }
      ]
    }
    ```
  </Step>

  <Step title="Process Requests" titleSize="h3">
    When a user makes a request, it will pass through Portkey's AI Gateway. Based on the configuration, the Gateway routes the request according to the user's metadata.

    <img src="https://mintcdn.com/portkey-docs-add-third-party-integration-issues-fixes/iw8u5vDH8VX-5kWU/images/llms/conditional-routing.png?fit=max&auto=format&n=iw8u5vDH8VX-5kWU&q=85&s=6a83d472d7eeadae87edf5860c70aa5f" alt="Conditional Routing Diagram" width="1094" height="726" data-path="images/llms/conditional-routing.png" />
  </Step>

  <Step title="Set Up the Portkey Client" titleSize="h3">
    Pass the Gateway configuration to your Portkey client. You can either use the config object or the Config ID from Portkey's hosted version.

    <CodeGroup>
      ```python Python theme={null}
      from portkey_ai import Portkey

      portkey = Portkey(
          api_key="PORTKEY_API_KEY",
          virtual_key="VIRTUAL_KEY",
          config=portkey_config
      )
      ```

      ```javascript Node.js theme={null}
      import Portkey from 'portkey-ai'

      const portkey = new Portkey({
        apiKey: "PORTKEY_API_KEY",
        virtualKey: "VIRTUAL_KEY",
        config: portkeyConfig
      })
      ```
    </CodeGroup>
  </Step>
</Steps>

That's it! Portkey seamlessly allows you to make your AI app more robust using built-in gateway features. Learn more about advanced gateway features:

<CardGroup cols={2}>
  <Card title="Load Balancing" icon="link" href="/product/ai-gateway/load-balancing">
    Distribute requests across multiple targets based on defined weights.
  </Card>

  <Card title="Fallbacks" icon="life-ring" href="/product/ai-gateway/fallbacks">
    Automatically switch to backup targets if the primary target fails.
  </Card>

  <Card title="Conditional Routing" icon="route" href="/product/ai-gateway/conditional-routing">
    Route requests to different targets based on specified conditions.
  </Card>

  <Card title="Caching" icon="database" href="/product/ai-gateway/cache-simple-and-semantic">
    Enable caching of responses to improve performance and reduce costs.
  </Card>
</CardGroup>

## Guardrails

Portkey's AI gateway enables you to enforce input/output checks on requests by applying custom hooks before and after processing. Protect your user's/company's data by using PII guardrails and many more available on Portkey Guardrails:

```json theme={null}
{
	"virtual_key":"lambda-xxx",
	"before_request_hooks": [{
		"id": "input-guardrail-id-xx"
	}],
	"after_request_hooks": [{
		"id": "output-guardrail-id-xx"
	}]
}
```

<Card title="Learn More About Guardrails" icon="shield-check" href="/product/guardrails">
  Explore Portkey's guardrail features to enhance the security and reliability of your AI applications.
</Card>

## Next Steps

The complete list of features supported in the SDK are available in our comprehensive documentation:

<Card title="Portkey SDK Documentation" icon="book-open" href="/api-reference/portkey-sdk-client">
  Explore the full capabilities of the Portkey SDK and how to leverage them in your projects.
</Card>

***

For the most up-to-date information on supported features and endpoints, please refer to our [API Reference](/docs/api-reference/introduction).
