Skip to content

Commit 60fb7ac

Browse files
committed
update: v0.2.1 (chat) sdk
1 parent cf2fd51 commit 60fb7ac

File tree

11 files changed

+405
-76
lines changed

11 files changed

+405
-76
lines changed

example/client/chat.py

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import os
2+
import time
3+
4+
from memu import MemuClient
5+
6+
7+
def print_chat_response(response, message_num: int):
8+
"""Print chat response with detailed token usage."""
9+
print(f"\n🤖 Chat Response #{message_num}:")
10+
print(f" {response.message}")
11+
12+
print("\n📊 Token Usage:")
13+
usage = response.chat_token_usage
14+
print(f" Total Tokens: {usage.total_tokens}")
15+
print(f" Prompt Tokens: {usage.prompt_tokens}")
16+
print(f" Completion Tokens: {usage.completion_tokens}")
17+
18+
if usage.prompt_tokens_breakdown:
19+
breakdown = usage.prompt_tokens_breakdown
20+
print(" 📈 Token Breakdown:")
21+
print(f" - Current Query: {breakdown.current_query}")
22+
print(f" - Short Term Context: {breakdown.short_term_context}")
23+
print(f" - User Profile: {breakdown.user_profile}")
24+
print(f" - Retrieved Memory: {breakdown.retrieved_memory}")
25+
26+
27+
def main():
28+
"""Main chat demonstration function."""
29+
print("🚀 MemU Chat API Demo")
30+
print("=" * 50)
31+
32+
# Initialize MemU client
33+
memu_client = MemuClient(
34+
base_url="https://api.memu.so",
35+
api_key=os.getenv("MEMU_API_KEY")
36+
)
37+
38+
user_id = "chat_demo_user"
39+
agent_id = "chat_demo_assistant"
40+
user_name = "Demo User"
41+
agent_name = "Chat Assistant"
42+
43+
print("\n💬 Starting chat session...")
44+
print("-" * 50)
45+
46+
# Chat examples demonstrating different scenarios
47+
chat_examples = [
48+
{
49+
"message": "Hello! Can you help me with some hiking advice?",
50+
"kwargs": {"temperature": 0.7, "max_tokens": 150},
51+
"description": "Basic chat with memory retrieval"
52+
},
53+
{
54+
"message": "I'm planning to cook Italian food tonight. What should I make?",
55+
"kwargs": {"temperature": 0.8, "max_tokens": 200},
56+
"description": "Query related to pasta making from memory"
57+
},
58+
{
59+
"message": "I'm feeling overwhelmed at work and considering a career change. Any advice?",
60+
"kwargs": {"temperature": 0.6, "max_tokens": 180},
61+
"description": "Career advice drawing from previous conversation"
62+
},
63+
{
64+
"message": "What are some easy vegetables I can grow in my garden this spring?",
65+
"kwargs": {"temperature": 0.5, "max_tokens": 160},
66+
"description": "Gardening advice with memory context"
67+
},
68+
{
69+
"message": "I want to start learning a new language. What's the best approach?",
70+
"kwargs": {"temperature": 0.7, "max_tokens": 170},
71+
"description": "Language learning guidance"
72+
}
73+
]
74+
75+
# Conduct the chat session
76+
for i, example in enumerate(chat_examples, 1):
77+
print(f"\n👤 User Message #{i}: {example['message']}")
78+
print(f" Context: {example['description']}")
79+
print(f" LLM Parameters: {example['kwargs']}")
80+
81+
try:
82+
# Send chat message
83+
response = memu_client.chat(
84+
user_id=user_id,
85+
user_name=user_name,
86+
agent_id=agent_id,
87+
agent_name=agent_name,
88+
message=example['message'],
89+
max_context_tokens=4000,
90+
**example['kwargs']
91+
)
92+
93+
# Print detailed response
94+
print_chat_response(response, i)
95+
96+
except Exception as e:
97+
print(f" ❌ Chat error: {e}")
98+
99+
# Small delay between messages
100+
time.sleep(1)
101+
102+
# Close the client
103+
memu_client.close()
104+
105+
print("\n✨ Chat API demo completed!")
106+
print("=" * 50)
107+
108+
109+
if __name__ == "__main__":
110+
main()

memu/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
Simplified unified memory architecture with a single Memory Agent.
77
"""
88

9-
__version__ = "0.1.11"
9+
__version__ = "0.2.1"
1010
__author__ = "MemU Team"
1111
__email__ = "support@nevamind.ai"
1212

memu/sdk/javascript/examples/basic-usage.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* 2. Memorize a conversation
77
* 3. Check task status
88
* 4. Retrieve memories and categories
9+
* 5. Chat with memory-enhanced conversation
910
*/
1011

1112
import { MemuClient } from 'memu-js'
@@ -144,6 +145,38 @@ export const basicExample = async () => {
144145
})
145146
})
146147

148+
console.log()
149+
150+
// Example 7: Chat with memory-enhanced conversation
151+
console.log('💬 Starting memory-enhanced chat...')
152+
const chatResponse = await client.chat({
153+
agentId: 'assistant',
154+
agentName: 'Assistant',
155+
kwargs: {
156+
temperature: 0.7,
157+
maxTokens: 150,
158+
},
159+
maxContextTokens: 4000,
160+
message: 'What should I prepare for my next hiking trip?',
161+
userId: 'user',
162+
userName: 'Johnson',
163+
})
164+
165+
console.log(`🤖 AI Response: ${chatResponse.message}`)
166+
console.log('📊 Token Usage:')
167+
console.log(` Total Tokens: ${chatResponse.chatTokenUsage.totalTokens}`)
168+
console.log(` Prompt Tokens: ${chatResponse.chatTokenUsage.promptTokens}`)
169+
console.log(` Completion Tokens: ${chatResponse.chatTokenUsage.completionTokens}`)
170+
171+
if (chatResponse.chatTokenUsage.promptTokensBreakdown) {
172+
const breakdown = chatResponse.chatTokenUsage.promptTokensBreakdown
173+
console.log(' Token Breakdown:')
174+
console.log(` - Current Query: ${breakdown.currentQuery || 0}`)
175+
console.log(` - Short Term Context: ${breakdown.shortTermContext || 0}`)
176+
console.log(` - User Profile: ${breakdown.userProfile || 0}`)
177+
console.log(` - Retrieved Memory: ${breakdown.retrievedMemory || 0}`)
178+
}
179+
147180
console.log('\n✨ Example completed successfully!')
148181
}
149182
catch (error) {

memu/sdk/javascript/examples/typescript-usage.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*/
77

88
import type {
9+
ChatResponse,
910
DefaultCategoriesResponse,
1011
MemorizeResponse,
1112
MemorizeTaskStatusResponse,
@@ -187,6 +188,47 @@ export const typescriptExample = async (): Promise<void> => {
187188
})
188189
})
189190

191+
console.log()
192+
193+
// Example 6: Memory-enhanced chat with full TypeScript support
194+
console.log('💬 Starting memory-enhanced chat...')
195+
const chatResponse: ChatResponse = await client.chat({
196+
agentId: 'ml_tutor',
197+
agentName: 'ML Tutor',
198+
kwargs: {
199+
maxTokens: 200,
200+
temperature: 0.8,
201+
},
202+
maxContextTokens: 4000,
203+
message: 'Can you explain more about supervised vs unsupervised learning?',
204+
userId: 'student_456',
205+
userName: 'Bob Smith',
206+
})
207+
208+
console.log(`🤖 AI Response: ${chatResponse.message}`)
209+
console.log('📊 Token Usage:')
210+
console.log(` Total Tokens: ${chatResponse.chatTokenUsage.totalTokens}`)
211+
console.log(` Prompt Tokens: ${chatResponse.chatTokenUsage.promptTokens}`)
212+
console.log(` Completion Tokens: ${chatResponse.chatTokenUsage.completionTokens}`)
213+
214+
// Type-safe access to token breakdown
215+
const breakdown = chatResponse.chatTokenUsage.promptTokensBreakdown
216+
if (breakdown) {
217+
console.log(' Token Breakdown:')
218+
if (breakdown.currentQuery !== undefined) {
219+
console.log(` - Current Query: ${breakdown.currentQuery}`)
220+
}
221+
if (breakdown.shortTermContext !== undefined) {
222+
console.log(` - Short Term Context: ${breakdown.shortTermContext}`)
223+
}
224+
if (breakdown.userProfile !== undefined) {
225+
console.log(` - User Profile: ${breakdown.userProfile}`)
226+
}
227+
if (breakdown.retrievedMemory !== undefined) {
228+
console.log(` - Retrieved Memory: ${breakdown.retrievedMemory}`)
229+
}
230+
}
231+
190232
console.log('\n✨ TypeScript example completed successfully!')
191233
}
192234
catch (error) {

memu/sdk/javascript/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "memu-js",
33
"type": "module",
4-
"version": "0.1.11",
4+
"version": "0.2.1",
55
"packageManager": "pnpm@10.15.0",
66
"description": "MemU JavaScript SDK for interacting with MemU API services",
77
"author": "MemU Team",

0 commit comments

Comments
 (0)