Skip to content

Commit c5ae9d3

Browse files
committed
add reflection agent
1 parent 7fc1c35 commit c5ae9d3

File tree

5 files changed

+136
-0
lines changed

5 files changed

+136
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ Here are the preferred tools for development.
4141
| [9_streamlit_azure_document_intelligence](./apps/9_streamlit_azure_document_intelligence/README.md) | Call Azure AI Document Intelligence API with Streamlit | ![9_streamlit_azure_document_intelligence](./docs/images/9_streamlit_azure_document_intelligence.main.png) |
4242
| [10_streamlit_batch_transcription](./apps/10_streamlit_batch_transcription/README.md) | Call Batch Transcription API with Streamlit | ![10_streamlit_batch_transcription](./docs/images/10_streamlit_batch_transcription.main.png) |
4343
| [11_promptflow](./apps/11_promptflow/README.md) | Get started with Prompt flow | No Image |
44+
| [12_langgraph_agent](./apps/12_langgraph_agent/README.md) | Create agents with LangGraph | No Image |
4445
| [99_streamlit_examples](./apps/99_streamlit_examples/README.md) | Code samples for Streamlit | ![99_streamlit_examples](./docs/images/99_streamlit_examples.explaindata.png) |
4546

4647
## How to run

apps/12_langgraph_agent/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Create agents with LangGraph
2+
3+
This app demonstrates how to implement agents with LangGraph.
4+
5+
## Prerequisites
6+
7+
- Python 3.10 or later
8+
- Azure OpenAI Service
9+
10+
## Overview
11+
12+
**What is [LangGraph](https://langchain-ai.github.io/langgraph/)?**
13+
14+
LangGraph is a library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows.
15+
16+
This chapter provides a practical example of how to use LangGraph to create an agent that can interact with users and external tools.
17+
18+
## Usage
19+
20+
1. Get Azure OpenAI Service API key
21+
1. Copy [.env.template](../../.env.template) to `.env` in the same directory
22+
1. Set credentials in `.env`
23+
1. Run main.py
24+
25+
```shell
26+
# Create a virtual environment
27+
$ python -m venv .venv
28+
29+
# Activate the virtual environment
30+
$ source .venv/bin/activate
31+
32+
# Install dependencies
33+
$ pip install -r requirements.txt
34+
35+
# Run the script
36+
$ python apps/12_langgraph_agent/reflection_agent/main.py
37+
```
38+
39+
### Example
40+
41+
## References
42+
43+
- [LangGraph](https://langchain-ai.github.io/langgraph/)
44+
- [Udemy > LangGraph- Develop LLM powered agents with LangGraph](https://www.udemy.com/course/langgraph)
45+
- [Prompt flow > Tracing](https://microsoft.github.io/promptflow/how-to-guides/tracing/index.html)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from os import getenv
2+
3+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
4+
from langchain_openai import AzureChatOpenAI
5+
6+
reflection_prompt = ChatPromptTemplate.from_messages(
7+
[
8+
(
9+
"system",
10+
"You are a viral twitter influencer grading a tweet. Generate critique and recommendations for the user's tweet." # noqa
11+
"Always provide detailed recommendations, including requests for length, virality, style, etc.", # noqa
12+
),
13+
MessagesPlaceholder(variable_name="messages"),
14+
]
15+
)
16+
17+
generation_prompt = ChatPromptTemplate.from_messages(
18+
[
19+
(
20+
"system",
21+
"You are a twitter techie influencer assistant tasked with writing excellent twitter posts."
22+
" Generate the best twitter post possible for the user's request."
23+
" If the user provides critique, respond with a revised version of your previous attempts.", # noqa
24+
),
25+
MessagesPlaceholder(variable_name="messages"),
26+
]
27+
)
28+
29+
30+
llm = AzureChatOpenAI(
31+
temperature=0,
32+
api_key=getenv("AZURE_OPENAI_API_KEY"),
33+
api_version=getenv("AZURE_OPENAI_API_VERSION"),
34+
azure_endpoint=getenv("AZURE_OPENAI_ENDPOINT"),
35+
model=getenv("AZURE_OPENAI_GPT_MODEL"),
36+
)
37+
38+
generate_chain = generation_prompt | llm
39+
reflect_chain = reflection_prompt | llm
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from collections.abc import Sequence
2+
3+
from chains import generate_chain, reflect_chain
4+
from dotenv import load_dotenv
5+
from langchain_core.messages import BaseMessage, HumanMessage
6+
from langgraph.graph import END, MessageGraph
7+
from promptflow.tracing import start_trace
8+
9+
load_dotenv()
10+
start_trace()
11+
12+
13+
REFLECT = "reflect"
14+
GENERATE = "generate"
15+
16+
17+
def generation_node(state: Sequence[BaseMessage]):
18+
return generate_chain.invoke({"messages": state})
19+
20+
21+
def reflection_node(messages: Sequence[BaseMessage]) -> list[BaseMessage]:
22+
res = reflect_chain.invoke({"messages": messages})
23+
return [HumanMessage(content=res.content)]
24+
25+
26+
builder = MessageGraph()
27+
builder.add_node(GENERATE, generation_node)
28+
builder.add_node(REFLECT, reflection_node)
29+
builder.set_entry_point(GENERATE)
30+
31+
32+
def should_continue(state: list[BaseMessage]):
33+
if len(state) > 6:
34+
return END
35+
return REFLECT
36+
37+
38+
builder.add_conditional_edges(GENERATE, should_continue)
39+
builder.add_edge(REFLECT, GENERATE)
40+
41+
graph = builder.compile()
42+
print(graph.get_graph().draw_mermaid())
43+
# graph.get_graph().print_ascii()
44+
45+
if __name__ == "__main__":
46+
inputs = HumanMessage(
47+
content="""Make this tweet better:"
48+
Microsoft's Azure OpenAI API is a game-changer for developers."""
49+
)
50+
response = graph.invoke(inputs)

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ azure-storage-blob==12.22.0
1414
requests==2.32.3
1515
promptflow==1.15.0
1616
promptflow-evals==0.3.2
17+
langgraph==0.2.23
1718

1819
# To run 99_streamlit_examples/pages/10_Object_Detection.py
1920
# ultralytics==8.2.89

0 commit comments

Comments
 (0)