-
Notifications
You must be signed in to change notification settings - Fork 416
/
api_client.py
172 lines (162 loc) · 5.84 KB
/
api_client.py
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
from typing import Any
import webbrowser
import httpx
from pydantic import BaseModel
import requests
import json
from loguru import logger
from sweepai.app.config import SweepChatConfig
from sweepai.core.entities import Function, PullRequest, Snippet
from sweepai.utils.constants import PREFIX
create_pr_function = Function(
name="create_pr",
description="Creates a PR.",
parameters={
"properties": {
"plan": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The file path to change."
},
"instructions": {
"type": "string",
"description": "Concise NATURAL LANGUAGE summary of what to change in each file. There should be absolutely NO code, only English.",
"example": [
"Refactor the algorithm by moving the main function to the top of the file.",
"Change the implementation to recursion"
]
},
},
"required": ["file_path", "instructions"]
},
"description": "A list of files to modify or create and corresponding instructions."
},
"title": {
"type": "string",
"description": "Title of PR",
},
"summary": {
"type": "string",
"description": "Detailed summary of PR",
},
"branch": {
"type": "string",
"description": "Name of branch to create PR in.",
},
},
"required": ["plan", "title", "summary", "branch"]
}
)
create_pr_function_call = {"name": "create_pr"}
def break_json(raw_json: str):
# turns something like {"function_call": {"arguments": " \""}}{"function_call": {"arguments": "summary"}} into two objects
try:
yield json.loads(raw_json)
except json.JSONDecodeError:
for i in range(1, len(raw_json)):
try:
obj = json.loads(raw_json[:i])
yield obj
for item in break_json(raw_json[i:]):
yield item
break
except json.JSONDecodeError:
pass
class APIClient(BaseModel):
config: SweepChatConfig
api_endpoint: str = f"https://sweepai--{PREFIX}-ui.modal.run"
def get_installation_id(self):
results = requests.post(
self.api_endpoint + "/installation_id",
json= self.config.dict(),
)
if results.status_code == 401:
print("Installation ID not found! Please install sweep first.")
webbrowser.open_new_tab("https://github.com/apps/sweep-ai")
raise Exception(results.json()["detail"])
if results.status_code != 200:
raise Exception(results.json()["detail"])
obj = results.json()
return obj["installation_id"]
def search(
self,
query: str,
n_results: int = 5,
):
results = requests.post(
self.api_endpoint + "/search",
json={
"query": query,
"n_results": n_results,
"config": self.config.dict(),
}
)
if results.status_code != 200:
raise Exception(results.text)
snippets = [Snippet(**item) for item in results.json()]
return snippets
def create_pr(
self,
file_change_requests: list[tuple[str, str]],
pull_request: PullRequest,
messages: list[tuple[str | None, str | None]],
):
results = requests.post(
self.api_endpoint + "/create_pr",
json={
"file_change_requests": file_change_requests,
"pull_request": pull_request,
"messages": messages,
"config": self.config.dict(),
},
timeout=10 * 60
)
return results.json()
def chat(
self,
messages: list[tuple[str | None, str | None]],
snippets: list[Snippet] = [],
model: str = "gpt-4-0613",
) -> str:
results = requests.post(
self.api_endpoint + "/chat",
json={
"messages": messages,
"snippets": [snippet.dict() for snippet in snippets],
"config": self.config.dict()
}
)
return results.json()
def stream_chat(
self,
messages: list[tuple[str | None, str | None]],
snippets: list[Snippet] = [],
functions: list[Function] = [],
function_call: Any = "auto",
model: str = "gpt-4-0613"
):
with httpx.Client(timeout=30) as client: # sometimes this step is slow
with client.stream(
'POST',
self.api_endpoint + '/chat_stream',
json={
"messages": messages,
"snippets": [snippet.dict() for snippet in snippets],
"functions": [func.dict() for func in functions],
"function_call": function_call,
"config": self.config.dict()
}
) as response:
for delta_chunk in response.iter_text():
if not delta_chunk:
break
try:
for item in break_json(delta_chunk):
yield item
except json.decoder.JSONDecodeError as e:
logger.error(delta_chunk)
raise e