Skip to content

Commit

Permalink
chore: Modified the documentation and updated the resources with the …
Browse files Browse the repository at this point in the history
…same name under different modules
  • Loading branch information
chyroc committed Sep 26, 2024
1 parent 94a90d3 commit 6c28294
Show file tree
Hide file tree
Showing 9 changed files with 111 additions and 92 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@
__pycache__/
dist/
debug.*
.env
.env_private
84 changes: 49 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,54 +10,36 @@ pip install cozepy

### Auth

```python
from cozepy import Coze, TokenAuth, JWTAuth
#### Personal Auth Token

# use pat or oauth token as auth
cli = Coze(auth=TokenAuth("your_token"))
create Personal Auth Token at [扣子](https://www.coze.cn/open/oauth/pats) or [Coze Platform](https://www.coze.com/open/oauth/pats)

# use application jwt auth flow as auth
cli = Coze(auth=JWTAuth("your_client_id", "your_private_key", "your_key_id"))
```

### Bots
and user `TokenAuth` to init Coze client.

```python
from cozepy import Coze, TokenAuth

# use pat or oauth token as auth
cli = Coze(auth=TokenAuth("your_token"))
```

# retrieve bot info
bot = cli.bots.retrieve(bot_id='bot id')
#### JWT OAuth App

# list bot list
bots_page = cli.bots.list(space_id='space id', page_num=1)
bots = bots_page.items
create JWT OAuth App at [扣子](https://www.coze.cn/open/oauth/apps) or [Coze Platform](https://www.coze.com/open/oauth/apps)

# create bot
bot = cli.bots.create(
space_id='space id',
name='bot name',
description='bot description',
)

# update bot info
cli.bots.update(
bot_id='bot id',
name='bot name',
description='bot description',
)
```python
from cozepy import Coze, JWTAuth

# delete bot
bot = cli.bots.publish(bot_id='bot id')
# use application jwt auth flow as auth
cli = Coze(auth=JWTAuth("your_client_id", "your_private_key", "your_key_id"))
```

### Chat

```python
import time

from cozepy import Coze, TokenAuth, Event, ChatStatus, Message
from cozepy import Coze, TokenAuth, ChatEventType, ChatStatus, Message

cli = Coze(auth=TokenAuth("your_token"))

Expand Down Expand Up @@ -94,10 +76,42 @@ chat_iterator = cli.chat.stream(
],
)
for event in chat_iterator:
if event.event == Event.conversation_message_delta:
if event.event == ChatEventType.conversation_message_delta:
print('got message delta:', event.messages.content)
```

### Bots

```python
from cozepy import Coze, TokenAuth

cli = Coze(auth=TokenAuth("your_token"))

# retrieve bot info
bot = cli.bots.retrieve(bot_id='bot id')

# list bot list
bots_page = cli.bots.list(space_id='space id', page_num=1)
bots = bots_page.items

# create bot
bot = cli.bots.create(
space_id='space id',
name='bot name',
description='bot description',
)

# update bot info
cli.bots.update(
bot_id='bot id',
name='bot name',
description='bot description',
)

# delete bot
bot = cli.bots.publish(bot_id='bot id')
```

### Conversations

```python
Expand Down Expand Up @@ -158,7 +172,7 @@ cli.files.retrieve(file_id=file.id)
### Workflows

```python
from cozepy import Coze, TokenAuth, Event, WorkflowEventIterator
from cozepy import Coze, TokenAuth, WorkflowEventType, WorkflowEventIterator

cli = Coze(auth=TokenAuth("your_token"))

Expand All @@ -174,11 +188,11 @@ result = cli.workflows.runs.create(
# stream workflow run
def handle_workflow_iterator(iterator: WorkflowEventIterator):
for event in iterator:
if event.event == Event.message:
if event.event == WorkflowEventType.message:
print('got message', event.message)
elif event.event == Event.error:
elif event.event == WorkflowEventType.error:
print('got error', event.error)
elif event.event == Event.interrupt:
elif event.event == WorkflowEventType.interrupt:
handle_workflow_iterator(cli.workflows.runs.resume(
workflow_id='workflow id',
event_id=event.interrupt.interrupt_data.event_id,
Expand Down
28 changes: 14 additions & 14 deletions cozepy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
MessageContentType,
MessageObjectStringType,
ChatStatus,
Event,
MessageObjectString,
Message,
Chat,
ChatEventType,
ChatEvent,
ChatIterator,
ChatChatIterator,
)
from .config import COZE_COM_BASE_URL, COZE_CN_BASE_URL
from .conversations import Conversation
Expand All @@ -24,11 +24,11 @@
)
from .workflows.runs import (
WorkflowRunResult,
Event,
EventMessage,
EventInterruptData,
EventInterrupt,
EventError,
WorkflowEventType,
WorkflowEventMessage,
WorkflowEventInterruptData,
WorkflowEventInterrupt,
WorkflowEventError,
WorkflowEvent,
WorkflowEventIterator,
)
Expand Down Expand Up @@ -56,23 +56,23 @@
"MessageContentType",
"MessageObjectStringType",
"ChatStatus",
"Event",
"ChatEventType",
"MessageObjectString",
"Message",
"Chat",
"ChatEvent",
"ChatIterator",
"ChatChatIterator",
# conversations
"Conversation",
# files
"File",
# workflows.runs
"WorkflowRunResult",
"Event",
"EventMessage",
"EventInterruptData",
"EventInterrupt",
"EventError",
"WorkflowEventType",
"WorkflowEventMessage",
"WorkflowEventInterruptData",
"WorkflowEventInterrupt",
"WorkflowEventError",
"WorkflowEvent",
"WorkflowEventIterator",
# workspaces
Expand Down
28 changes: 14 additions & 14 deletions cozepy/chat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ class Chat(CozeModel):
# Details of the information needed for execution.


class Event(str, Enum):
class ChatEventType(str, Enum):
# Event for creating a conversation, indicating the start of the conversation.
# 创建对话的事件,表示对话开始。
conversation_chat_created = "conversation.chat.created"
Expand Down Expand Up @@ -218,12 +218,12 @@ class Event(str, Enum):


class ChatEvent(CozeModel):
event: Event
event: ChatEventType
chat: Chat = None
message: Message = None


class ChatIterator(object):
class ChatChatIterator(object):
def __init__(self, iters: Iterator[bytes]):
self._iters = iters

Expand Down Expand Up @@ -255,18 +255,18 @@ def __next__(self) -> ChatEvent:

times += 1

if event == Event.done:
if event == ChatEventType.done:
raise StopIteration
elif event == Event.error:
elif event == ChatEventType.error:
raise Exception(f"error event: {line}")
elif event in [Event.conversation_message_delta, Event.conversation_message_completed]:
elif event in [ChatEventType.conversation_message_delta, ChatEventType.conversation_message_completed]:
return ChatEvent(event=event, message=Message.model_validate(json.loads(data)))
elif event in [
Event.conversation_chat_created,
Event.conversation_chat_in_progress,
Event.conversation_chat_completed,
Event.conversation_chat_failed,
Event.conversation_chat_requires_action,
ChatEventType.conversation_chat_created,
ChatEventType.conversation_chat_in_progress,
ChatEventType.conversation_chat_completed,
ChatEventType.conversation_chat_failed,
ChatEventType.conversation_chat_requires_action,
]:
return ChatEvent(event=event, chat=Chat.model_validate(json.loads(data)))
else:
Expand Down Expand Up @@ -316,7 +316,7 @@ def stream(
auto_save_history: bool = True,
meta_data: Dict[str, str] = None,
conversation_id: str = None,
) -> ChatIterator:
) -> ChatChatIterator:
"""
Create a conversation.
Conversation is an interaction between a bot and a user, including one or more messages.
Expand All @@ -343,7 +343,7 @@ def _create(
auto_save_history: bool = True,
meta_data: Dict[str, str] = None,
conversation_id: str = None,
) -> Union[Chat, ChatIterator]:
) -> Union[Chat, ChatChatIterator]:
"""
Create a conversation.
Conversation is an interaction between a bot and a user, including one or more messages.
Expand All @@ -362,7 +362,7 @@ def _create(
if not stream:
return self._requester.request("post", url, Chat, body=body, stream=stream)

return ChatIterator(self._requester.request("post", url, Chat, body=body, stream=stream))
return ChatChatIterator(self._requester.request("post", url, Chat, body=body, stream=stream))

def retrieve(
self,
Expand Down
34 changes: 17 additions & 17 deletions cozepy/workflows/runs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class WorkflowRunResult(CozeModel):
data: str


class Event(str, Enum):
class WorkflowEventType(str, Enum):
# The output message from the workflow node, such as the output message from
# the message node or end node. You can view the specific message content in data.
# 工作流节点输出消息,例如消息节点、结束节点的输出消息。可以在 data 中查看具体的消息内容。
Expand All @@ -32,7 +32,7 @@ class Event(str, Enum):
interrupt = "Interrupt"


class EventMessage(CozeModel):
class WorkflowEventMessage(CozeModel):
# The content of the streamed output message.
# 流式输出的消息内容。
content: str
Expand All @@ -54,7 +54,7 @@ class EventMessage(CozeModel):
ext: Dict[str, Any] = None


class EventInterruptData(CozeModel):
class WorkflowEventInterruptData(CozeModel):
# The workflow interruption event ID, which should be passed back when resuming the workflow.
# 工作流中断事件 ID,恢复运行时应回传此字段。
event_id: str
Expand All @@ -64,17 +64,17 @@ class EventInterruptData(CozeModel):
type: int


class EventInterrupt(CozeModel):
class WorkflowEventInterrupt(CozeModel):
# The content of interruption event.
# 中断控制内容。
interrupt_data: EventInterruptData
interrupt_data: WorkflowEventInterruptData

# The name of the node that outputs the message, such as "Question".
# 输出消息的节点名称,例如“问答”。
node_title: str


class EventError(CozeModel):
class WorkflowEventError(CozeModel):
# Status code. 0 represents a successful API call. Other values indicate that the call has failed. You can determine the detailed reason for the error through the error_message field.
# 调用状态码。0 表示调用成功。其他值表示调用失败。你可以通过 error_message 字段判断详细的错误原因。
error_code: int
Expand All @@ -89,13 +89,13 @@ class WorkflowEvent(CozeModel):
id: int

# The current streaming data packet event.
event: Event
event: WorkflowEventType

message: EventMessage = None
message: WorkflowEventMessage = None

interrupt: EventInterrupt = None
interrupt: WorkflowEventInterrupt = None

error: EventError = None
error: WorkflowEventError = None


class WorkflowEventIterator(object):
Expand Down Expand Up @@ -136,14 +136,14 @@ def __next__(self) -> WorkflowEvent:

times += 1

if event == Event.done:
if event == WorkflowEventType.done:
raise StopIteration
elif event == Event.message:
return WorkflowEvent(id=id, event=event, message=EventMessage.model_validate_json(data))
elif event == Event.error:
return WorkflowEvent(id=id, event=event, error=EventError.model_validate_json(data))
elif event == Event.interrupt:
return WorkflowEvent(id=id, event=event, interrupt=EventInterrupt.model_validate_json(data))
elif event == WorkflowEventType.message:
return WorkflowEvent(id=id, event=event, message=WorkflowEventMessage.model_validate_json(data))
elif event == WorkflowEventType.error:
return WorkflowEvent(id=id, event=event, error=WorkflowEventError.model_validate_json(data))
elif event == WorkflowEventType.interrupt:
return WorkflowEvent(id=id, event=event, interrupt=WorkflowEventInterrupt.model_validate_json(data))
else:
raise Exception(f"unknown event: {line}")

Expand Down
6 changes: 3 additions & 3 deletions cozepy/workspaces/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from enum import StrEnum
from enum import Enum
from typing import List

from cozepy import NumberPaged
Expand All @@ -7,13 +7,13 @@
from cozepy.request import Requester


class WorkspaceRoleType(StrEnum):
class WorkspaceRoleType(str, Enum):
owner = "owner"
admin = "admin"
member = "member"


class WorkspaceType(StrEnum):
class WorkspaceType(str, Enum):
personal = "personal"
team = "team"

Expand Down
Loading

0 comments on commit 6c28294

Please sign in to comment.