-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcel_structured_example.py
More file actions
292 lines (221 loc) · 8.42 KB
/
lcel_structured_example.py
File metadata and controls
292 lines (221 loc) · 8.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""
Alternative Implementation: Using LCEL and with_structured_output()
This shows the MODERN way to get structured outputs using LCEL chains.
Compare this to react_agent.py which uses the CLASSIC AgentExecutor pattern.
"""
from typing import List
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from langchain_core.prompts import ChatPromptTemplate
from langchain_ollama import ChatOllama
from langchain_core.runnables import RunnablePassthrough, RunnableLambda
from tavily import TavilyClient
load_dotenv()
tavily = TavilyClient()
# Define the structured output schema
class Source(BaseModel):
"""A source URL used to answer the query."""
url: str = Field(description="The URL of the source")
class ResearchResponse(BaseModel):
"""Structured response with answer and sources."""
answer: str = Field(description="The answer to the query")
sources: List[Source] = Field(description="List of sources used")
def search_tavily(query: str) -> dict:
"""Search using Tavily API."""
return tavily.search(query=query)
def format_search_results(search_response: dict) -> str:
"""Format Tavily search results into a readable string."""
results = search_response.get("results", [])
formatted = "Search Results:\n\n"
for i, result in enumerate(results[:5], 1):
formatted += f"{i}. {result['title']}\n"
formatted += f" URL: {result['url']}\n"
formatted += f" Content: {result['content']}\n\n"
return formatted
# ============================================================================
# APPROACH 1: Using with_structured_output() - RECOMMENDED FOR MODERN LANGCHAIN
# ============================================================================
def create_lcel_chain_with_structured_output():
"""
Creates an LCEL chain that returns structured output.
This demonstrates:
1. Building a chain BEFORE execution (not after)
2. Using with_structured_output() for guaranteed structure
3. Proper use of the pipe operator |
"""
# Initialize LLM
llm = ChatOllama(
model="qwen3:30b-a3b",
temperature=0.1
)
# Add structured output capability to the LLM
structured_llm = llm.with_structured_output(ResearchResponse)
# Create the prompt template
prompt = ChatPromptTemplate.from_messages([
("system", """You are a helpful research assistant.
Based on the search results provided, answer the user's query and list the sources you used.
Search Results:
{search_results}
"""),
("human", "{query}")
])
# Build the LCEL chain using pipe operator
# This is a RUNNABLE CHAIN - not executed until .invoke() is called
chain = (
{
"query": RunnablePassthrough(),
"search_results": RunnableLambda(search_tavily) | RunnableLambda(format_search_results)
}
| prompt
| structured_llm
)
return chain
# ============================================================================
# APPROACH 2: Manual Extraction (like react_agent.py)
# ============================================================================
def create_simple_chain_with_manual_extraction():
"""
Creates a chain without structured output, requiring manual extraction.
This is similar to what we did in react_agent.py - simpler but requires
post-processing to extract structured data.
"""
llm = ChatOllama(
model="qwen3:30b-a3b",
temperature=0.1
)
prompt = ChatPromptTemplate.from_messages([
("system", """You are a helpful research assistant.
Based on the search results provided, answer the user's query.
Make sure to mention which sources you used.
Search Results:
{search_results}
"""),
("human", "{query}")
])
# Simple chain without structured output
chain = (
{
"query": RunnablePassthrough(),
"search_results": RunnableLambda(search_tavily) | RunnableLambda(format_search_results)
}
| prompt
| llm
)
return chain
def extract_sources_manually(search_results: dict) -> List[Source]:
"""
Manually extract sources from search results.
This is POST-PROCESSING, not part of the LCEL chain.
"""
sources = []
for result in search_results.get("results", [])[:5]:
sources.append(Source(url=result["url"]))
return sources
# ============================================================================
# DEMO FUNCTIONS
# ============================================================================
def demo_structured_output():
"""
Demo: Using with_structured_output() for automatic structure.
"""
print("\n" + "="*70)
print("DEMO 1: LCEL Chain with with_structured_output()")
print("="*70)
# Build the chain (NOT executed yet - this is the key!)
chain = create_lcel_chain_with_structured_output()
# Now execute it
result = chain.invoke("What is the current price of Bitcoin?")
# result is automatically a ResearchResponse object!
print(f"\nType of result: {type(result)}")
print(f"\nAnswer: {result.answer}")
print(f"\nSources ({len(result.sources)}):")
for i, source in enumerate(result.sources, 1):
print(f" {i}. {source.url}")
def demo_manual_extraction():
"""
Demo: Manual extraction (similar to react_agent.py approach).
"""
print("\n" + "="*70)
print("DEMO 2: LCEL Chain with Manual Extraction")
print("="*70)
# Build the chain
chain = create_simple_chain_with_manual_extraction()
# Execute it
result = chain.invoke("What is the current price of Bitcoin?")
# result is a string, need to manually extract sources
print(f"\nType of result: {type(result)}")
print(f"\nAnswer: {result.content}")
# Manually get sources (this is POST-PROCESSING)
search_results = search_tavily("What is the current price of Bitcoin?")
sources = extract_sources_manually(search_results)
print(f"\nSources ({len(sources)}):")
for i, source in enumerate(sources, 1):
print(f" {i}. {source.url}")
# ============================================================================
# UNDERSTANDING THE DIFFERENCE
# ============================================================================
def explain_the_difference():
"""
Explains the key differences between the approaches.
"""
print("\n" + "="*70)
print("KEY DIFFERENCES EXPLAINED")
print("="*70)
print("""
Approach 1: with_structured_output()
-------------------------------------
✅ LLM automatically returns structured data
✅ Type-safe (Pydantic models)
✅ No manual parsing needed
✅ Clean and modern
❌ Only works with LLMs that support structured output
❌ Requires schema definition upfront
Usage:
chain = prompt | llm.with_structured_output(Schema)
result = chain.invoke(input) # result is Schema object
Approach 2: Manual Extraction
------------------------------
✅ Works with any LLM
✅ More control over extraction logic
✅ Can extract from intermediate steps (like react_agent.py)
❌ Requires manual processing
❌ More code
❌ Less type safety
Usage:
chain = prompt | llm
result = chain.invoke(input) # result is string/dict
structured = extract_manually(result) # manual processing
Your react_agent.py Issue:
---------------------------
❌ WRONG:
result = agent_executor.invoke(...) # ← Executed (returns dict)
chain = result | extract | format # ← Can't pipe dict!
✅ CORRECT (Post-processing):
result = agent_executor.invoke(...)
formatted = extract_sources_from_result(result)
✅ CORRECT (LCEL chain):
chain = prompt | llm | parser # ← Build chain first
result = chain.invoke(input) # ← Then execute
""")
# ============================================================================
# MAIN
# ============================================================================
def main():
"""Run all demos."""
# Explain the concepts
explain_the_difference()
# Demo 1: Structured output (modern approach)
demo_structured_output()
# Demo 2: Manual extraction (classic approach)
demo_manual_extraction()
print("\n" + "="*70)
print("Summary:")
print("="*70)
print("""
1. LCEL chains must be built BEFORE execution
2. Use with_structured_output() for automatic structure (modern)
3. Use manual extraction for classic patterns (like AgentExecutor)
4. Never try to pipe already-executed data (dict/string)
""")
if __name__ == "__main__":
main()