Skip to content

Commit 07761b3

Browse files
authored
Merge pull request #23 from Azure-Samples/langchainv1
Add Langchain v1 examples
2 parents ec7b0db + 542dc7f commit 07761b3

16 files changed

+726
-91
lines changed

AGENTS.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,16 @@ All examples should be the same functionally across english and spanish,
77
with the prompts and data in the respective language.
88

99
All examples should support Azure OpenAI, GitHub Models, and Ollama.
10+
11+
When running Python examples, always run them from inside the .venv virtual environment.
12+
You can activate it with:
13+
14+
```bash
15+
source .venv/bin/activate
16+
```
17+
18+
Or you can run python commands inside the .venv with:
19+
20+
```bash
21+
.venv/bin/python <your_script.py>
22+
```

README.md

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,26 +87,63 @@ A related option is VS Code Dev Containers, which will open the project in your
8787

8888
You can run the examples in this repository by executing the scripts in the `examples` directory. Each script demonstrates a different AI agent pattern or framework.
8989

90+
### Autogen
91+
9092
| Example | Description |
9193
| ------- | ----------- |
9294
| [autogen_basic.py](examples/autogen_basic.py) | Uses AutoGen to build a single agent. |
9395
| [autogen_tools.py](examples/autogen_tools.py) | Uses AutoGen to build a single agent with tools. |
9496
| [autogen_magenticone.py](examples/autogen_magenticone.py) | Uses AutoGen with the MagenticOne orchestrator agent for travel planning. |
9597
| [autogen_swarm.py](examples/autogen_swarm.py) | Uses AutoGen with the Swarm orchestrator agent for flight refunding requests. |
96-
| [langgraph_agent.py](examples/langgraph_agent.py) | Uses LangGraph to build an agent with a StateGraph to play songs. |
97-
| [llamaindex.py](examples/llamaindex.py) | Uses LlamaIndex to build a ReAct agent for RAG on multiple indexes. |
98+
99+
### Langchain v1 and LangGraph
100+
101+
| Example | Description |
102+
| ------- | ----------- |
103+
| [langchainv1_basic.py](examples/langchainv1_basic.py) | Uses LangChain v1 to build a basic informational agent. |
104+
| [langchainv1_tool.py](examples/langchainv1_tool.py) | Uses LangChain v1 to build an agent with a single weather tool. |
105+
| [langchainv1_tools.py](examples/langchainv1_tools.py) | Uses LangChain v1 to build a weekend planning agent with multiple tools. |
106+
| [langchainv1_supervisor.py](examples/langchainv1_supervisor.py) | Uses LangChain v1 with a supervisor orchestrating activity and recipe sub-agents. |
107+
| [langchainv1_quickstart.py](examples/langchainv1_quickstart.py) | Uses LangChain v1 to build an assistant with tool calling, structured output, and memory. Based off official Quickstart docs. |
108+
| [langgraph_agent.py](examples/langgraph_agent.py) | Builds LangGraph graph for an agent to play songs. |
109+
| [langgraph_mcp_http.py](examples/langgraph_mcp_http.py) | Uses LangGraph with ReAct agent that uses tools from local MCP HTTP server. |
110+
| [langgraph_mcp_http_graph.py](examples/langgraph_mcp_http_graph.py) | Builds a custom LangGraph state graph using tools from local MCP HTTP server. |
111+
| [langgraph_mcp_github.py](examples/langgraph_mcp_github.py) | Uses a LangGraph with agent and GitHub MCP server to triage repository issues. |
112+
113+
### OpenAI and OpenAI-Agents
114+
115+
| Example | Description |
116+
| ------- | ----------- |
117+
| [openai_githubmodels.py](examples/openai_githubmodels.py) | Basic setup for using GitHub models with the OpenAI API. |
118+
| [openai_functioncalling.py](examples/openai_functioncalling.py) | Uses OpenAI Function Calling to call functions based on LLM output. |
98119
| [openai_agents_basic.py](examples/openai_agents_basic.py) | Uses the OpenAI Agents framework to build a single agent. |
99120
| [openai_agents_handoffs.py](examples/openai_agents_handoffs.py) | Uses the OpenAI Agents framework to handoff between several agents with tools. |
100121
| [openai_agents_tools.py](examples/openai_agents_tools.py) | Uses the OpenAI Agents framework to build a weekend planner with tools. |
101-
| [openai_functioncalling.py](examples/openai_functioncalling.py) | Uses OpenAI Function Calling to call functions based on LLM output. |
102-
| [openai_githubmodels.py](examples/openai_githubmodels.py) | Basic setup for using GitHub models with the OpenAI API. |
122+
| [openai_agents_mcp_http.py](examples/openai_agents_mcp_http.py) | Uses the OpenAI Agents framework with an MCP HTTP server (travel planning tools). |
123+
124+
### PydanticAI
125+
126+
| Example | Description |
127+
| ------- | ----------- |
103128
| [pydanticai_basic.py](examples/pydanticai_basic.py) | Uses PydanticAI to build a basic single agent (Spanish tutor). |
104129
| [pydanticai_multiagent.py](examples/pydanticai_multiagent.py) | Uses PydanticAI to build a two-agent sequential workflow (flight + seat selection). |
105130
| [pydanticai_graph.py](examples/pydanticai_graph.py) | Uses PydanticAI with pydantic-graph to build a small question/answer evaluation graph. |
106131
| [pydanticai_tools.py](examples/pydanticai_tools.py) | Uses PydanticAI with multiple Python tools for weekend activity planning. |
107132
| [pydanticai_mcp_http.py](examples/pydanticai_mcp_http.py) | Uses PydanticAI with an MCP HTTP server toolset for travel planning (hotel search). |
133+
134+
### Semantic Kernel
135+
136+
| Example | Description |
137+
| ------- | ----------- |
108138
| [semantickernel_basic.py](examples/semantickernel_basic.py) | Uses Semantic Kernel to build a simple agent that teaches Spanish. |
109139
| [semantickernel_groupchat.py](examples/semantickernel_groupchat.py) | Uses Semantic Kernel to build a writer/editor two-agent workflow. |
140+
| [semantickernel_mcp_http.py](examples/semantickernel_mcp_http.py) | Uses Semantic Kernel agent with tools from a local MCP HTTP server for hotel search. |
141+
142+
### Other frameworks
143+
144+
| Example | Description |
145+
| ------- | ----------- |
146+
| [llamaindex.py](examples/llamaindex.py) | Uses LlamaIndex to build a ReAct agent for RAG on multiple indexes. |
110147
| [smolagents_codeagent.py](examples/smolagents_codeagent.py) | Uses SmolAgents to build a question-answering agent that can search the web and run code. |
111148

112149
## Configuring GitHub Models

examples/langchainv1_basic.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import os
2+
3+
import azure.identity
4+
from dotenv import load_dotenv
5+
from langchain.agents import create_agent
6+
from langchain_openai import AzureChatOpenAI, ChatOpenAI
7+
from rich import print
8+
9+
load_dotenv(override=True)
10+
API_HOST = os.getenv("API_HOST", "github")
11+
12+
if API_HOST == "azure":
13+
token_provider = azure.identity.get_bearer_token_provider(
14+
azure.identity.DefaultAzureCredential(),
15+
"https://cognitiveservices.azure.com/.default",
16+
)
17+
model = AzureChatOpenAI(
18+
azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
19+
azure_deployment=os.environ.get("AZURE_OPENAI_CHAT_DEPLOYMENT"),
20+
openai_api_version=os.environ.get("AZURE_OPENAI_VERSION"),
21+
azure_ad_token_provider=token_provider,
22+
)
23+
elif API_HOST == "github":
24+
model = ChatOpenAI(
25+
model=os.getenv("GITHUB_MODEL", "gpt-4o"),
26+
base_url="https://models.inference.ai.azure.com",
27+
api_key=os.environ.get("GITHUB_TOKEN"),
28+
)
29+
elif API_HOST == "ollama":
30+
model = ChatOpenAI(
31+
model=os.environ.get("OLLAMA_MODEL", "llama3.1"),
32+
base_url=os.environ.get("OLLAMA_ENDPOINT", "http://localhost:11434/v1"),
33+
api_key="none",
34+
)
35+
else:
36+
model = ChatOpenAI(model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"))
37+
38+
agent = create_agent(model=model, prompt="You're an informational agent. Answer questions cheerfully.", tools=[])
39+
40+
41+
def main():
42+
response = agent.invoke({"messages": [{"role": "user", "content": "Whats weather today in San Francisco?"}]})
43+
latest_message = response["messages"][-1]
44+
print(latest_message.content)
45+
46+
47+
if __name__ == "__main__":
48+
main()

examples/langchainv1_quickstart.py

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
"""LangChain v1 style weather agent example.
2+
https://docs.langchain.com/oss/python/langchain-quickstart
3+
4+
This example mirrors the pattern from the LangChain v1 Quickstart docs,
5+
adapted to this repo's multiple-provider model configuration.
6+
"""
7+
from __future__ import annotations
8+
9+
import os
10+
from dataclasses import dataclass
11+
12+
import azure.identity
13+
from dotenv import load_dotenv
14+
from langchain.agents import create_agent
15+
from langchain_core.runnables import RunnableConfig
16+
from langchain_core.tools import tool
17+
from langchain_openai import AzureChatOpenAI, ChatOpenAI
18+
from langgraph.checkpoint.memory import InMemorySaver
19+
from langgraph.runtime import get_runtime
20+
from rich import print
21+
22+
load_dotenv(override=True)
23+
API_HOST = os.getenv("API_HOST", "github")
24+
25+
if API_HOST == "azure":
26+
token_provider = azure.identity.get_bearer_token_provider(
27+
azure.identity.DefaultAzureCredential(),
28+
"https://cognitiveservices.azure.com/.default",
29+
)
30+
model = AzureChatOpenAI(
31+
azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
32+
azure_deployment=os.environ.get("AZURE_OPENAI_CHAT_DEPLOYMENT"),
33+
openai_api_version=os.environ.get("AZURE_OPENAI_VERSION"),
34+
azure_ad_token_provider=token_provider,
35+
)
36+
elif API_HOST == "github":
37+
model = ChatOpenAI(
38+
model=os.getenv("GITHUB_MODEL", "gpt-4o"),
39+
base_url="https://models.inference.ai.azure.com",
40+
api_key=os.environ.get("GITHUB_TOKEN"),
41+
)
42+
elif API_HOST == "ollama":
43+
model = ChatOpenAI(
44+
model=os.environ.get("OLLAMA_MODEL", "llama3.1"),
45+
base_url=os.environ.get("OLLAMA_ENDPOINT", "http://localhost:11434/v1"),
46+
api_key="none",
47+
)
48+
else:
49+
model = ChatOpenAI(model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"))
50+
51+
52+
system_prompt = """You are an expert weather forecaster, who speaks in puns.
53+
54+
You have access to two tools:
55+
56+
- get_weather_for_location: use this to get the weather for a specific location
57+
- get_user_location: use this to get the user's location
58+
59+
If a user asks you for the weather, make sure you know the location.
60+
If you can tell from the question that they mean whereever they are,
61+
use the get_user_location tool to find their location."""
62+
63+
# Mock user locations keyed by user id (string)
64+
USER_LOCATION = {
65+
"1": "Florida",
66+
"2": "SF",
67+
}
68+
69+
70+
@dataclass
71+
class UserContext:
72+
user_id: str
73+
74+
75+
@tool
76+
def get_weather(city: str) -> str:
77+
"""Get weather for a given city."""
78+
return f"It's always sunny in {city}!"
79+
80+
81+
@tool
82+
def get_user_info(config: RunnableConfig) -> str:
83+
"""Retrieve user information based on user ID."""
84+
runtime = get_runtime(UserContext)
85+
user_id = runtime.context.user_id
86+
return USER_LOCATION[user_id]
87+
88+
89+
@dataclass
90+
class WeatherResponse:
91+
conditions: str
92+
punny_response: str
93+
94+
95+
checkpointer = InMemorySaver()
96+
97+
agent = create_agent(
98+
model=model,
99+
prompt=system_prompt,
100+
tools=[get_user_info, get_weather],
101+
response_format=WeatherResponse,
102+
checkpointer=checkpointer,
103+
)
104+
105+
106+
def main():
107+
config = {"configurable": {"thread_id": "1"}}
108+
context = UserContext(user_id="1")
109+
110+
r1 = agent.invoke(
111+
{"messages": [{"role": "user", "content": "what is the weather outside?"}]}, config=config, context=context
112+
)
113+
print(r1.get("structured_response"))
114+
115+
r2 = agent.invoke(
116+
{"messages": [{"role": "user", "content": "Thanks"}]},
117+
config=config,
118+
context=context,
119+
)
120+
print(r2.get("structured_response"))
121+
122+
123+
if __name__ == "__main__":
124+
main()

0 commit comments

Comments
 (0)