Issue Connecting to Azure OpenAI with CrewAI and LangChain
Hello all,
I dont know why in documentation they mentioned it will support Azure openAI but didnt even mention how to connect it. I like to know connection with azure they said will work or is it just fake ?
I’ve been trying to connect to Azure OpenAI using the following code, but I keep running into errors. No matter what I try, I can’t seem to get it to work. Can anyone guide me on what I’m doing wrong?
Code Snippet
from crewai import Agent, Task, Crew, Process
from crewai_tools import YoutubeChannelSearchTool
from langchain_openai import AzureChatOpenAI
from dotenv import load_dotenv
import os
load_dotenv()
# Setting up Azure OpenAI
model = "gpt-4o"
api_key = "YOUR_AZURE_OPENAI_API_KEY"
api_version = "2024-05-01-preview"
base_url = "https://your-openai-instance.openai.azure.com/"
azure_llm = AzureChatOpenAI(
azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
api_key=os.environ.get("AZURE_OPENAI_KEY"),
api_version=os.environ.get("AZURE_OPENAI_VERSION"),
)
# Initializing the YouTube Channel Search Tool
yt_tool = YoutubeChannelSearchTool(youtube_channel_handle="@zackdfilms")
# Agents
blog_researcher = Agent(
role="Blog Creator from YouTube Videos",
goal="Get the relevant video content for the topic {topic} from YouTube channel",
verbose=True,
memory=True,
backstory=(
"Expert in understanding videos in crime, fun, and entertainment and providing suggestions"
),
tools=[yt_tool],
allow_delegation=True,
llm=azure_llm
)
Error Message
api_key = self.config.api_key or os.environ["OPENAI_API_KEY"]
~~~~~~~~~~^^^^^^^^^^^^^^^^^^
File "<frozen os>", line 714, in __getitem__
KeyError: 'OPENAI_API_KEY'
What I’ve Tried
- Setting environment variables correctly in the
.env
file:AZURE_OPENAI_ENDPOINT=https://your-openai-instance.openai.azure.com/ AZURE_OPENAI_KEY=your-api-key AZURE_OPENAI_VERSION=2024-05-01-preview
- Verifying that the
dotenv
package is loading environment variables correctly. - Explicitly passing
api_key="your-api-key"
instead of relying onos.environ.get()
. - Checking if the
AzureChatOpenAI
class expectsOPENAI_API_KEY
instead ofAZURE_OPENAI_KEY
.
Would appreciate any guidance! Thanks in advance.