Comments (5)
@psymbio Have you checked out the existing methods for streaming response data in our documentation?
from urllib3.
Closing due to lack of activity, I think this question has been answered.
from urllib3.
Sorry for the delay in response @sethmlarson
Yes, I've looked at the documentation and written the following code:
import micropip
await micropip.install('https://raw.githubusercontent.com/psymbio/pyodide_wheels/main/multidict/multidict-4.7.6-py3-none-any.whl', keep_going=True)
await micropip.install('https://raw.githubusercontent.com/psymbio/pyodide_wheels/main/frozenlist/frozenlist-1.4.0-py3-none-any.whl', keep_going=True)
await micropip.install('https://raw.githubusercontent.com/psymbio/pyodide_wheels/main/aiohttp/aiohttp-3.9.1-py3-none-any.whl', keep_going=True)
await micropip.install('https://raw.githubusercontent.com/psymbio/pyodide_wheels/main/openai/openai-1.3.7-py3-none-any.whl', keep_going=True)
await micropip.install('https://raw.githubusercontent.com/psymbio/pyodide_wheels/main/urllib3/urllib3-2.1.0-py3-none-any.whl', keep_going=True)
await micropip.install("ssl")
import ssl
await micropip.install("httpx", keep_going=True)
import httpx
await micropip.install('https://raw.githubusercontent.com/psymbio/pyodide_wheels/main/urllib3/urllib3-2.1.0-py3-none-any.whl', keep_going=True)
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import json
class URLLib3Stream(httpx.SyncByteStream):
def __init__(self, stream):
self._stream = stream
def __iter__(self):
# print(self._stream)
# print(dir(self._stream))
# print(self._stream.__self__)
# print(dir(self._stream.__self__))
print(self._stream.__self__.data)
with httpx._transports.default.map_httpcore_exceptions():
for part in self._stream:
yield part
def close(self):
if hasattr(self._stream, "close"):
self._stream.close()
class URLLib3Transport(httpx.BaseTransport):
def __init__(self):
# self._pool = urllib3.PoolManager()
self._pool = urllib3.connectionpool.ConnectionPool(host="localhost")
def handle_request(self, request: httpx.Request):
payload = json.loads(request.content.decode("utf-8").replace("'",'"'))
urllib3_response = urllib3.request(
method=request.method,
url=str(request.url),
headers=request.headers,
json=payload,
# stream=True,
preload_content=False
)
headers = [(b"content-type", b"application/json")]
return httpx.Response(
200,
headers=headers,
stream=URLLib3Stream(urllib3_response.stream)
)
client = httpx.Client(transport=URLLib3Transport())
from openai import OpenAI
from openai import AzureOpenAI
import openai
import os
os.environ['AZURE_OPENAI_API_KEY'] = "xxx"
openai_client = AzureOpenAI(
api_version="2023-07-01-preview",
azure_endpoint="https://xxx.openai.azure.com/",
http_client=client
)
response = openai_client.chat.completions.with_raw_response.create(
messages=[{
"role": "user",
"content": "sing me a song",
}],
model="gpt-35-turbo",
max_tokens=30,
temperature=0.7,
# stream=True
)
completion = response.parse()
print(completion)
but seeing the output from this part of the code:
class URLLib3Stream(httpx.SyncByteStream):
def __init__(self, stream):
self._stream = stream
def __iter__(self):
print(self._stream.__self__.data)
with httpx._transports.default.map_httpcore_exceptions():
for part in self._stream:
yield part
def close(self):
if hasattr(self._stream, "close"):
self._stream.close()
Gives me three different responses for a single request:
b'{"id":"chatcmpl-8ucZ1UsLPxKy6SMYpE1JkJ4SsaSwT","object":"chat.completion","created":1708505299,"model":"gpt-35-turbo","prompt_filter_results":[{"prompt_index":0,"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"choices":[{"finish_reason":"stop","index":0,"message":{"role":"assistant","content":"I can\'t sing, but I can certainly help you find a song to listen to! What kind of music are you in the mood for?"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":{"prompt_tokens":11,"completion_tokens":29,"total_tokens":40},"system_fingerprint":"fp_68a7d165bf"}\n'
b'{"id":"chatcmpl-8ucZ2tRwvhcyTgINUlrsZScHuWIXu","object":"chat.completion","created":1708505300,"model":"gpt-35-turbo","prompt_filter_results":[{"prompt_index":0,"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"choices":[{"finish_reason":"length","index":0,"message":{"role":"assistant","content":"I\'m just a digital assistant, so I can\'t sing, but I can certainly help you find the lyrics to a song or recommend some good tunes"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":{"prompt_tokens":11,"completion_tokens":30,"total_tokens":41},"system_fingerprint":"fp_68a7d165bf"}\n'
b'{"id":"chatcmpl-8ucZ5to0cm2ZVFGtIDK9RcvuN3iRL","object":"chat.completion","created":1708505303,"model":"gpt-35-turbo","prompt_filter_results":[{"prompt_index":0,"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"choices":[{"finish_reason":"length","index":0,"message":{"role":"assistant","content":"I\'m just a virtual assistant, so I can\'t sing, but I can help you find the lyrics to a song or recommend some music for you"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":{"prompt_tokens":11,"completion_tokens":30,"total_tokens":41},"system_fingerprint":"fp_68a7d165bf"}\n'
Not completely sure how to resolve this - because it's not working as intended.
from urllib3.
@psymbio Have you found out the way? I am searching for the same solution.
from urllib3.
No, not really - I'm not sure why streaming isn't working here.
@tomchristie can you have a quick glance at this
from urllib3.
Related Issues (20)
- urllib3 2.2 explicitly casts all headers to HTTPHeaderDict HOT 4
- verbose logging output
- Excess leading path separators causes ConnectionPool.urlopen to parse URL as host & port HOT 4
- ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')) HOT 1
- SSL: UNEXPECTED_EOF_WHILE_READING HOT 7
- imprecise types on `urllib3.Retry.new` / `urllib3.Retry.increment` HOT 1
- Investigate CI failures with Python 3.13.0a5 HOT 2
- "unable to get local issuer certificate", even though cURL works with the same website HOT 3
- Unclosed socket warning after HTTP 407 response from HTTP CONNECT proxy HOT 1
- All Retry backoff_factor to optionally start applying from first retry HOT 4
- Retry backoff_factor offset from second retry incorrectly computed HOT 2
- HTTPConnection.request chunked=False doesn't work properly HOT 8
- Need to exception for "SSLEOFError" on python 3.10, 3.11, 3.12 HOT 3
- After upgrading to 2.2.1: 'HTTPResponse' object has no attribute 'json' HOT 1
- Comment typo settimout settimeout HOT 1
- Dependency management issue HOT 2
- Fix test_redirecting_to_bad_url failure in Requests HOT 12
- NodeJS + pyodide support HOT 1
- Retry.respect_retry_after_header=False is not honored when retry is incremented HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from urllib3.