Skip to content

Commit 21ec459

Browse files
committed
moved userRapport to account
1 parent cb68b8e commit 21ec459

File tree

7 files changed

+76
-56
lines changed

7 files changed

+76
-56
lines changed

packages/adapter-sqlite/src/index.ts

+33-29
Original file line numberDiff line numberDiff line change
@@ -122,24 +122,25 @@ export class SqliteDatabaseAdapter
122122

123123
const messages = await this.getConversationMessages(conversationId);
124124

125-
// Format each message with timestamp
126-
const formattedMessages = messages.map(msg => {
127-
// Ensure we have a valid number for the timestamp
128-
const timestamp = typeof msg.createdAt === 'number'
129-
? new Date(msg.createdAt)
130-
: new Date();
131-
132-
const formattedTime = timestamp.toLocaleString("en-US", {
133-
hour: "2-digit",
134-
minute: "2-digit",
135-
month: "short",
136-
day: "numeric"
137-
});
138-
const username = msg.content.username || msg.userId;
139-
return `@${username} (${formattedTime}):\n${msg.content.text}`;
140-
});
141-
142-
return `Context: ${conversation.context}\n\n${formattedMessages.join('\n\n')}`;
125+
// Format each message showing only username
126+
const formattedMessages = await Promise.all(messages.map(async msg => {
127+
// First try to get username from message content
128+
let username = msg.content.username;
129+
130+
// If no username in content, try to get it from accounts table
131+
if (!username) {
132+
const account = await this.getAccountById(msg.userId);
133+
if (account?.username) {
134+
username = account.username;
135+
}
136+
}
137+
console.log("username", username)
138+
// Add @ prefix if we found a username
139+
const displayName = username ? `@${username}` : `user_${msg.userId.substring(0, 8)}`;
140+
return `${displayName}: ${msg.content.text}`;
141+
}));
142+
143+
return formattedMessages.join('\n\n');
143144
}
144145

145146
async setParticipantUserState(
@@ -794,20 +795,23 @@ export class SqliteDatabaseAdapter
794795
.all(params.userId, params.userId) as Relationship[];
795796
}
796797
async getUserRapport(userId: UUID, agentId: UUID): Promise<number> {
797-
const sql = "SELECT score FROM user_rapport WHERE userId = ? AND agentId = ?";
798-
const rapport = this.db.prepare(sql).get(userId, agentId) as { score: number } | undefined;
799-
800-
// Return default rapport score of 0 if none exists
801-
return rapport?.score ?? 0;
798+
try {
799+
const sql = "SELECT userRapport FROM accounts WHERE id = ?";
800+
const account = this.db.prepare(sql).get(userId) as { userRapport: number } | undefined;
801+
return account?.userRapport ?? 0;
802+
} catch (error) {
803+
console.error("Error getting user rapport:", error);
804+
return 0;
805+
}
802806
}
803807

804808
async setUserRapport(userId: UUID, agentId: UUID, score: number): Promise<void> {
805-
const sql = `
806-
INSERT INTO user_rapport (userId, agentId, score)
807-
VALUES (?, ?, ?)
808-
ON CONFLICT(userId, agentId) DO UPDATE SET score = ?
809-
`;
810-
this.db.prepare(sql).run(userId, agentId, score, score);
809+
try {
810+
const sql = "UPDATE accounts SET userRapport = ? WHERE id = ?";
811+
this.db.prepare(sql).run(score, userId);
812+
} catch (error) {
813+
console.error("Error setting user rapport:", error);
814+
}
811815
}
812816

813817
async getCache(params: {

packages/adapter-sqlite/src/sqliteTables.ts

+9-11
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,17 @@ CREATE TABLE IF NOT EXISTS "accounts" (
1111
"username" TEXT,
1212
"email" TEXT NOT NULL,
1313
"avatarUrl" TEXT,
14-
"details" TEXT DEFAULT '{}' CHECK(json_valid("details")) -- Ensuring details is a valid JSON field
14+
"details" TEXT DEFAULT '{}' CHECK(json_valid("details")), -- Ensuring details is a valid JSON field
15+
"userRapport" REAL NOT NULL DEFAULT 0
1516
);
1617
18+
-- Add userRapport column if it doesn't exist (using correct SQLite syntax)
19+
SELECT CASE
20+
WHEN NOT EXISTS(SELECT 1 FROM pragma_table_info('accounts') WHERE name='userRapport')
21+
THEN 'ALTER TABLE accounts ADD COLUMN "userRapport" REAL NOT NULL DEFAULT 0;'
22+
END
23+
WHERE NOT EXISTS(SELECT 1 FROM pragma_table_info('accounts') WHERE name='userRapport');
24+
1725
-- Table: memories
1826
CREATE TABLE IF NOT EXISTS "memories" (
1927
"id" TEXT PRIMARY KEY,
@@ -126,14 +134,6 @@ CREATE TABLE IF NOT EXISTS "knowledge" (
126134
CHECK((isShared = 1 AND agentId IS NULL) OR (isShared = 0 AND agentId IS NOT NULL))
127135
);
128136
129-
-- Table: user_rapport
130-
CREATE TABLE IF NOT EXISTS user_rapport (
131-
userId TEXT NOT NULL,
132-
agentId TEXT NOT NULL,
133-
score REAL NOT NULL DEFAULT 0,
134-
PRIMARY KEY (userId, agentId)
135-
);
136-
137137
-- Index: relationships_id_key
138138
CREATE UNIQUE INDEX IF NOT EXISTS "relationships_id_key" ON "relationships" ("id");
139139
@@ -144,8 +144,6 @@ CREATE UNIQUE INDEX IF NOT EXISTS "memories_id_key" ON "memories" ("id");
144144
CREATE UNIQUE INDEX IF NOT EXISTS "participants_id_key" ON "participants" ("id");
145145
146146
-- Index: knowledge
147-
-- Index: user_rapport_user_agent
148-
CREATE INDEX IF NOT EXISTS "user_rapport_user_agent" ON "user_rapport" ("userId", "agentId");
149147
CREATE INDEX IF NOT EXISTS "knowledge_agent_key" ON "knowledge" ("agentId");
150148
CREATE INDEX IF NOT EXISTS "knowledge_agent_main_key" ON "knowledge" ("agentId", "isMain");
151149
CREATE INDEX IF NOT EXISTS "knowledge_original_key" ON "knowledge" ("originalId");

packages/client-twitter/src/interactions.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -128,11 +128,13 @@ export class TwitterInteractionClient {
128128

129129
elizaLogger.log("Checking active conversations");
130130
// Get all active conversations
131-
const activeConversations = await this.runtime.databaseAdapter.getConversationsByStatus('ACTIVE');
131+
const activeConversations = await this.runtime.databaseAdapter.getConversationsByStatus('CLOSED');
132132

133133
for (const conversation of activeConversations) {
134134
const messageIds = JSON.parse(conversation.messageIds);
135-
135+
console.log("messageIds", messageIds)
136+
console.log ("checking if conversation is done", conversation.id)
137+
console.log("if satement logic :",isConversationDone(conversation.id, this.runtime), messageIds.length)
136138
if( isConversationDone(conversation.id, this.runtime)&&messageIds.length>=3){
137139
await analyzeConversation(conversation.id, this.runtime);
138140
}

packages/client-twitter/src/utils.ts

+18-12
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Tweet } from "agent-twitter-client";
2-
import { getEmbeddingZeroVector, composeContext, elizaLogger } from "@elizaos/core";
2+
import { getEmbeddingZeroVector, composeContext, elizaLogger, generateText,ModelClass
3+
} from "@elizaos/core";
34
import type { Content, Memory, UUID, IAgentRuntime } from "@elizaos/core";
45

56
import { stringToUuid } from "@elizaos/core";
@@ -438,7 +439,9 @@ export async function analyzeConversation(
438439
conversationId: UUID,
439440
runtime: IAgentRuntime
440441
): Promise<void> {
442+
441443
const conversation = await runtime.databaseAdapter.getConversation(conversationId);
444+
console.log("analyze conversation", conversation)
442445
if (!conversation) {
443446
elizaLogger.error("No conversation found for analysis", conversationId);
444447
return;
@@ -450,25 +453,25 @@ export async function analyzeConversation(
450453
elizaLogger.error("No messages found in conversation for analysis", conversationId);
451454
return;
452455
}
453-
454-
// Get the last message to use for state building
456+
// Get the last message to use for state building
455457
const lastMessage = messages[messages.length - 1];
456-
457458
// Build state with conversation context
458459
const state = await runtime.composeState(lastMessage, {
459460
conversationId: conversationId,
460461
twitterUserName: runtime.getSetting("TWITTER_USERNAME")
461462
});
462463

464+
//console.log("state:", state)
465+
463466
// Format conversation for per-user analysis
464467
const analysisTemplate = `
465-
#Recent Conversations:
468+
#Conversation:
466469
{{recentUserConversations}}
467470
468471
#Instructions:
469472
Evaluate the messages the other users sent to you in this conversation.
470473
Rate each users messages sent to you as a whole using these metrics: [-5] very bad, [0] neutral, [5] very good.
471-
Evaluates these messages as the character ${runtime.character.name} with the context of the whole conversation.
474+
Evaluates these messages as the character {{agentName}} (@{{twitterUserName}}):with the context of the whole conversation.
472475
If you aren't sure if the message was directed to you, or you're missing context to give a good answer, give the score [0] neutral.
473476
474477
Return ONLY a JSON object with usernames as keys and scores as values. Example format:
@@ -480,9 +483,12 @@ export async function analyzeConversation(
480483
state,
481484
template: analysisTemplate
482485
});
483-
484-
const analysis = await runtime.generateText({
485-
prompt: context,
486+
console.log("context", context)
487+
488+
const analysis = await generateText({
489+
runtime,
490+
context,
491+
modelClass: ModelClass.LARGE,
486492
});
487493

488494
elizaLogger.log("User sentiment scores:", analysis);
@@ -493,7 +499,7 @@ export async function analyzeConversation(
493499
// Update conversation with analysis
494500
await runtime.databaseAdapter.updateConversation({
495501
id: conversationId,
496-
status: 'CLOSED'
502+
//status: 'CLOSED'
497503
});
498504

499505
// Update user rapport based on sentiment scores
@@ -506,7 +512,7 @@ export async function analyzeConversation(
506512
await runtime.databaseAdapter.setUserRapport(
507513
userId,
508514
runtime.agentId,
509-
score as number
515+
score as number // Use the sentiment score directly
510516
);
511517
elizaLogger.log(`Updated rapport for user ${username}:`, score);
512518
}
@@ -526,7 +532,7 @@ export async function isConversationDone(
526532

527533
const timeInactive = now.getTime() - lastMessageTime.getTime();
528534
if (timeInactive > 45 * 60 * 1000) {
529-
elizaLogger.log("Conversation inactive for 45 minutes");
535+
elizaLogger.log("Conversation inactive for 45 minutes",conversationId);
530536

531537
return true;
532538
}

packages/core/src/generation.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,12 @@ export async function generateText({
6161
modelClass: string;
6262
stop?: string[];
6363
}): Promise<string> {
64+
elizaLogger.debug("Entering generateText function with:", {
65+
modelProvider: runtime?.modelProvider,
66+
modelClass,
67+
contextLength: context?.length
68+
});
69+
6470
if (!context) {
6571
console.error("generateText context is empty");
6672
return "";
@@ -535,7 +541,7 @@ export async function generateText({
535541
}
536542

537543
case ModelProviderName.VENICE: {
538-
elizaLogger.debug("Initializing Venice model.");
544+
elizaLogger.log("Initializing Venice model.");
539545
const venice = createOpenAI({
540546
apiKey: apiKey,
541547
baseURL: endpoint,
@@ -553,7 +559,7 @@ export async function generateText({
553559
});
554560

555561
response = veniceResponse;
556-
elizaLogger.debug("Received response from Venice model.");
562+
elizaLogger.log("Received response from Venice model.", veniceResponse);
557563
break;
558564
}
559565

packages/core/src/runtime.ts

+1
Original file line numberDiff line numberDiff line change
@@ -1043,6 +1043,7 @@ Text: ${attachment.text}
10431043
recentPostInteractions: formattedPostInteractions,
10441044
// Raw memory[] array of interactions
10451045
recentInteractionsData: recentInteractions,
1046+
recentUserConversations: recentUserConversations,
10461047
// randomly pick one topic
10471048
topic:
10481049
this.character.topics && this.character.topics.length > 0

packages/core/src/types.ts

+3
Original file line numberDiff line numberDiff line change
@@ -526,6 +526,9 @@ export interface Account {
526526

527527
/** Optional avatar URL */
528528
avatarUrl?: string;
529+
530+
/** User rapport score based on memory */
531+
userRapport?: number;
529532
}
530533

531534
/**

0 commit comments

Comments
 (0)