Skip to content

Commit 904c861

Browse files
committed
📦 NEW: Advanc Examples
1 parent 8dc6990 commit 904c861

26 files changed

+151
-64
lines changed

README.md

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -53,14 +53,14 @@ langbase_api_key = os.getenv("LANGBASE_API_KEY")
5353
llm_api_key = os.getenv("LLM_API_KEY")
5454

5555
# Initialize the client
56-
lb = Langbase(api_key=langbase_api_key)
56+
langbase = Langbase(api_key=langbase_api_key)
5757
```
5858

5959
### 3. Generate text
6060

6161
```python
6262
# Simple generation
63-
response = lb.agent.run(
63+
response = langbase.agent.run(
6464
input=[{"role": "user", "content": "Tell me about AI"}],
6565
model="openai:gpt-4.1-mini",
6666
api_key=llm_api_key,
@@ -148,10 +148,10 @@ runner.process()
148148

149149
```python
150150
# List all pipes
151-
pipes = lb.pipes.list()
151+
pipes = langbase.pipes.list()
152152

153153
# Run a pipe
154-
response = lb.pipes.run(
154+
response = langbase.pipes.run(
155155
name="ai-agent",
156156
messages=[{"role": "user", "content": "Hello!"}],
157157
variables={"style": "friendly"}, # Optional variables
@@ -163,21 +163,21 @@ response = lb.pipes.run(
163163

164164
```python
165165
# Create a memory
166-
memory = lb.memories.create(
166+
memory = langbase.memories.create(
167167
name="product-docs",
168168
description="Product documentation",
169169
)
170170

171171
# Upload documents
172-
lb.memories.documents.upload(
172+
langbase.memories.documents.upload(
173173
memory_name="product-docs",
174174
document_name="guide.pdf",
175175
document=open("guide.pdf", "rb"),
176176
content_type="application/pdf",
177177
)
178178

179179
# Retrieve relevant context
180-
results = lb.memories.retrieve(
180+
results = langbase.memories.retrieve(
181181
query="How do I get started?",
182182
memory=[{"name": "product-docs"}],
183183
top_k=3,
@@ -188,7 +188,7 @@ results = lb.memories.retrieve(
188188

189189
```python
190190
# Run an agent with tools
191-
response = lb.agent.run(
191+
response = langbase.agent.run(
192192
model="openai:gpt-4",
193193
messages=[{"role": "user", "content": "Search for AI news"}],
194194
tools=[{"type": "function", "function": {...}}],
@@ -202,20 +202,20 @@ response = lb.agent.run(
202202

203203
```python
204204
# Chunk text for processing
205-
chunks = lb.chunker(
205+
chunks = langbase.chunker(
206206
content="Long text to split...",
207207
chunk_max_length=1024,
208208
chunk_overlap=256,
209209
)
210210

211211
# Generate embeddings
212-
embeddings = lb.embed(
212+
embeddings = langbase.embed(
213213
chunks=["Text 1", "Text 2"],
214214
embedding_model="openai:text-embedding-3-small",
215215
)
216216

217217
# Parse documents
218-
content = lb.parser(
218+
content = langbase.parser(
219219
document=open("document.pdf", "rb"),
220220
document_name="document.pdf",
221221
content_type="application/pdf",

examples/agent/agent.run.typed.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
"""
2+
Run Agent
3+
4+
This example demonstrates how to run an agent with a Typed Stream
5+
"""
6+
7+
import os
8+
9+
from dotenv import load_dotenv
10+
11+
from langbase import Langbase, StreamEventType, get_typed_runner
12+
13+
load_dotenv()
14+
15+
16+
def main():
17+
# Check for required environment variables
18+
langbase_api_key = os.environ.get("LANGBASE_API_KEY")
19+
llm_api_key = os.environ.get("LLM_API_KEY")
20+
21+
if not langbase_api_key:
22+
print("❌ Missing LANGBASE_API_KEY in environment variables.")
23+
print("Please set: export LANGBASE_API_KEY='your_langbase_api_key'")
24+
exit(1)
25+
26+
if not llm_api_key:
27+
print("❌ Missing LLM_API_KEY in environment variables.")
28+
print("Please set: export LLM_API_KEY='your_llm_api_key'")
29+
exit(1)
30+
31+
# Initialize Langbase client
32+
langbase = Langbase(api_key=langbase_api_key)
33+
try:
34+
# Get streaming response
35+
response = langbase.agent.run(
36+
stream=True,
37+
model="openai:gpt-4.1-mini",
38+
api_key=llm_api_key,
39+
instructions="You are a helpful assistant that help users summarize text.",
40+
input=[{"role": "user", "content": "Who is an AI Engineer?"}],
41+
)
42+
43+
# Create typed stream processor
44+
runner = get_typed_runner(response)
45+
46+
# Register event handlers
47+
runner.on(
48+
StreamEventType.CONNECT,
49+
lambda event: print(f"✓ Connected! Thread ID: {event['threadId']}\n"),
50+
)
51+
52+
runner.on(
53+
StreamEventType.CONTENT,
54+
lambda event: print(event["content"], end="", flush=True),
55+
)
56+
57+
runner.on(
58+
StreamEventType.TOOL_CALL,
59+
lambda event: print(
60+
f"\n🔧 Tool call: {event['toolCall']['function']['name']}"
61+
),
62+
)
63+
64+
runner.on(
65+
StreamEventType.COMPLETION,
66+
lambda event: print(f"\n\n✓ Completed! Reason: {event['reason']}"),
67+
)
68+
69+
runner.on(
70+
StreamEventType.ERROR,
71+
lambda event: print(f"\n❌ Error: {event['message']}"),
72+
)
73+
74+
runner.on(
75+
StreamEventType.END,
76+
lambda event: print(f"⏱️ Total duration: {event['duration']:.2f}s"),
77+
)
78+
79+
# Process the stream
80+
runner.process()
81+
82+
except Exception as e:
83+
print(f"Error: {e}")
84+
85+
86+
if __name__ == "__main__":
87+
main()

examples/agent/agent.run.workflow.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,7 @@ def __init__(self, langbase_client: Langbase, debug: bool = False):
279279
langbase_client: Langbase client instance
280280
debug: Whether to enable debug mode
281281
"""
282-
self.lb = langbase_client
282+
self.langbase = langbase_client
283283
self.workflow = Workflow(debug=debug)
284284

285285
async def generate_blog_post(
@@ -299,7 +299,7 @@ async def generate_blog_post(
299299

300300
# Step 1: Generate outline
301301
async def create_outline():
302-
response = self.lb.agent.run(
302+
response = self.langbase.agent.run(
303303
input=f"Create a {target_length} blog post outline about: {topic}",
304304
model="openai:gpt-4o-mini",
305305
api_key=os.environ.get("LLM_API_KEY"),
@@ -309,7 +309,7 @@ async def create_outline():
309309
# Step 2: Generate introduction
310310
async def write_introduction():
311311
outline = self.workflow.context["outputs"]["outline"]
312-
response = self.lb.agent.run(
312+
response = self.langbase.agent.run(
313313
input=f"Write an engaging introduction for this outline: {outline}. Tone: {tone}",
314314
model="openai:gpt-4o-mini",
315315
api_key=os.environ.get("LLM_API_KEY"),
@@ -320,7 +320,7 @@ async def write_introduction():
320320
async def write_main_content():
321321
outline = self.workflow.context["outputs"]["outline"]
322322
intro = self.workflow.context["outputs"]["introduction"]
323-
response = self.lb.agent.run(
323+
response = self.langbase.agent.run(
324324
input=f"Write the main content based on outline: {outline}\nIntroduction: {intro}\nTone: {tone}",
325325
model="openai:gpt-4o-mini",
326326
api_key=os.environ.get("LLM_API_KEY"),
@@ -331,7 +331,7 @@ async def write_main_content():
331331
async def write_conclusion():
332332
outline = self.workflow.context["outputs"]["outline"]
333333
content = self.workflow.context["outputs"]["main_content"]
334-
response = self.lb.agent.run(
334+
response = self.langbase.agent.run(
335335
input=f"Write a conclusion for this content: {content[:500]}...",
336336
model="openai:gpt-4o-mini",
337337
api_key=os.environ.get("LLM_API_KEY"),
@@ -392,8 +392,8 @@ async def advanced_workflow_example():
392392
print("\n🚀 Advanced Workflow Example")
393393
print("=" * 50)
394394

395-
lb = Langbase(api_key=os.environ.get("LANGBASE_API_KEY"))
396-
blog_workflow = AIContentWorkflow(lb, debug=True)
395+
langbase = Langbase(api_key=os.environ.get("LANGBASE_API_KEY"))
396+
blog_workflow = AIContentWorkflow(langbase, debug=True)
397397

398398
result = await blog_workflow.generate_blog_post(
399399
topic="The Future of Artificial Intelligence",

examples/chunker/chunker.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
langbase_api_key = os.getenv("LANGBASE_API_KEY")
1717

1818
# Initialize the client
19-
lb = Langbase(api_key=langbase_api_key)
19+
langbase = Langbase(api_key=langbase_api_key)
2020

2121

2222
def main():
@@ -31,7 +31,7 @@ def main():
3131
with open(document_path, "r", encoding="utf-8") as file:
3232
document_content = file.read()
3333
# Chunk the content
34-
chunks = lb.chunker(
34+
chunks = langbase.chunker(
3535
content=document_content, chunk_max_length=1024, chunk_overlap=256
3636
)
3737

examples/memory/memory.create.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ def main():
1717
langbase_api_key = os.getenv("LANGBASE_API_KEY")
1818

1919
# Initialize the client
20-
lb = Langbase(api_key=langbase_api_key)
20+
langbase = Langbase(api_key=langbase_api_key)
2121

2222
# Create the memory
2323
try:
24-
response = lb.memories.create(
24+
response = langbase.memories.create(
2525
name="product-knowledge",
2626
description="Memory store for product documentation and information",
2727
embedding_model="openai:text-embedding-3-large",

examples/memory/memory.docs.delete.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,15 @@ def main():
1717
langbase_api_key = os.getenv("LANGBASE_API_KEY")
1818

1919
# Initialize the client
20-
lb = Langbase(api_key=langbase_api_key)
20+
langbase = Langbase(api_key=langbase_api_key)
2121

2222
# Memory name and document ID to delete
2323
memory_name = "product-knowledge" # Replace with your memory name
2424
document_name = "intro.txt" # Replace with the document name you want to delete
2525

2626
# Delete the document
2727
try:
28-
response = lb.memories.documents.delete(
28+
response = langbase.memories.documents.delete(
2929
memory_name=memory_name, document_name=document_name
3030
)
3131

examples/memory/memory.docs.list.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,14 @@ def main():
1717
langbase_api_key = os.getenv("LANGBASE_API_KEY")
1818

1919
# Initialize the client
20-
lb = Langbase(api_key=langbase_api_key)
20+
langbase = Langbase(api_key=langbase_api_key)
2121

2222
# Memory name to list documents from
2323
memory_name = "product-knowledge" # Replace with your memory name
2424

2525
# List documents in the memory
2626
try:
27-
response = lb.memories.documents.list(memory_name=memory_name)
27+
response = langbase.memories.documents.list(memory_name=memory_name)
2828

2929
print(f"Documents in memory '{memory_name}':")
3030
print(json.dumps(response, indent=2))

examples/memory/memory.docs.retry-embed.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,15 @@ def main():
1717
langbase_api_key = os.getenv("LANGBASE_API_KEY")
1818

1919
# Initialize the client
20-
lb = Langbase(api_key=langbase_api_key)
20+
langbase = Langbase(api_key=langbase_api_key)
2121

2222
# Memory name to retry embedding for
2323
memory_name = "product-knowledge" # Replace with your memory name
2424
document_name = "name.txt" # Replace with document name
2525

2626
# Retry embedding for failed documents
2727
try:
28-
response = lb.memories.documents.embeddings.retry(
28+
response = langbase.memories.documents.embeddings.retry(
2929
memory_name=memory_name, document_name=document_name
3030
)
3131

examples/memory/memory.docs.upload-pdf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def main():
1717
langbase_api_key = os.getenv("LANGBASE_API_KEY")
1818

1919
# Initialize the client
20-
lb = Langbase(api_key=langbase_api_key)
20+
langbase = Langbase(api_key=langbase_api_key)
2121

2222
# Memory name to upload documents to
2323
memory_name = "product-knowledge" # Replace with your memory name
@@ -31,7 +31,7 @@ def main():
3131
document_content = file.read()
3232

3333
content = "Langbase is a powerful platform for building AI applications with composable AI."
34-
response = lb.memories.documents.upload(
34+
response = langbase.memories.documents.upload(
3535
memory_name=memory_name,
3636
document_name="document.pdf",
3737
document=document_content, # Convert string to bytes

examples/memory/memory.docs.upload.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,15 @@ def main():
1616
langbase_api_key = os.getenv("LANGBASE_API_KEY")
1717

1818
# Initialize the client
19-
lb = Langbase(api_key=langbase_api_key)
19+
langbase = Langbase(api_key=langbase_api_key)
2020

2121
# Memory name to upload documents to
2222
memory_name = "product-knowledge" # Replace with your memory name
2323

2424
# Upload documents to the memory
2525
try:
2626
content = "Langbase is a powerful platform for building AI applications with composable AI."
27-
response = lb.memories.documents.upload(
27+
response = langbase.memories.documents.upload(
2828
memory_name=memory_name,
2929
document_name="intro.txt",
3030
document=content.encode("utf-8"), # Convert string to bytes

0 commit comments

Comments
 (0)