Skip to content

Commit fe9e5d4

Browse files
committed
update stream
1 parent 0fa501c commit fe9e5d4

File tree

12 files changed

+176
-79
lines changed

12 files changed

+176
-79
lines changed

README.md

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,22 @@
1-
# AgentX Python SDK API library
1+
![Logo](https://agentx-resources.s3.us-west-1.amazonaws.com/AgentX-logo-387x60.png)
22

33
[![PyPI version](https://img.shields.io/pypi/v/agentx-python)](https://pypi.org/project/agentx-python/)
44

5-
The AgentX Python SDK provides a convenient way to access to your Agent programmatically.
6-
This is a python SDK for AgentX (https://www.agentx.so/)
5+
---
6+
7+
## Fast way to build AI Agents and create agent workforce
8+
9+
The official AgentX Python SDK for [AgentX](https://www.agentx.so/)
10+
11+
Why build AI agent with AgentX?
12+
13+
- Simplicity, Agent - Conversation - Message structure.
14+
- Include chain-of-thoughts.
15+
- Choose from most open and closed sourced LLM vendors.
16+
- Built-in Voice(ASR, TTS), Image Gen, Document, CSV/excel tool, OCR, etc.
17+
- Support all running MCP (model context protocol).
18+
- Support RAG with built-in re-rank.
19+
- Multi-agent workforce orchestration.
720

821
## Installation
922

@@ -19,7 +32,7 @@ You can get an API key from https://app.agentx.so
1932
### Agent
2033

2134
```python
22-
from agentx_python import AgentX
35+
from agentx import AgentX
2336

2437
client = AgentX(api_key="<your api key here>")
2538

@@ -36,7 +49,13 @@ Each Conversation has `agents` and `users` tied to it.
3649
my_agent = client.get_agent(id="<agent id here>")
3750

3851
# Get the list of conversation from this agent
39-
print(my_agent.list_conversations())
52+
existing_conversations = my_agent.list_conversations()
53+
print(existing_conversations)
54+
55+
# Get the list of history messages from a conversation
56+
last_conversation = existing_conversations[-1]
57+
msgs = last_conversation.list_messages()
58+
print(msgs)
4059
```
4160

4261
### Chat
@@ -46,10 +65,23 @@ A `chat` needs to happen in the conversation. You can do `stream` response too,
4665
```python
4766
a_conversation = my_agent.get_conversation(id="<conversation id here>")
4867

49-
response = a_conversation.chat("Hello, what is your name?", stream=True)
68+
response = a_conversation.chat_stream("Hello, what is your name?")
5069
for chunk in response:
51-
print(chunk, end="")
70+
print(chunk)
71+
```
72+
73+
output looks like:
5274

53-
# output:
54-
# My name is Rosita. I'm an AI assistant created by AgentX. It's nice to meet you! How can I help you today?
5575
```
76+
text=None cot='The user is greeting and asking for my ' botId='xxx'
77+
text=None cot='name, which are casual, straightforward questions.' botId='xxx'
78+
text=None cot=' I can answer these directly' botId='xxx'
79+
text='Hello' cot=None botId='xxx'
80+
text='!' cot=None botId='xxx'
81+
text=' I' cot=None botId='xxx'
82+
text=' am' cot=None botId='xxx'
83+
text=' AgentX' cot=None botId='xxx'
84+
text=None cot=None botId='xxx'
85+
```
86+
87+
\*`cot` stands for chain-of-thoughts

agentx_python/__init__.py renamed to agentx/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import logging
22

3-
from agentx_python.agentx import AgentX
4-
from agentx_python.version import VERSION
3+
from agentx.agentx import AgentX
4+
from agentx.version import VERSION
55

66
logging.basicConfig(
77
level=logging.INFO,

agentx_python/agentx.py renamed to agentx/agentx.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
import os
44
import logging
55

6-
from agentx_python.util import get_headers
7-
from agentx_python.resources.agent import Agent
6+
from agentx.util import get_headers
7+
from agentx.resources.agent import Agent
88

99

1010
class AgentX:

agentx/images/LOGO.png

4.75 KB
Loading
File renamed without changes.

agentx_python/resources/agent.py renamed to agentx/resources/agent.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import os
55
import logging
66
from dataclasses import dataclass
7-
from agentx_python.util import get_headers
7+
from agentx.util import get_headers
88
from .conversation import Conversation
99

1010

agentx/resources/conversation.py

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
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+
)
File renamed without changes.

agentx/version.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
VERSION = "0.3.0"

agentx_python/resources/conversation.py

Lines changed: 0 additions & 63 deletions
This file was deleted.

0 commit comments

Comments
 (0)