Skip to content

Commit 32fd49e

Browse files
authored
Merge pull request #3 from pamelafox/langchain
Adding Langchain example
2 parents 9f4b12c + 2918730 commit 32fd49e

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Plus these scripts to demonstrate additional features:
1313

1414
5. [`chat_safety.py`](./chat_safety.py): The simple script with exception handling for Azure AI Content Safety filter errors.
1515
6. [`chat_async.py`](./chat_async.py): Uses the async clients to make asynchronous calls, including an example of sending off multiple requests at once using `asyncio.gather`.
16+
6. [`chat_langchain.py`](./chat_langchain.py): Uses the langchain SDK to generate chat completions. [Learn more from Langchain docs](https://python.langchain.com/docs/get_started/quickstart)
1617

1718
## Setting up the environment
1819

@@ -62,3 +63,5 @@ depending on the environment variables you set.
6263
OLLAMA_ENDPOINT=http://localhost:11434/v1
6364
OLLAMA_MODEL=llama2
6465
```
66+
67+
If you're running inside the Dev Container, replace `localhost` with `host.docker.internal`.

chat_langchain.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import os
2+
3+
import azure.identity
4+
from dotenv import load_dotenv
5+
from langchain_core.prompts import ChatPromptTemplate
6+
from langchain_openai import AzureChatOpenAI, ChatOpenAI
7+
8+
# Setup the OpenAI client to use either Azure, OpenAI.com, or Ollama API
9+
load_dotenv(override=True)
10+
API_HOST = os.getenv("API_HOST")
11+
12+
if API_HOST == "azure":
13+
token_provider = azure.identity.get_bearer_token_provider(
14+
azure.identity.DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
15+
)
16+
llm = AzureChatOpenAI(
17+
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
18+
azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT"),
19+
openai_api_version=os.getenv("AZURE_OPENAI_VERSION"),
20+
azure_ad_token_provider=token_provider,
21+
)
22+
elif API_HOST == "ollama":
23+
llm = ChatOpenAI(
24+
model_name=os.getenv("OLLAMA_MODEL"),
25+
openai_api_base=os.getenv("OLLAMA_ENDPOINT"),
26+
openai_api_key=os.getenv("OPENAI_KEY"),
27+
)
28+
else:
29+
llm = ChatOpenAI(model_name=os.getenv("OPENAI_MODEL"), openai_api_key=os.getenv("OPENAI_KEY"))
30+
31+
32+
prompt = ChatPromptTemplate.from_messages(
33+
[("system", "You are a helpful assistant that makes lots of cat references and uses emojis."), ("user", "{input}")]
34+
)
35+
chain = prompt | llm
36+
response = chain.invoke({"input": "write a haiku about a hungry cat that wants tuna"})
37+
38+
print(f"Response from {API_HOST}: \n")
39+
print(response.content)

0 commit comments

Comments
 (0)