|
| 1 | +import json |
| 2 | +import requests |
| 3 | +from typing import Optional, List, Any, Iterator |
| 4 | +from pydantic import BaseModel, Field |
| 5 | +from agentx.util import get_headers |
| 6 | + |
| 7 | + |
| 8 | +class ChatResponse(BaseModel): |
| 9 | + text: str | None |
| 10 | + cot: str | None |
| 11 | + botId: str |
| 12 | + reference: Optional[Any] |
| 13 | + tasks: Optional[Any] |
| 14 | + |
| 15 | + |
| 16 | +class Message(BaseModel): |
| 17 | + id: str = Field(alias="_id") |
| 18 | + conversationId: str |
| 19 | + role: str # user or bot |
| 20 | + botId: Optional[str] = Field(alias="bot", default=None) |
| 21 | + userId: Optional[str] = Field(alias="user", default=None) |
| 22 | + text: str | None |
| 23 | + cot: str | None |
| 24 | + createdAt: str |
| 25 | + updatedAt: str |
| 26 | + |
| 27 | + class Config: |
| 28 | + populate_by_name = True |
| 29 | + extra = "ignore" |
| 30 | + |
| 31 | + |
| 32 | +class Conversation(BaseModel): |
| 33 | + agent_id: str |
| 34 | + id: str = Field(alias="_id") |
| 35 | + title: Optional[str] = Field(default=None) # conversation customized title |
| 36 | + users: List[str] |
| 37 | + agents: List[str] = Field(alias="bots") |
| 38 | + createdAt: Optional[str] |
| 39 | + updatedAt: Optional[str] |
| 40 | + |
| 41 | + class Config: |
| 42 | + populate_by_name = True |
| 43 | + extra = "ignore" |
| 44 | + |
| 45 | + def __init__(self, **data): |
| 46 | + super().__init__(**data) |
| 47 | + |
| 48 | + def new_conversation(self) -> "Conversation": |
| 49 | + url = f"https://api.agentx.so/api/v1/access/agents/{self.agent_id}/conversations/new" |
| 50 | + response = requests.post( |
| 51 | + url, |
| 52 | + headers=get_headers(), |
| 53 | + json={"type": "chat"}, |
| 54 | + ) |
| 55 | + if response.status_code == 200: |
| 56 | + new_conv = response.json() |
| 57 | + new_conv["agent_id"] = self.agent_id |
| 58 | + return Conversation(**new_conv) |
| 59 | + else: |
| 60 | + raise Exception( |
| 61 | + f"Failed to create new conversation: {response.status_code} - {response.reason}" |
| 62 | + ) |
| 63 | + |
| 64 | + def list_messages(self) -> List[Message]: |
| 65 | + url = f"https://api.agentx.so/api/v1/access/agents/{self.agent_id}/conversations/{self.id}" |
| 66 | + response = requests.get(url, headers=get_headers()) |
| 67 | + if response.status_code == 200: |
| 68 | + res = response.json() |
| 69 | + if res.get("messages"): |
| 70 | + message_list = [] |
| 71 | + for message in res["messages"]: |
| 72 | + if message.get("bot"): |
| 73 | + message["role"] = "bot" |
| 74 | + else: |
| 75 | + message["role"] = "user" |
| 76 | + message_list.append(Message(**message)) |
| 77 | + return message_list |
| 78 | + else: |
| 79 | + raise Exception("No messages found in the conversation.") |
| 80 | + else: |
| 81 | + raise Exception( |
| 82 | + f"Failed to retrieve agent details: {response.status_code} - {response.reason}" |
| 83 | + ) |
| 84 | + |
| 85 | + def chat(self, message: str, context: int = None): |
| 86 | + url = f"https://api.agentx.so/api/v1/access/conversations/{self.id}/message" |
| 87 | + response = requests.post( |
| 88 | + url, |
| 89 | + headers=get_headers(), |
| 90 | + json={"message": message, "context": context}, |
| 91 | + ) |
| 92 | + return response.json() |
| 93 | + |
| 94 | + def chat_stream(self, message: str, context: int = None) -> Iterator[ChatResponse]: |
| 95 | + url = f"https://api.agentx.so/api/v1/access/conversations/{self.id}/jsonmessagesse" |
| 96 | + response = requests.post( |
| 97 | + url, headers=get_headers(), json={"message": message, "context": context} |
| 98 | + ) |
| 99 | + result = "" |
| 100 | + if response.status_code == 200: |
| 101 | + buf = b"" |
| 102 | + for chunk in response.iter_content(): |
| 103 | + buf += chunk |
| 104 | + try: |
| 105 | + chunk = buf.decode("utf-8") |
| 106 | + # yield chunk |
| 107 | + except UnicodeDecodeError: |
| 108 | + continue |
| 109 | + result += chunk |
| 110 | + buf = b"" |
| 111 | + try: |
| 112 | + if result.count("{") == result.count("}"): |
| 113 | + catch_json = json.loads(result) |
| 114 | + if catch_json: |
| 115 | + result = "" |
| 116 | + yield ChatResponse( |
| 117 | + text=catch_json.get("text"), |
| 118 | + cot=catch_json.get("cot"), |
| 119 | + botId=catch_json.get("botId"), |
| 120 | + reference=catch_json.get("reference"), |
| 121 | + tasks=catch_json.get("tasks"), |
| 122 | + ) |
| 123 | + except json.JSONDecodeError: |
| 124 | + continue |
| 125 | + else: |
| 126 | + raise Exception( |
| 127 | + f"Failed to send message: {response.status_code} - {response.reason}" |
| 128 | + ) |
0 commit comments