Spaces:
Sleeping
Sleeping
File size: 12,879 Bytes
c96b98a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | import requests
from os import getenv
from typing import Optional
from phi.tools import Toolkit
from phi.utils.log import logger
class LinearTool(Toolkit):
def __init__(
self,
get_user_details: bool = True,
get_issue_details: bool = True,
create_issue: bool = True,
update_issue: bool = True,
get_user_assigned_issues: bool = True,
get_workflow_issues: bool = True,
get_high_priority_issues: bool = True,
):
super().__init__(name="linear tools")
self.api_token = getenv("LINEAR_API_KEY")
if not self.api_token:
api_error_message = "API token 'LINEAR_API_KEY' is missing. Please set it as an environment variable."
logger.error(api_error_message)
self.endpoint = "https://api.linear.app/graphql"
self.headers = {"Authorization": f"{self.api_token}"}
if get_user_details:
self.register(self.get_user_details)
if get_issue_details:
self.register(self.get_issue_details)
if create_issue:
self.register(self.create_issue)
if update_issue:
self.register(self.update_issue)
if get_user_assigned_issues:
self.register(self.get_user_assigned_issues)
if get_workflow_issues:
self.register(self.get_workflow_issues)
if get_high_priority_issues:
self.register(self.get_high_priority_issues)
def _execute_query(self, query, variables=None):
"""Helper method to execute GraphQL queries with optional variables."""
try:
response = requests.post(self.endpoint, json={"query": query, "variables": variables}, headers=self.headers)
response.raise_for_status()
data = response.json()
if "errors" in data:
logger.error(f"GraphQL Error: {data['errors']}")
raise Exception(f"GraphQL Error: {data['errors']}")
logger.info("GraphQL query executed successfully.")
return data.get("data")
except requests.exceptions.RequestException as e:
logger.error(f"Request error: {e}")
raise
except Exception as e:
logger.error(f"Unexpected error: {e}")
raise
def get_user_details(self) -> Optional[str]:
"""
Fetch authenticated user details.
It will return the user's unique ID, name, and email address from the viewer object in the GraphQL response.
Returns:
str or None: A string containing user details like user id, name, and email.
Raises:
Exception: If an error occurs during the query execution or data retrieval.
"""
query = """
query Me {
viewer {
id
name
email
}
}
"""
try:
response = self._execute_query(query)
if response.get("viewer"):
user = response["viewer"]
logger.info(
f"Retrieved authenticated user details with name: {user['name']}, ID: {user['id']}, Email: {user['email']}"
)
return str(user)
else:
logger.error("Failed to retrieve the current user details")
return None
except Exception as e:
logger.error(f"Error fetching authenticated user details: {e}")
raise
def get_issue_details(self, issue_id: str) -> Optional[str]:
"""
Retrieve details of a specific issue by issue ID.
Args:
issue_id (str): The unique identifier of the issue to retrieve.
Returns:
str or None: A string containing issue details like issue id, issue title, and issue description.
Returns `None` if the issue is not found.
Raises:
Exception: If an error occurs during the query execution or data retrieval.
"""
query = """
query IssueDetails ($issueId: String!){
issue(id: $issueId) {
id
title
description
}
}
"""
variables = {"issueId": issue_id}
try:
response = self._execute_query(query, variables)
if response.get("issue"):
issue = response["issue"]
logger.info(f"Issue '{issue['title']}' retrieved successfully with ID {issue['id']}.")
return str(issue)
else:
logger.error(f"Failed to retrieve issue with ID {issue_id}.")
return None
except Exception as e:
logger.error(f"Error retrieving issue with ID {issue_id}: {e}")
raise
def create_issue(
self, title: str, description: str, team_id: str, project_id: str, assignee_id: str
) -> Optional[str]:
"""
Create a new issue within a specific project and team.
Args:
title (str): The title of the new issue.
description (str): The description of the new issue.
team_id (str): The unique identifier of the team in which to create the issue.
Returns:
str or None: A string containing the created issue's details like issue id and issue title.
Returns `None` if the issue creation fails.
Raises:
Exception: If an error occurs during the mutation execution or data retrieval.
"""
query = """
mutation IssueCreate ($title: String!, $description: String!, $teamId: String!, $projectId: String!, $assigneeId: String!){
issueCreate(
input: { title: $title, description: $description, teamId: $teamId, projectId: $projectId, assigneeId: $assigneeId}
) {
success
issue {
id
title
url
}
}
}
"""
variables = {
"title": title,
"description": description,
"teamId": team_id,
"projectId": project_id,
"assigneeId": assignee_id,
}
try:
response = self._execute_query(query, variables)
logger.info(f"Response: {response}")
if response["issueCreate"]["success"]:
issue = response["issueCreate"]["issue"]
logger.info(f"Issue '{issue['title']}' created successfully with ID {issue['id']}")
return str(issue)
else:
logger.error("Issue creation failed.")
return None
except Exception as e:
logger.error(f"Error creating issue '{title}' for team ID {team_id}: {e}")
raise
def update_issue(self, issue_id: str, title: Optional[str]) -> Optional[str]:
"""
Update the title or state of a specific issue by issue ID.
Args:
issue_id (str): The unique identifier of the issue to update.
title (str, optional): The new title for the issue. If None, the title remains unchanged.
Returns:
str or None: A string containing the updated issue's details with issue id, issue title, and issue state (which includes `id` and `name`).
Returns `None` if the update is unsuccessful.
Raises:
Exception: If an error occurs during the mutation execution or data retrieval.
"""
query = """
mutation IssueUpdate ($issueId: String!, $title: String!){
issueUpdate(
id: $issueId,
input: { title: $title}
) {
success
issue {
id
title
state {
id
name
}
}
}
}
"""
variables = {"issueId": issue_id, "title": title}
try:
response = self._execute_query(query, variables)
if response["issueUpdate"]["success"]:
issue = response["issueUpdate"]["issue"]
logger.info(f"Issue ID {issue_id} updated successfully.")
return str(issue)
else:
logger.error(f"Failed to update issue ID {issue_id}. Success flag was false.")
return None
except Exception as e:
logger.error(f"Error updating issue ID {issue_id}: {e}")
raise
def get_user_assigned_issues(self, user_id: str) -> Optional[str]:
"""
Retrieve issues assigned to a specific user by user ID.
Args:
user_id (str): The unique identifier of the user for whom to retrieve assigned issues.
Returns:
str or None: A string representing the assigned issues to user id,
where each issue contains issue details (e.g., `id`, `title`).
Returns None if the user or issues cannot be retrieved.
Raises:
Exception: If an error occurs while querying for the user's assigned issues.
"""
query = """
query UserAssignedIssues($userId: String!) {
user(id: $userId) {
id
name
assignedIssues {
nodes {
id
title
}
}
}
}
"""
variables = {"userId": user_id}
try:
response = self._execute_query(query, variables)
if response.get("user"):
user = response["user"]
issues = user["assignedIssues"]["nodes"]
logger.info(f"Retrieved {len(issues)} issues assigned to user '{user['name']}' (ID: {user['id']}).")
return str(issues)
else:
logger.error("Failed to retrieve user or issues.")
return None
except Exception as e:
logger.error(f"Error retrieving issues for user ID {user_id}: {e}")
raise
def get_workflow_issues(self, workflow_id: str) -> Optional[str]:
"""
Retrieve issues within a specific workflow state by workflow ID.
Args:
workflow_id (str): The unique identifier of the workflow state to retrieve issues from.
Returns:
str or None: A string representing the issues within the specified workflow state,
where each issue contains details of an issue (e.g., `title`).
Returns None if no issues are found or if the workflow state cannot be retrieved.
Raises:
Exception: If an error occurs while querying issues for the specified workflow state.
"""
query = """
query WorkflowStateIssues($workflowId: String!) {
workflowState(id: $workflowId) {
issues {
nodes {
title
}
}
}
}
"""
variables = {"workflowId": workflow_id}
try:
response = self._execute_query(query, variables)
if response.get("workflowState"):
issues = response["workflowState"]["issues"]["nodes"]
logger.info(f"Retrieved {len(issues)} issues in workflow state ID {workflow_id}.")
return str(issues)
else:
logger.error("Failed to retrieve issues for the specified workflow state.")
return None
except Exception as e:
logger.error(f"Error retrieving issues for workflow state ID {workflow_id}: {e}")
raise
def get_high_priority_issues(self) -> Optional[str]:
"""
Retrieve issues with a high priority (priority <= 2).
Returns:
str or None: A str representing high-priority issues, where it
contains details of an issue (e.g., `id`, `title`, `priority`).
Returns None if no issues are retrieved.
Raises:
Exception: If an error occurs during the query process.
"""
query = """
query HighPriorityIssues {
issues(filter: {
priority: { lte: 2 }
}) {
nodes {
id
title
priority
}
}
}
"""
try:
response = self._execute_query(query)
if response.get("issues"):
high_priority_issues = response["issues"]["nodes"]
logger.info(f"Retrieved {len(high_priority_issues)} high-priority issues.")
return str(high_priority_issues)
else:
logger.error("Failed to retrieve high-priority issues.")
return None
except Exception as e:
logger.error(f"Error retrieving high-priority issues: {e}")
raise
|