DeepMostInnovations commited on
Commit
c712545
·
verified ·
1 Parent(s): a730190

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +5 -146
README.md CHANGED
@@ -49,157 +49,16 @@ This is a reinforcement learning model trained to predict real-time sales conver
49
 
50
  ```bash
51
  pip install azure-openai stable-baselines3 numpy torch huggingface_hub
 
 
 
52
  ```
53
 
54
 
55
- ## Complete Inference Code
56
 
57
- ```python
58
- import os
59
- import numpy as np
60
- import torch
61
- import torch.nn as nn
62
- from openai import AzureOpenAI
63
- from stable_baselines3 import PPO
64
- from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
65
- from dataclasses import dataclass
66
- from typing import List, Dict
67
- from huggingface_hub import hf_hub_download
68
- # Azure OpenAI Configuration
69
- AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY")
70
- AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT")
71
- AZURE_EMBEDDING_DEPLOYMENT = os.getenv("AZURE_EMBEDDING_DEPLOYMENT", "text-embedding-3-large")
72
-
73
- # Initialize Azure OpenAI client
74
- openai_client = AzureOpenAI(
75
- api_key=AZURE_OPENAI_API_KEY,
76
- api_version="2023-05-15",
77
- azure_endpoint=AZURE_OPENAI_ENDPOINT
78
- )
79
- model_path = hf_hub_download(
80
- repo_id="DeepMostInnovations/sales-conversion-model-reinf-learning",
81
- filename="sales_model.zip"
82
- )
83
- # Check for GPU
84
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
85
-
86
- # Custom Linear Layer class
87
- class CustomLN(BaseFeaturesExtractor):
88
- def __init__(self, observation_space, features_dim: int = 64):
89
- super().__init__(observation_space, features_dim)
90
- n_input_channels = observation_space.shape[0]
91
- self.ln = nn.Sequential(
92
- nn.Linear(n_input_channels, 512),
93
- nn.ReLU(),
94
- nn.Linear(512, 256),
95
- nn.ReLU(),
96
- nn.Linear(256, features_dim),
97
- nn.ReLU(),
98
- ).to(device)
99
-
100
- def forward(self, observations: torch.Tensor) -> torch.Tensor:
101
- return self.ln(observations)
102
-
103
- @dataclass
104
- class SalesAgent:
105
- model_path: str
106
-
107
- def __init__(self, model_path: str):
108
- self.model_path = model_path
109
- self.expected_embedding_dim = 3072
110
-
111
- # Load RL model
112
- policy_kwargs = dict(
113
- activation_fn=nn.ReLU,
114
- net_arch=[dict(pi=[128, 64], vf=[128, 64])],
115
- features_extractor_class=CustomLN,
116
- features_extractor_kwargs=dict(features_dim=64)
117
- )
118
-
119
- self.model = PPO.load(
120
- model_path,
121
- device=device,
122
- custom_objects={"policy_kwargs": policy_kwargs}
123
- )
124
-
125
- def get_embedding(self, text: str) -> np.ndarray:
126
- """Get embedding using Azure OpenAI"""
127
- response = openai_client.embeddings.create(
128
- model=AZURE_EMBEDDING_DEPLOYMENT,
129
- input=text
130
- )
131
-
132
- embedding = np.array(response.data[0].embedding, dtype=np.float32)
133
-
134
- # Adjust to expected dimension if needed
135
- if len(embedding) > self.expected_embedding_dim:
136
- # Average pooling
137
- embedding = np.array([
138
- np.mean(embedding[i:i+len(embedding)//self.expected_embedding_dim])
139
- for i in range(0, len(embedding), len(embedding)//self.expected_embedding_dim)
140
- ][:self.expected_embedding_dim])
141
- elif len(embedding) < self.expected_embedding_dim:
142
- # Pad with zeros
143
- embedding = np.pad(embedding, (0, self.expected_embedding_dim - len(embedding)))
144
-
145
- return embedding
146
-
147
- def create_state_vector(self, conversation_text: str, turn_number: int) -> np.ndarray:
148
- """Create state vector for RL model"""
149
- embedding = self.get_embedding(conversation_text)
150
-
151
- # Simple metrics
152
- metrics = np.array([0.5, 0.5, turn_number, 0.5, min(1.0, turn_number / 20)], dtype=np.float32)
153
- turn_info = np.array([turn_number], dtype=np.float32)
154
- prob_history = np.zeros(10, dtype=np.float32)
155
-
156
- return np.concatenate([embedding, metrics, turn_info, prob_history])
157
-
158
- def predict_conversion(self, conversation_text: str, turn_number: int) -> float:
159
- """Predict conversion probability"""
160
- state_vector = self.create_state_vector(conversation_text, turn_number)
161
-
162
- with torch.no_grad():
163
- action, _ = self.model.predict(state_vector, deterministic=True)
164
- probability = float(action[0])
165
-
166
- return max(0.0, min(1.0, probability))
167
-
168
- def analyze_conversation(self, conversation: List[Dict[str, str]]) -> Dict:
169
- """Analyze a full conversation"""
170
- results = []
171
- conversation_text = ""
172
-
173
- for i, turn in enumerate(conversation):
174
- conversation_text += f"{turn['role']}: {turn['content']}\n"
175
-
176
- if turn['role'] == 'assistant':
177
- probability = self.predict_conversion(conversation_text, i // 2 + 1)
178
- results.append({
179
- 'turn_number': i // 2 + 1,
180
- 'response': turn['content'],
181
- 'probability': probability
182
- })
183
-
184
- final_probability = results[-1]['probability'] if results else 0.0
185
-
186
- return {
187
- 'conversation_results': results,
188
- 'final_probability': final_probability,
189
- 'summary': f"Predicted final conversion: {final_probability*100:.1f}%"
190
- }
191
 
192
- # Example usage
193
- if __name__ == "__main__":
194
- agent = SalesAgent(model_path)
195
-
196
- conversation = [
197
- {"role": "user", "content": "I'm looking for a project management tool."},
198
- {"role": "assistant", "content": "Thanks! How large is your team?"}
199
- ]
200
-
201
- results = agent.analyze_conversation(conversation)
202
- print(results['summary'])
203
  ```
204
 
205
 
 
49
 
50
  ```bash
51
  pip install azure-openai stable-baselines3 numpy torch huggingface_hub
52
+ git lfs install
53
+ git clone https://huggingface.co/DeepMostInnovations/sales-conversion-model-reinf-learning
54
+ %cd sales-conversion-model-reinf-learning
55
  ```
56
 
57
 
58
+ ## Run
59
 
60
+ ```bash
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
 
62
  ```
63
 
64