Skip to content

Commit 0527ad2

Browse files
committed
👌 IMPROVE: Examples
1 parent 42e1066 commit 0527ad2

12 files changed

+114
-114
lines changed

examples/agent/agent.run.stream.py

Lines changed: 37 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,64 @@
11
"""
2-
Run Agent Streaming
2+
Run Agent Streaming with get_runner
33
4-
This example demonstrates how to run an agent with streaming response.
4+
This example demonstrates how to run an agent with streaming response using get_runner.
55
"""
66

77
import os
8-
import sys
98

109
from dotenv import load_dotenv
1110

12-
from langbase import Langbase
13-
from langbase.helper import stream_text
11+
from langbase import Langbase, get_runner
1412

1513
load_dotenv()
1614

1715

1816
def main():
1917
# Check for required environment variables
2018
langbase_api_key = os.environ.get("LANGBASE_API_KEY")
21-
llm_api_key = os.environ.get("LLM_API_KEY")
19+
api_key = os.environ.get("LLM_API_KEY")
2220

2321
if not langbase_api_key:
2422
print("❌ Missing LANGBASE_API_KEY in environment variables.")
2523
print("Please set: export LANGBASE_API_KEY='your_langbase_api_key'")
2624
exit(1)
2725

28-
if not llm_api_key:
29-
print("❌ Missing LLM_API_KEY in environment variables.")
30-
print("Please set: export LLM_API_KEY='your_llm_api_key'")
31-
exit(1)
32-
3326
# Initialize Langbase client
3427
langbase = Langbase(api_key=langbase_api_key)
3528

36-
# Run the agent with streaming
37-
response = langbase.agent_run(
38-
stream=True,
39-
model="openai:gpt-4.1-mini",
40-
api_key=llm_api_key,
41-
instructions="You are a helpful assistant that help users summarize text.",
42-
input=[{"role": "user", "content": "Who is an AI Engineer?"}],
43-
)
44-
45-
print("Stream started.\n")
46-
47-
# Process the streaming response
48-
for line in response.iter_lines():
49-
if line:
50-
line_str = line.decode("utf-8")
51-
if line_str.startswith("data: "):
52-
data = line_str[6:] # Remove 'data: ' prefix
53-
if data.strip() == "[DONE]":
54-
print("\nStream ended.")
55-
break
56-
try:
57-
import json
58-
59-
json_data = json.loads(data)
60-
if "choices" in json_data and len(json_data["choices"]) > 0:
61-
delta = json_data["choices"][0].get("delta", {})
62-
if "content" in delta:
63-
sys.stdout.write(delta["content"])
64-
sys.stdout.flush()
65-
except json.JSONDecodeError:
66-
# Skip invalid JSON lines
67-
continue
29+
try:
30+
# Get readable stream - equivalent to const {stream} = await langbase.agent.run(...)
31+
response = langbase.agent_run(
32+
stream=True,
33+
model="openai:gpt-4.1-mini",
34+
instructions="You are a helpful assistant that help users summarize text.",
35+
input=[{"role": "user", "content": "Who is an AI Engineer?"}],
36+
api_key=api_key
37+
)
38+
39+
# Convert the stream to a stream runner - equivalent to getRunner(stream)
40+
runner = get_runner(response)
41+
42+
# Event-like handling in Python
43+
# Method 1: Using iterator pattern (Python equivalent of event listeners)
44+
45+
# Equivalent to runner.on('connect', ...)
46+
print("Stream started.\n")
47+
48+
try:
49+
# Equivalent to runner.on('content', content => {...})
50+
for content in runner.text_generator():
51+
print(content, end="", flush=True)
52+
53+
# Equivalent to runner.on('end', ...)
54+
print("\nStream ended.")
55+
56+
except Exception as error:
57+
# Equivalent to runner.on('error', error => {...})
58+
print(f"Error: {error}")
59+
60+
except Exception as e:
61+
print(f"Error: {e}")
6862

6963

7064
if __name__ == "__main__":

examples/chunker/chunker.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import os
66
import pathlib
7+
import json
78

89
from dotenv import load_dotenv
910

@@ -37,15 +38,10 @@ def main():
3738
and tools for each part of the job and provides developers with a zero-config composable
3839
AI infrastructure."""
3940

40-
# Alternative: Read content from a file
41-
# document_path = pathlib.Path(__file__).parent.parent / "parse" / "composable-ai.md"
42-
# with open(document_path, "r", encoding="utf-8") as file:
43-
# content = file.read()
44-
4541
# Chunk the content
4642
chunks = lb.chunker(content=content, chunk_max_length=1024, chunk_overlap=256)
4743

48-
print(chunks)
44+
print(json.dumps(chunks, indent=2))
4945

5046
except Exception as e:
5147
print(f"Error chunking content: {e}")

examples/embed/embed.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Experimental upcoming beta AI primitve.
22
# Please refer to the documentation for more information: https://langbase.com/docs for more information.
33
import os
4-
4+
import json
55
from dotenv import load_dotenv
66

77
from langbase import Langbase
@@ -22,7 +22,7 @@ def main():
2222
],
2323
embedding_model="openai:text-embedding-3-large",
2424
)
25-
print(response)
25+
print(json.dumps(response, indent=2))
2626

2727

2828
if __name__ == "__main__":

examples/memory/memory.docs.delete.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@ def main():
2121

2222
# Memory name and document ID to delete
2323
memory_name = "product-knowledge" # Replace with your memory name
24-
document_id = "doc-123" # Replace with the document ID you want to delete
24+
document_name = "name.txt" # Replace with the document name you want to delete
2525

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

3030
print(
3131
f"Document '{document_id}' deleted successfully from memory '{memory_name}'"

examples/memory/memory.docs.list.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ def main():
2424

2525
# List documents in the memory
2626
try:
27-
response = lb.memories.docs.list(
28-
name=memory_name, limit=10 # Limit the number of documents returned
27+
response = lb.memories.documents.list(
28+
memory_name=memory_name
2929
)
3030

3131
print(f"Documents in memory '{memory_name}':")

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,11 @@ def main():
2121

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

2526
# Retry embedding for failed documents
2627
try:
27-
response = lb.memories.docs.retry_embed(name=memory_name)
28+
response = lb.memories.documents.embeddings.retry(memory_name=memory_name,document_name=document_name)
2829

2930
print(f"Retry embedding initiated for memory '{memory_name}'")
3031
print(json.dumps(response, indent=2))

examples/memory/memory.docs.upload.py

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,22 +24,17 @@ def main():
2424

2525
# Upload documents to the memory
2626
try:
27-
response = lb.memories.docs.upload(
28-
name=memory_name,
29-
documents=[
30-
{
31-
"content": "Langbase is a powerful platform for building AI applications with composable AI.",
32-
"metadata": {"source": "documentation", "section": "introduction"},
33-
},
34-
{
35-
"content": "The platform supports various AI models and provides tools for memory management.",
36-
"metadata": {"source": "documentation", "section": "features"},
37-
},
38-
],
27+
# Example 1: Upload string content as bytes
28+
content1 = "Langbase is a powerful platform for building AI applications with composable AI."
29+
response1 = lb.memories.documents.upload(
30+
memory_name=memory_name,
31+
document_name="intro.txt",
32+
document=content1.encode('utf-8'), # Convert string to bytes
33+
content_type="text/plain",
34+
meta={"source": "documentation", "section": "introduction"}
3935
)
40-
41-
print("Documents uploaded successfully!")
42-
print(json.dumps(response, indent=2))
36+
print("Document 1 uploaded successfully!")
37+
print(f"Status: {response1.status_code}")
4338

4439
except Exception as e:
4540
print(f"Error uploading documents: {e}")

examples/memory/memory.retrieve.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
"""
22
Example demonstrating how to retrieve memories in Langbase.
3+
4+
This example shows how to retrieve memories using a query. The memory parameter
5+
expects a list of dictionaries with 'name' keys specifying which memories to search.
36
"""
47

58
import json
@@ -21,12 +24,16 @@ def main():
2124

2225
# Retrieve memories using a query
2326
memory_name = "product-knowledge" # Replace with your memory name
24-
query = "What are the main features of the product?"
27+
query = "What is Langbase?"
2528

2629
try:
2730
response = lb.memories.retrieve(
28-
name=memory_name,
2931
query=query,
32+
memory=[
33+
{
34+
"name": memory_name
35+
}
36+
],
3037
top_k=5, # Number of relevant memories to retrieve
3138
)
3239

examples/pipes/pipes.create.py

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,24 +19,19 @@ def main():
1919
# Initialize the client
2020
lb = Langbase(api_key=langbase_api_key)
2121

22-
# Define pipe configuration
23-
pipe_config = {
24-
"name": "my-summary-pipe", # Replace with your desired pipe name
25-
"description": "A pipe for text summarization",
26-
"system_prompt": "You are a helpful assistant that summarizes text clearly and concisely.",
27-
"model": "openai:gpt-4-turbo-preview",
28-
"variables": [
29-
{
30-
"name": "text_to_summarize",
31-
"description": "The text that needs to be summarized",
32-
"type": "string",
33-
}
34-
],
35-
}
36-
3722
# Create the pipe
3823
try:
39-
response = lb.pipes.create(**pipe_config)
24+
response = lb.pipes.create(
25+
name="summary-agent",
26+
description="A pipe for text summarization",
27+
messages=[
28+
{
29+
"role": "system",
30+
"content": "You are a helpful assistant that summarizes text clearly and concisely.",
31+
}
32+
],
33+
upsert=True
34+
)
4035

4136
print("Pipe created successfully!")
4237
print(json.dumps(response, indent=2))

examples/pipes/pipes.run.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,19 @@ def main():
2020
# Initialize the client
2121
lb = Langbase(api_key=langbase_api_key)
2222

23-
# Name of the pipe to run
24-
pipe_name = "summary-agent-14" # Replace with your pipe name
25-
26-
# Define messages for the conversation
27-
messages = [{"role": "user", "content": "Who is an AI Engineer?"}]
2823

2924
# Run the pipe with explicit stream=False
3025
try:
31-
response = lb.pipes.run(name=pipe_name, messages=messages, stream=False)
26+
response = lb.pipes.run(
27+
name="summary-agent",
28+
messages=[
29+
{
30+
"role": "user",
31+
"content": "Who is an AI Engineer?"
32+
}
33+
],
34+
stream=False
35+
)
3236

3337
# Print the entire response as is
3438
print(json.dumps(response, indent=2))

0 commit comments

Comments
 (0)