> ## Documentation Index
> Fetch the complete documentation index at: https://docs.helicone.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Azure OpenAI with LangChain

> Use LangChain to integrate Azure OpenAI with Helicone to log your Azure OpenAI usage.

export const strings = {
  additionalHeadersForSessions: "Helicone provides additional headers to help you manage and analyze your sessions.",
  azureOpenAIDocs: `To learn more about the differences between OpenAI and AzureOpenAI, review the <a href="https://learn.microsoft.com/en-us/azure/ai-services/openai/overview">documentation here</a>.`,
  chainOfThoughtPromptingCookbookDescription: "Craft effective prompts, ideal for complex responses requiring multi-step problem solving.",
  chatbotCookbookDescription: "This step-by-step guide covers function calling, response formatting and monitoring with Helicone.",
  createHeliconeManualLogger: "Create a new HeliconeManualLogger instance",
  configureWebSocketConnection: "Configure WebSocket connection",
  environmentTrackingCookbookDescription: "Effortlessly track and manage your environments with Helicone across different deployment contexts.",
  exportBaseUrl: tool => `Export your ${tool} base URL`,
  getStartedWithPackage: "To get started, install the @helicone/helpers package",
  generateKey: "Create an account and generate an API key",
  generateKeyInstructions: `Log into <a href="https://www.helicone.ai" target="_blank">Helicone</a> or create an account. Once you have an account, you can generate an <a href="https://helicone.ai/developer" target="_blank">API key here</a>.`,
  generateSessionId: "Generate the unique session ID that will be used to track the session.",
  gettingUserRequestsCookbookDescription: "Retrieve user-specific requests to monitor, debug, and track costs for individual users.",
  githubActionsCookbookDescription: "Automate the monitoring and caching of your LLM calls in your CI pipelines for better deployment processes.",
  groupingCallsWithSessions: "Grouping Calls with Helicone Sessions",
  handleWebSocketEvents: "Handle WebSocket events",
  heliconeLoggerAPIReference: `To learn more about the <code>HeliconeManualLogger</code> API, see the <a href="/getting-started/integration-method/custom" target="_blank">API Reference here</a>.`,
  howToIntegrate: "How to Integrate",
  howToPromptThinkingModelsCookbookDescription: "Best practices to to effectively prompt thinking models like Deepseek and OpenAI o1-o3 for optimal results.",
  howToUseSessions: "To group related API calls and analyze them collectively, you can use Helicone's session tracking features. This is useful for grouping all interactions within a single conversation or user session.",
  includeHeadersInRequests: "Include headers in your requests",
  includeSessionHeaders: "Include the session headers when you make API requests. This way, the session information is attached to each request, allowing Helicone to group and analyze them together.",
  installRequiredDependencies: "Install required dependencies",
  installSDK: tool => `Install ${tool}`,
  logYourRequest: "Log your request",
  modelRegistryDescription: "You can find all 100+ supported models at <a href=\"https://helicone.ai/models\" target=\"_blank\">helicone.ai/models</a>.",
  modifyBasePath: "Modify the base URL path",
  optional: "Optional",
  relatedGuides: "Related Guides",
  replayLlmSessionsCookbookDescription: "Learn how to replay and modify LLM sessions using Helicone to optimize your AI agents and improve their performance.",
  sessionManagement: "Session Management",
  setApiKey: "Set up your Helicone API key in your .env file",
  setUpToolBaseUrl: tool => `Set up your ${tool} base URL`,
  setUpToolApiKey: tool => `Set up your ${tool} API key as an environment variable`,
  startUsing: tool => `Start using ${tool} with Helicone`,
  useTheSDK: tool => `Use the ${tool} SDK`,
  verifyInHelicone: "Verify your requests in Helicone",
  verifyInHeliconeDesciption: tool => `With the above setup, any calls to ${tool} will automatically be logged and monitored by Helicone. Review them in your <a href="https://www.helicone.ai/dashboard" target="_blank">Helicone dashboard</a>.`,
  viewRequestsInDashboard: "View requests in the Helicone dashboard",
  viewRequestsInDashboardDescription: product => `All your ${product} requests are now visible in your <a href="https://us.helicone.ai/dashboard" target="_blank">Helicone dashboard</a>.`,
  whyUseSessions: "By including the session headers in each request, you have more granular control over session tracking. This approach is especially useful if you want to handle sessions dynamically or manage multiple sessions concurrently."
};

<Warning>
  This integration method is maintained but no longer actively developed. For the best experience and latest features, use our new [AI Gateway](/gateway/overview) with unified API access to 100+ models.
</Warning>

## {strings.howToIntegrate}

<Steps>
  <Step title={strings.generateKey}>
    <div dangerouslySetInnerHTML={{ __html: strings.generateKeyInstructions }} />
  </Step>

  <Step title={strings.setApiKey}>
    ```javascript theme={null}
    HELICONE_API_KEY=<YOUR_HELICONE_API_KEY>
    AZURE_OPENAI_API_KEY=<YOUR_AZURE_OPENAI_API_KEY>
    ```
  </Step>

  <Step title={strings.modifyBasePath}>
    <Note>
      Make sure to include the <code>api-version</code> in all of your requests.
    </Note>

    <CodeGroup>
      ```javascript ChatOpenAI js theme={null}
      const model = new ChatOpenAI({
        baseURL: "https://oai.helicone.ai/v1",
        defaultHeaders: {
          "Helicone-Auth": `Bearer ${process.env.HELICONE_API_KEY}`,
          "Helicone-OpenAI-Api-Base": "https://[AZURE_DOMAIN].azure.com/",
          "api-key": process.env.AZURE_OPENAI_API_KEY
        },
        model: "[MODEL_NAME]", // eg "gpt-4o-mini"
        apiVersion: "[API_VERSION]" // eg "2023-05-15"
      });
      ```

      ```javascript AzureChatOpenAI js theme={null}
      const model = new AzureChatOpenAI({
        model: "[MODEL_NAME]",
        azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,
        azureOpenAIApiInstanceName: "[AZURE_DOMAIN_NAME]", // "july-mb1z0q9z-eastus2"
        azureOpenAIApiDeploymentName: "[DEPLOYMENT_NAME]",
        azureOpenAIApiVersion: "[API_VERSION]", // "2023-05-15"
        defaultHeaders: {
          "Helicone-Auth": `Bearer ${process.env.HELICONE_API_KEY}`,
          "Helicone-OpenAI-Api-Base":
            "https://[AZURE_DOMAIN].azure.com/",
          "api-key": process.env.AZURE_OPENAI_API_KEY
        }
      });
      ```

      ```python AzureChatOpenAI py theme={null}
      from langchain.chat_models import AzureChatOpenAI
      from dotenv import load_dotenv
      import os

      load_dotenv()

      HELICONE_API_KEY = os.getenv("HELICONE_API_KEY")
      AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY")

      helicone_headers = {
        "Helicone-Auth": f"Bearer {HELICONE_API_KEY}",
        "Helicone-OpenAI-Api-Base": "https://[YOUR_AZURE_DOMAIN].azure.com/",
        "Helicone-Model-Override": "[MODEL_NAME]", # "gpt-35-turbo"
        # ...additional headers
      }

      self.model = AzureChatOpenAI(
        openai_api_base="https://oai.helicone.ai",
        deployment_name="[DEPLOYMENT_NAME]",
        openai_api_key=f"{AZURE_OPENAI_API_KEY}",
        openai_api_version="[API_VERSION]", # "2023-05-15"
        openai_api_type="azure",
        max_retries=max_retries,
        headers=helicone_headers,
        **kwargs
      )
      ```
    </CodeGroup>

    <Info>
      <b>Recomendation: Model Override</b>

      When using Azure, the model displays differently than expected at times. We have implemented logic to parse out the model, but if you want to guarantee your model is consistent, we highly recommend using model override:

      <code>Helicone-Model-Override: \[MODEL\_NAME]</code>

      <br />

      <br />

      <a href="/helicone-headers/header-directory#param-helicone-model-override"> Click here to learn more about model override</a>
    </Info>
  </Step>

  <Step title={strings.startUsing("Azure OpenAI")}>
    <CodeGroup>
      ```javascript javascript theme={null}
      const response = await model.invoke("What is the meaning of life?");
      console.log(response);
      ```

      ```python python theme={null}
      response = model.invoke("What is the meaning of life?")
      print(response)
      ```
    </CodeGroup>
  </Step>

  <Step title={strings.verifyInHelicone}>
    <div dangerouslySetInnerHTML={{ __html: strings.verifyInHeliconeDesciption("Azure OpenAI") }} />
  </Step>
</Steps>

<div dangerouslySetInnerHTML={{ __html: strings.azureOpenAIDocs }} />

## {strings.relatedGuides}

<CardGroup cols={2}>
  <Card title="How to Prompt Thinking Models" icon="brain" href="/guides/cookbooks/prompt-thinking-models" iconType="light" vertical>
    {strings.howToPromptThinkingModelsCookbookDescription}
  </Card>

  <Card title="Getting User Requests" icon="user" href="/guides/cookbooks/getting-user-requests" iconType="light" vertical>
    {strings.gettingUserRequestsCookbookDescription}
  </Card>
</CardGroup>
