Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(agents-api): New chat context query and model #437

Merged
merged 44 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
fc34ce3
feat(typespec): Add initial typespec definitions
Jul 11, 2024
8806f76
Merge branch 'dev-tasks' into f/typespec
Jul 12, 2024
2d6f6b8
feat(typespec): Add Tasks typespec
Jul 12, 2024
0381586
feat(typespec): Add Executions typespec
Jul 12, 2024
787d654
feat: Add session token budget and context overflow
whiterabbit1983 Jul 13, 2024
a56bbbe
fix(typespec): Minor spec fixes
Jul 14, 2024
a88ab44
feat(typespec): Add name field to Tool
Jul 14, 2024
5157c44
Merge branch 'dev-tasks' into f/typespec
Jul 14, 2024
c5414e0
refactor(typespec): Minor refactors to common/ utils
Jul 14, 2024
955f8b9
feat(typespec): Add search endpoints
Jul 14, 2024
6373794
feat(typespec): Add multi-agent multi-user sessions, add template for…
Jul 15, 2024
63ba26f
refactor: Remove mock_openapi.yaml and link openapi.yaml to the types…
Jul 15, 2024
aa4da04
feat: Codegen for all new typespec stuff
Jul 15, 2024
cc54e26
feat(fern): Upgrade fern and fern-python
Jul 15, 2024
d54bca3
feat(typespec): Various changes to the spec
Jul 18, 2024
f9ce313
Merge branch 'f/typespec' into f/typespec-codegen
Jul 18, 2024
b2f5808
fix(typespec): Fix docstrings
Jul 20, 2024
2676f6d
wip
Jul 20, 2024
14bee99
wip
Jul 20, 2024
b652995
fix(agents-api): Fix datamodel-codegen options
Jul 20, 2024
2406fe8
fix(typespec): Misc fixes
Jul 22, 2024
c3bc32c
feat(agents-api): Add migrations for updated typespec models
Jul 22, 2024
059f94b
wip
Jul 22, 2024
b9c6a82
wip
Jul 22, 2024
67a0fff
feat(agents-api): Add migrations for developers relations and renamin…
Jul 22, 2024
59462d2
wip
Jul 22, 2024
ac3fcec
wip
Jul 22, 2024
99d5e9e
wip
Jul 22, 2024
752fbaf
fix(agents-api): Update agent/tool models
Jul 23, 2024
9bb58c3
wip
Jul 25, 2024
c31f563
wip
Jul 26, 2024
027faca
wip
Jul 26, 2024
fdfb94b
wip
Jul 26, 2024
c4bac6c
wip
Jul 26, 2024
b8f8992
wip
Jul 28, 2024
4428ed9
wip
Jul 28, 2024
e5aac60
reformat evthing
Jul 28, 2024
1bd6bf2
wip
Jul 29, 2024
d18f7da
wip
Jul 29, 2024
f184863
Merge branch 'dev-tasks' into f/typespec-codegen
Jul 29, 2024
4fc719d
wup
Jul 29, 2024
4921f44
history
Jul 30, 2024
de2e885
feat(agents-api): New chat context query and model
Jul 30, 2024
9c2a316
Merge branch 'dev-tasks' into f/typespec-codegen
Jul 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 44 additions & 36 deletions agents-api/agents_api/autogen/Entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,48 @@
from .Tools import ChosenToolCall, Tool, ToolResponse


class BaseEntry(BaseModel):
model_config = ConfigDict(
populate_by_name=True,
)
role: Literal[
"user",
"agent",
"system",
"function",
"function_response",
"function_call",
"auto",
]
"""
ChatML role (system|assistant|user|function_call|function|function_response|auto)
"""
name: str | None = None
content: (
list[ChatMLTextContentPart | ChatMLImageContentPart]
| Tool
| ChosenToolCall
| str
| ToolResponse
| list[
list[ChatMLTextContentPart | ChatMLImageContentPart]
| Tool
| ChosenToolCall
| str
| ToolResponse
]
)
source: Literal[
"api_request", "api_response", "tool_response", "internal", "summarizer", "meta"
]
tokenizer: str | None = None
token_count: int | None = None
timestamp: Annotated[float, Field(ge=0.0)]
"""
This is the time that this event refers to.
"""


class ChatMLImageContentPart(BaseModel):
model_config = ConfigDict(
populate_by_name=True,
Expand Down Expand Up @@ -73,44 +115,10 @@ class ChatMLTextContentPart(BaseModel):
"""


class Entry(BaseModel):
class Entry(BaseEntry):
model_config = ConfigDict(
populate_by_name=True,
)
role: Literal[
"user",
"agent",
"system",
"function",
"function_response",
"function_call",
"auto",
]
"""
ChatML role (system|assistant|user|function_call|function|function_response|auto)
"""
name: str | None = None
content: (
list[ChatMLTextContentPart | ChatMLImageContentPart]
| Tool
| ChosenToolCall
| str
| ToolResponse
| list[
list[ChatMLTextContentPart | ChatMLImageContentPart]
| Tool
| ChosenToolCall
| str
| ToolResponse
]
)
source: Literal[
"api_request", "api_response", "tool_response", "internal", "summarizer", "meta"
]
timestamp: Annotated[float, Field(ge=0.0)]
"""
This is the time that this event refers to.
"""
created_at: Annotated[AwareDatetime, Field(json_schema_extra={"readOnly": True})]
"""
When this resource was created as UTC date-time
Expand All @@ -122,7 +130,7 @@ class History(BaseModel):
model_config = ConfigDict(
populate_by_name=True,
)
entries: list[Entry]
entries: list[BaseEntry]
relations: list[Relation]
session_id: Annotated[UUID, Field(json_schema_extra={"readOnly": True})]
created_at: Annotated[AwareDatetime, Field(json_schema_extra={"readOnly": True})]
Expand Down
10 changes: 4 additions & 6 deletions agents-api/agents_api/autogen/openapi_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,13 @@
"metadata",
)

ChatMLRole = Entry.model_fields["role"].annotation
ChatMLRole = BaseEntry.model_fields["role"].annotation


class CreateEntryRequest(Entry):
id: Annotated[UUID | None, Field(default=None)]
created_at: Annotated[AwareDatetime | None, Field(default=None)]
class CreateEntryRequest(BaseEntry):
timestamp: Annotated[
float, Field(ge=0.0, default_factory=lambda: utcnow().timestamp())
]
tokenizer: str
token_count: int


def make_session(
Expand Down Expand Up @@ -72,3 +68,5 @@ def make_session(
case _:
cls = MultiAgentMultiUserSession
participants = {"agents": agents, "users": users}

return cls(**{**data, **participants})
5 changes: 2 additions & 3 deletions agents-api/agents_api/common/protocol/entries.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import json
from typing import Literal
from uuid import UUID, uuid4
from uuid import UUID

from pydantic import BaseModel, Field, computed_field
from pydantic import Field, computed_field

from ...autogen.openapi_model import (
ChatMLImageContentPart,
Expand All @@ -12,7 +12,6 @@
from ...autogen.openapi_model import (
Entry as BaseEntry,
)
from ...common.utils.datetime import utcnow

EntrySource = Literal["api_request", "api_response", "internal", "summarizer"]
Tokenizer = Literal["character_count"]
Expand Down
46 changes: 23 additions & 23 deletions agents-api/agents_api/common/protocol/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,18 @@
It includes definitions for session settings and session data models.
"""

from typing import Dict, Optional
from uuid import UUID
from typing import Optional

from pydantic import BaseModel

from ...autogen.openapi_model import (
Agent,
Entry,
Session,
Settings,
Tool,
User,
)
from .agents import AgentDefaultSettings


Expand All @@ -22,26 +29,19 @@ class SessionSettings(AgentDefaultSettings):

class SessionData(BaseModel):
"""
Represents the data associated with a session, including identifiers for the agent, user, and session itself,
along with session-specific information such as situation, summary, and timestamps.
Represents the data associated with a session, including for agents, and users.
"""

agent_id: UUID
user_id: Optional[UUID]
session_id: UUID
situation: str
summary: Optional[str]
user_name: Optional[str]
user_about: Optional[str]
agent_name: Optional[str]
agent_about: str
updated_at: float
created_at: float
model: str
default_settings: SessionSettings
render_templates: bool = False
metadata: Dict = {}
user_metadata: Optional[Dict] = None
agent_metadata: Dict = {}
token_budget: int | None = None
context_overflow: str | None = None
session: Session
agents: list[Agent]
users: list[User] = []
settings: Optional[Settings] = None


class ChatContext(SessionData):
"""
Represents the data associated with a context, including for agents, and users.
"""

entries: list[Entry]
tools: list[Tool]
4 changes: 2 additions & 2 deletions agents-api/agents_api/common/protocol/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
User,
YieldStep,
)
from ...models.execution.prepare_execution_data import get_execution_input_query
from ...models.execution.prepare_execution_data import prepare_execution_data
from ..utils.cozo import uuid_int_list_to_uuid4

WorkflowStep = (
Expand Down Expand Up @@ -117,7 +117,7 @@ class ExecutionInput(BaseModel):
def fetch(
cls, *, developer_id: UUID4, task_id: UUID4, execution_id: UUID4, client: Any
) -> "ExecutionInput":
[data] = get_execution_input_query(
[data] = prepare_execution_data(
task_id=task_id,
execution_id=execution_id,
client=client,
Expand Down
2 changes: 1 addition & 1 deletion agents-api/agents_api/models/agent/list_agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def list_agents(
developer_id: UUID,
limit: int = 100,
offset: int = 0,
sort_by: Literal["created_at", "updated_at", "deleted_at"] = "created_at",
sort_by: Literal["created_at", "updated_at"] = "created_at",
direction: Literal["asc", "desc"] = "desc",
metadata_filter: dict[str, Any] = {},
) -> tuple[str, dict]:
Expand Down
45 changes: 43 additions & 2 deletions agents-api/agents_api/models/entry/create_entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from pycozo.client import QueryException
from pydantic import ValidationError

from ...autogen.openapi_model import CreateEntryRequest, Entry
from ...autogen.openapi_model import CreateEntryRequest, Entry, Relation
from ...common.utils.cozo import cozo_process_mutate_data
from ...common.utils.datetime import utcnow
from ...common.utils.messages import content_to_json
Expand Down Expand Up @@ -39,7 +39,7 @@ def create_entries(
*,
developer_id: UUID,
session_id: UUID,
data: list[Entry],
data: list[CreateEntryRequest],
) -> tuple[str, dict]:
developer_id = str(developer_id)
session_id = str(session_id)
Expand Down Expand Up @@ -78,3 +78,44 @@ def create_entries(
query = f"{{ {query} }}"

return (query, {"rows": rows})


@rewrap_exceptions(
{
QueryException: partialclass(HTTPException, status_code=400),
ValidationError: partialclass(HTTPException, status_code=400),
TypeError: partialclass(HTTPException, status_code=400),
}
)
@wrap_in_class(Relation)
@cozo_query
@beartype
def add_entry_relations(
*,
developer_id: UUID,
data: list[Relation],
) -> tuple[str, dict]:
developer_id = str(developer_id)

data_dicts = [item.model_dump(mode="json") for item in data]
cols, rows = cozo_process_mutate_data(data_dicts)

create_query = f"""
?[{cols}] <- $rows

:insert relations {{
{cols}
}}

:returning
"""

queries = [
verify_developer_id_query(developer_id),
create_query,
]

query = "}\n\n{\n".join(queries)
query = f"{{ {query} }}"

return (query, {"rows": rows})
Loading
Loading